AppDelegate.m 35 KB

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