AppDelegate.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import "NCBridgeSwift.h"
  25. #import "NCAutoUpload.h"
  26. #import "NSNotificationCenter+MainThread.h"
  27. #import "NCPushNotification.h"
  28. #import <QuartzCore/QuartzCore.h>
  29. #import "CCUploadFromOtherUpp.h"
  30. @import Firebase;
  31. @class NCViewerRichdocument;
  32. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  33. @end
  34. @implementation AppDelegate
  35. + (void)initialize
  36. {
  37. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  38. }
  39. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  40. {
  41. BOOL isSimulatorOrTestFlight = [[NCUtility shared] isSimulatorOrTestFlight];
  42. if (![CCUtility getDisableCrashservice] && NCBrandOptions.shared.disable_crash_service == false) {
  43. [FIRApp configure];
  44. }
  45. [CCUtility createDirectoryStandard];
  46. [CCUtility emptyTemporaryDirectory];
  47. // Networking
  48. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  49. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent]];
  50. NSInteger logLevel = [CCUtility getLogLevel];
  51. [[NCCommunicationCommon shared] setFileLogWithLevel:logLevel];
  52. NSString *versionApp = [NSString stringWithFormat:@"%@.%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
  53. NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions shared].textCopyrightNextcloudiOS, versionApp];
  54. if (isSimulatorOrTestFlight) {
  55. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@ (Simulator / TestFlight)", (unsigned long)logLevel, versionNextcloudiOS]];
  56. } else {
  57. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@", (unsigned long)logLevel, versionNextcloudiOS]];
  58. }
  59. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:NCBrandGlobal.shared.notificationCenterInitializeMain object:nil];
  60. // Set account, if no exists clear all
  61. tableAccount *tableAccount = [[NCManageDatabase shared] getAccountActive];
  62. if (tableAccount == nil) {
  63. // remove all the keys Chain
  64. [CCUtility deleteAllChainStore];
  65. // remove all the App group key
  66. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  67. } else {
  68. // FIX 3.0.5 lost urlbase
  69. if (tableAccount.urlBase.length == 0) {
  70. NSString *user = [tableAccount.user stringByAppendingString:@" "];
  71. NSString *urlBase = [tableAccount.account stringByReplacingOccurrencesOfString:user withString:@""];
  72. tableAccount.urlBase = urlBase;
  73. [[NCManageDatabase shared] updateAccount:tableAccount];
  74. tableAccount = [[NCManageDatabase shared] getAccountActive];
  75. }
  76. [self settingAccount:tableAccount.account urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  77. }
  78. // UserDefaults
  79. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions shared].capabilitiesGroups];
  80. // Background Fetch
  81. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  82. self.listProgressMetadata = [NSMutableDictionary new];
  83. self.listFilesVC = [NSMutableDictionary new];
  84. self.listFavoriteVC = [NSMutableDictionary new];
  85. self.listOfflineVC = [NSMutableDictionary new];
  86. // Push Notification
  87. [application registerForRemoteNotifications];
  88. // Display notification
  89. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  90. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  91. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  92. //AV Session
  93. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  94. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  95. // Start Timer
  96. [self startTimerErrorNetworking];
  97. // Store review
  98. if ([[NCUtility shared] isSimulatorOrTestFlight] == false) {
  99. NCStoreReview *review = [NCStoreReview new];
  100. [review incrementAppRuns];
  101. [review showStoreReview];
  102. }
  103. // Detect Dark mode
  104. if (@available(iOS 13.0, *)) {
  105. if ([CCUtility getDarkModeDetect]) {
  106. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  107. [CCUtility setDarkMode:YES];
  108. } else {
  109. [CCUtility setDarkMode:NO];
  110. }
  111. }
  112. }
  113. if ([NCBrandOptions shared].disable_intro) {
  114. [CCUtility setIntro:YES];
  115. if (self.account == nil || self.account.length == 0) {
  116. [self openLoginView:nil selector:NCBrandGlobal.shared.introLogin openLoginWeb:false];
  117. }
  118. } else {
  119. if ([CCUtility getIntro] == NO) {
  120. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  121. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  122. self.window.rootViewController = navController;
  123. [self.window makeKeyAndVisible];
  124. }
  125. }
  126. // init home
  127. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterInitializeMain object:nil userInfo:nil];
  128. // Passcode
  129. dispatch_async(dispatch_get_main_queue(), ^{
  130. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  131. });
  132. // Auto upload
  133. self.networkingAutoUpload = [NCNetworkingAutoUpload new];
  134. return YES;
  135. }
  136. //
  137. // L' applicazione si dimetterà dallo stato di attivo
  138. //
  139. - (void)applicationWillResignActive:(UIApplication *)application
  140. {
  141. if (self.account == nil || self.account.length == 0) { return; }
  142. // Dismiss FileViewInFolder
  143. if (self.activeFileViewInFolder != nil ) {
  144. [self.activeFileViewInFolder dismissViewControllerAnimated:false completion:^{
  145. self.activeFileViewInFolder = nil;
  146. }];
  147. }
  148. }
  149. //
  150. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  151. //
  152. - (void)applicationWillEnterForeground:(UIApplication *)application
  153. {
  154. if (self.account == nil || self.account.length == 0) { return; }
  155. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterApplicationWillEnterForeground object:nil];
  156. // Request Passcode
  157. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  158. // Initialize Auto upload
  159. [[NCAutoUpload shared] initStateAutoUpload];
  160. // Read active directory
  161. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterReloadDataSourceNetworkForced object:nil];
  162. // Required unsubscribing / subscribing
  163. [[NCPushNotification shared] pushNotification];
  164. // RichDocument
  165. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterRichdocumentGrabFocus object:nil];
  166. // Request Service Server Nextcloud
  167. [[NCService shared] startRequestServicesServer];
  168. }
  169. //
  170. // L' applicazione entrerà in primo piano (attivo sempre)
  171. //
  172. - (void)applicationDidBecomeActive:(UIApplication *)application
  173. {
  174. if (self.account == nil || self.account.length == 0) { return; }
  175. // Brand
  176. #if defined(HC)
  177. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  178. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  179. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  180. vc.account = account;
  181. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  182. }
  183. #endif
  184. [[NCNetworking shared] verifyUploadZombie];
  185. }
  186. //
  187. // L' applicazione è entrata nello sfondo
  188. //
  189. - (void)applicationDidEnterBackground:(UIApplication *)application
  190. {
  191. if (self.account == nil || self.account.length == 0) { return; }
  192. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterApplicationDidEnterBackground object:nil];
  193. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  194. }
  195. //
  196. // L'applicazione terminerà
  197. //
  198. - (void)applicationWillTerminate:(UIApplication *)application
  199. {
  200. [[NCCommunicationCommon shared] writeLog:@"bye bye"];
  201. }
  202. // NotificationCenter
  203. - (void)initializeMain:(NSNotification *)notification
  204. {
  205. if (self.account == nil || self.account.length == 0) { return; }
  206. // Clear error certificate
  207. [CCUtility setCertificateError:self.account error:NO];
  208. // Setting Theming
  209. [[NCBrandColor shared] settingThemingColorWithAccount:self.account];
  210. // close detail
  211. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterMenuDetailClose object:nil];
  212. // Not Photos Video in library ? then align and Init Auto Upload
  213. NSArray *recordsPhotoLibrary = [[NCManageDatabase shared] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", self.account]];
  214. if ([recordsPhotoLibrary count] == 0) {
  215. [[NCAutoUpload shared] alignPhotoLibrary];
  216. }
  217. // Start Auto Upload
  218. [[NCAutoUpload shared] initStateAutoUpload];
  219. // Start services
  220. [[NCService shared] startRequestServicesServer];
  221. // Registeration push notification
  222. [[NCPushNotification shared] pushNotification];
  223. // Registeration domain File Provider
  224. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  225. //[fileProviderDomain removeAllDomains];
  226. //[fileProviderDomain registerDomains];
  227. [[NCCommunicationCommon shared] writeLog:@"initialize Main"];
  228. }
  229. #pragma mark Login / checkErrorNetworking
  230. - (void)checkErrorNetworking
  231. {
  232. if (self.account == nil || self.account.length == 0) { return; }
  233. // check unauthorized server (401)
  234. if ([CCUtility getPassword:self.account].length == 0) {
  235. [self openLoginView:self.window.rootViewController selector:NCBrandGlobal.shared.introLogin openLoginWeb:true];
  236. }
  237. // check certificate untrusted (-1202)
  238. if ([CCUtility getCertificateError:self.account]) {
  239. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  240. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  241. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  242. [self startTimerErrorNetworking];
  243. }]];
  244. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  245. [self startTimerErrorNetworking];
  246. }]];
  247. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  248. // Stop timer error network
  249. [self.timerErrorNetworking invalidate];
  250. }];
  251. }
  252. }
  253. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  254. {
  255. // use appConfig [MDM]
  256. if ([NCBrandOptions shared].use_configuration) {
  257. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  258. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  259. [self showLoginViewController:self.appConfigView forContext:viewController];
  260. }
  261. return;
  262. }
  263. // only for personalized LoginWeb [customer]
  264. if ([NCBrandOptions shared].use_login_web_personalized) {
  265. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  266. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  267. self.activeLoginWeb.urlBase = [[NCBrandOptions shared] loginBaseUrl];
  268. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  269. }
  270. return;
  271. }
  272. // normal login
  273. if (selector == NCBrandGlobal.shared.introSignup) {
  274. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  275. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  276. if (selector == NCBrandGlobal.shared.introSignup) {
  277. self.activeLoginWeb.urlBase = [[NCBrandOptions shared] linkloginPreferredProviders];
  278. } else {
  279. self.activeLoginWeb.urlBase = self.urlBase;
  280. }
  281. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  282. }
  283. } else if ([NCBrandOptions shared].disable_intro && [NCBrandOptions shared].disable_request_login_url) {
  284. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  285. self.activeLoginWeb.urlBase = [[NCBrandOptions shared] loginBaseUrl];
  286. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  287. } else if (openLoginWeb) {
  288. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  289. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  290. self.activeLoginWeb.urlBase = self.urlBase;
  291. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  292. }
  293. } else {
  294. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  295. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  296. [self showLoginViewController:_activeLogin forContext:viewController];
  297. }
  298. }
  299. }
  300. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  301. {
  302. if (contextViewController == NULL) {
  303. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  304. navigationController.navigationBar.barStyle = UIBarStyleBlack;
  305. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText;
  306. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer;
  307. [navigationController.navigationBar setTranslucent:false];
  308. self.window.rootViewController = navigationController;
  309. [self.window makeKeyAndVisible];
  310. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  311. UINavigationController *navigationController = ((UINavigationController *)contextViewController);
  312. [navigationController pushViewController:viewController animated:true];
  313. } else {
  314. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  315. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  316. navigationController.navigationBar.barStyle = UIBarStyleBlack;
  317. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText;
  318. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer;
  319. [navigationController.navigationBar setTranslucent:false];
  320. [contextViewController presentViewController:navigationController animated:true completion:nil];
  321. }
  322. }
  323. - (void)startTimerErrorNetworking
  324. {
  325. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  326. }
  327. #pragma mark Account & Communication
  328. - (void)settingAccount:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user userID:(NSString *)userID password:(NSString *)password
  329. {
  330. self.account = account;
  331. self.urlBase = urlBase;
  332. self.user = user;
  333. self.userID = userID;
  334. self.password = password;
  335. (void)[NCNetworkingNotificationCenter shared];
  336. [[NCCommunicationCommon shared] setupWithAccount:account user:user userId:userID password:password urlBase:urlBase];
  337. NSInteger serverVersionMajor = [[NCManageDatabase shared] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  338. if (serverVersionMajor > 0) {
  339. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  340. }
  341. [[NCCommunicationCommon shared] setupWithWebDav:[[NCUtilityFileSystem shared] getWebDAVWithAccount:account]];
  342. [[NCCommunicationCommon shared] setupWithDav:[[NCUtilityFileSystem shared] getDAV]];
  343. }
  344. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  345. {
  346. // Push Notification
  347. tableAccount *accountPN = [[NCManageDatabase shared] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  348. [[NCPushNotification shared] unsubscribingNextcloudServerPushNotification:accountPN.account urlBase:accountPN.urlBase user:accountPN.user withSubscribing:false];
  349. [self settingAccount:nil urlBase:nil user:nil userID:nil password:nil];
  350. /* DELETE ALL FILES LOCAL FS */
  351. NSArray *results = [[NCManageDatabase shared] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  352. for (tableLocalFile *result in results) {
  353. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  354. }
  355. // Clear database
  356. [[NCManageDatabase shared] clearDatabaseWithAccount:account removeAccount:true];
  357. [CCUtility clearAllKeysEndToEnd:account];
  358. [CCUtility clearAllKeysPushNotification:account];
  359. [CCUtility setCertificateError:account error:false];
  360. [CCUtility setPassword:account password:nil];
  361. if (wipe) {
  362. NSArray *listAccount = [[NCManageDatabase shared] getAccounts];
  363. if ([listAccount count] > 0) {
  364. NSString *newAccount = listAccount[0];
  365. tableAccount *tableAccount = [[NCManageDatabase shared] setAccountActive:newAccount];
  366. [self settingAccount:newAccount urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterInitializeMain object:nil userInfo:nil];
  368. } else {
  369. [self openLoginView:self.window.rootViewController selector:NCBrandGlobal.shared.introLogin openLoginWeb:false];
  370. }
  371. }
  372. }
  373. #pragma mark Push Notifications
  374. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  375. {
  376. completionHandler(UNNotificationPresentationOptionAlert);
  377. }
  378. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  379. {
  380. completionHandler();
  381. }
  382. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  383. {
  384. [[NCPushNotification shared] registerForRemoteNotificationsWithDeviceToken:deviceToken];
  385. }
  386. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  387. {
  388. [[NCPushNotification shared] applicationdidReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) {
  389. completionHandler(result);
  390. }];
  391. }
  392. #pragma mark Fetch
  393. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  394. {
  395. if (self.account == nil || self.account.length == 0) {
  396. completionHandler(UIBackgroundFetchResultNoData);
  397. return;
  398. }
  399. [[NCCommunicationCommon shared] writeLog:@"Start perform Fetch With Completion Handler"];
  400. // Verify new photo
  401. [[NCAutoUpload shared] initStateAutoUpload];
  402. // after 20 sec
  403. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  404. [[NCCommunicationCommon shared] writeLog:@"End 20 sec. perform Fetch With Completion Handler"];
  405. completionHandler(UIBackgroundFetchResultNoData);
  406. });
  407. }
  408. #pragma mark Operation Networking & Session
  409. //
  410. // Method called by the system when all the background task has end
  411. //
  412. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  413. {
  414. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start handle Events For Background URLSession: %@", identifier]];
  415. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  416. self.backgroundSessionCompletionHandler = completionHandler;
  417. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  418. self.backgroundSessionCompletionHandler = nil;
  419. completionHandler();
  420. });
  421. }
  422. #pragma mark OpenURL
  423. // Method called from iOS system to send a file from other app.
  424. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  425. {
  426. if (self.account == nil || self.account.length == 0) { return YES; }
  427. NSString *scheme = url.scheme;
  428. NSString *fileName;
  429. NSString *serverUrl;
  430. if ([scheme isEqualToString:@"nextcloud"]) {
  431. NSString *action = url.host;
  432. if ([action isEqualToString:@"open-file"]) {
  433. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  434. NSArray *queryItems = urlComponents.queryItems;
  435. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  436. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  437. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  438. tableAccount *matchedAccount = nil;
  439. // verify parameter
  440. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  441. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  442. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  443. [alertController addAction:okAction];
  444. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  445. } else {
  446. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  447. if (account) {
  448. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  449. NSString *accountUser = account.user;
  450. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  451. matchedAccount = account;
  452. } else {
  453. NSArray *accounts = [[NCManageDatabase shared] getAllAccount];
  454. for (tableAccount *account in accounts) {
  455. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  456. NSString *accountUser = account.user;
  457. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  458. matchedAccount = [[NCManageDatabase shared] setAccountActive:account.account];
  459. [self settingAccount:matchedAccount.account urlBase:matchedAccount.urlBase user:matchedAccount.user userID:matchedAccount.userID password:[CCUtility getPassword:matchedAccount.account]];
  460. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCBrandGlobal.shared.notificationCenterInitializeMain object:nil userInfo:nil];
  461. }
  462. }
  463. }
  464. if (matchedAccount) {
  465. NSString *webDAV = [[NCUtilityFileSystem shared] getWebDAVWithAccount:self.account];
  466. if ([path containsString:@"/"]) {
  467. fileName = [path lastPathComponent];
  468. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, [path stringByDeletingLastPathComponent]];
  469. } else {
  470. fileName = path;
  471. serverUrl = [NSString stringWithFormat:@"%@/%@", matchedAccount.urlBase, webDAV];
  472. }
  473. [[NCCollectionCommon shared] openFileViewInFolderWithServerUrl:serverUrl fileName:fileName];
  474. } else {
  475. NSString *domain = [[NSURL URLWithString:link] host];
  476. NSString *fileName = [path lastPathComponent];
  477. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  478. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  479. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  480. [alertController addAction:okAction];
  481. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  482. }
  483. }
  484. }
  485. }
  486. return YES;
  487. }
  488. /*
  489. NSError *error;
  490. NSLog(@"[LOG] the path is: %@", url.path);
  491. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  492. NSString *fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  493. if (self.account && [[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
  494. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileNameUpload] error:nil];
  495. [[NSFileManager defaultManager] moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:fileNameUpload] error:&error];
  496. if (error == nil) {
  497. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  498. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateInitialViewController];
  499. CCUploadFromOtherUpp *uploadFromOtherUpp = (CCUploadFromOtherUpp *)[navigationController topViewController];
  500. uploadFromOtherUpp.fileNameUpload = fileNameUpload;
  501. [self.window.rootViewController presentViewController:uploadFromOtherUpp animated:YES completion:nil];
  502. });
  503. }
  504. }
  505. */
  506. return YES;
  507. }
  508. #pragma mark Passcode + Delegate
  509. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  510. {
  511. LAContext *laContext = [LAContext new];
  512. NSError *error;
  513. BOOL isBiometryAvailable = false;
  514. if ([[CCUtility getPasscode] length] == 0 || [self.account length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  515. if (self.passcodeViewController == nil) {
  516. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  517. if (@available(iOS 13.0, *)) {
  518. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  519. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  520. }
  521. }
  522. self.passcodeViewController.delegate = self;
  523. self.passcodeViewController.keypadButtonShowLettering = false;
  524. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  525. if (error == NULL) {
  526. if (laContext.biometryType == LABiometryTypeFaceID) {
  527. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  528. self.passcodeViewController.allowBiometricValidation = true;
  529. isBiometryAvailable = true;
  530. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  531. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  532. self.passcodeViewController.allowBiometricValidation = true;
  533. isBiometryAvailable = true;
  534. } else {
  535. isBiometryAvailable = false;
  536. NSLog(@"No Biometric support");
  537. }
  538. }
  539. }
  540. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:^{
  541. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  542. }];
  543. } else {
  544. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  545. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  546. });
  547. }
  548. }
  549. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  550. {
  551. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  552. self.passcodeViewController = nil;
  553. }];
  554. }
  555. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  556. {
  557. return [code isEqualToString:[CCUtility getPasscode]];
  558. }
  559. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  560. {
  561. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions shared] brand] reply:^(BOOL success, NSError * _Nullable error) {
  562. if (success) {
  563. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  564. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  565. self.passcodeViewController = nil;
  566. }];
  567. });
  568. }
  569. }];
  570. }
  571. - (void)enableTouchFaceID:(BOOL)automaticallyPromptForBiometricValidation
  572. {
  573. if (CCUtility.getEnableTouchFaceID && automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  574. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions shared] brand] reply:^(BOOL success, NSError * _Nullable error) {
  575. if (success) {
  576. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  577. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  578. self.passcodeViewController = nil;
  579. }];
  580. });
  581. }
  582. }];
  583. }
  584. }
  585. @end