AppDelegate.m 33 KB

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