AppDelegate.m 36 KB

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