AppDelegate.m 32 KB

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