AppDelegate.m 32 KB

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