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