AppDelegate.m 35 KB

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