AppDelegate.m 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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 "CCGraphics.h"
  25. #import "NCBridgeSwift.h"
  26. #import "NCAutoUpload.h"
  27. #import "NCPushNotificationEncryption.h"
  28. #import <QuartzCore/QuartzCore.h>
  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 (isSimulatorOrTestFlight) {
  41. NCBrandOptions.sharedInstance.disable_crash_service = false;
  42. }
  43. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  44. }
  45. [CCUtility createDirectoryStandard];
  46. [CCUtility emptyTemporaryDirectory];
  47. // Networking
  48. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  49. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent]];
  50. NSInteger logLevel = [CCUtility getLogLevel];
  51. [[NCCommunicationCommon shared] setFileLogWithLevel:logLevel];
  52. NSString *versionApp = [NSString stringWithFormat:@"%@.%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
  53. NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions sharedInstance].textCopyrightNextcloudiOS, versionApp];
  54. if (isSimulatorOrTestFlight) {
  55. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@ (Simulator / TestFlight)", (unsigned long)logLevel, versionNextcloudiOS]];
  56. } else {
  57. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@", (unsigned long)logLevel, versionNextcloudiOS]];
  58. }
  59. //
  60. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  61. // Set account, if no exists clear all
  62. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  63. if (tableAccount == nil) {
  64. // remove all the keys Chain
  65. [CCUtility deleteAllChainStore];
  66. // remove all the App group key
  67. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  68. } else {
  69. // FIX 3.0.5 lost urlbase
  70. if (tableAccount.urlBase.length == 0) {
  71. NSString *user = [tableAccount.user stringByAppendingString:@" "];
  72. NSString *urlBase = [tableAccount.account stringByReplacingOccurrencesOfString:user withString:@""];
  73. tableAccount.urlBase = urlBase;
  74. [[NCManageDatabase sharedInstance] updateAccount:tableAccount];
  75. tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  76. }
  77. [self settingAccount:tableAccount.account urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  78. }
  79. // UserDefaults
  80. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  81. // Background Fetch
  82. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  83. self.listProgressMetadata = [NSMutableDictionary new];
  84. self.listFilesVC = [NSMutableDictionary new];
  85. self.listFavoriteVC = [NSMutableDictionary new];
  86. self.listOfflineVC = [NSMutableDictionary new];
  87. // Push Notification
  88. [application registerForRemoteNotifications];
  89. // Display notification
  90. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  91. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  92. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  93. //AV Session
  94. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  95. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  96. // Start Timer
  97. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  98. [self startTimerErrorNetworking];
  99. // Store review
  100. if ([[NCUtility shared] isSimulatorOrTestFlight] == false) {
  101. NCStoreReview *review = [NCStoreReview new];
  102. [review incrementAppRuns];
  103. [review showStoreReview];
  104. }
  105. // Detect Dark mode
  106. if (@available(iOS 13.0, *)) {
  107. if ([CCUtility getDarkModeDetect]) {
  108. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  109. [CCUtility setDarkMode:YES];
  110. } else {
  111. [CCUtility setDarkMode:NO];
  112. }
  113. }
  114. }
  115. if ([NCBrandOptions sharedInstance].disable_intro) {
  116. [CCUtility setIntro:YES];
  117. if (self.account.length == 0) {
  118. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  119. }
  120. } else {
  121. if ([CCUtility getIntro] == NO) {
  122. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  123. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  124. self.window.rootViewController = navController;
  125. [self.window makeKeyAndVisible];
  126. }
  127. }
  128. // init home
  129. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  130. // Passcode
  131. dispatch_async(dispatch_get_main_queue(), ^{
  132. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  133. });
  134. // Auto upload
  135. self.networkingAutoUpload = [NCNetworkingAutoUpload new];
  136. return YES;
  137. }
  138. //
  139. // L' applicazione si dimetterà dallo stato di attivo
  140. //
  141. - (void)applicationWillResignActive:(UIApplication *)application
  142. {
  143. if (self.account.length == 0) return;
  144. // Dismiss FileViewInFolder
  145. if (self.activeFileViewInFolder != nil ) {
  146. [self.activeFileViewInFolder dismissViewControllerAnimated:false completion:^{
  147. self.activeFileViewInFolder = nil;
  148. }];
  149. }
  150. [self updateApplicationIconBadgeNumber];
  151. }
  152. //
  153. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  154. //
  155. - (void)applicationWillEnterForeground:(UIApplication *)application
  156. {
  157. if (self.account.length == 0) { return; }
  158. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationWillEnterForeground object:nil];
  159. // Request Passcode
  160. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  161. // Initialize Auto upload
  162. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  163. // Read active directory
  164. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_reloadDataSourceNetworkForced object:nil];
  165. // Required unsubscribing / subscribing
  166. [self pushNotification];
  167. // RichDocument
  168. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  169. // Request Service Server Nextcloud
  170. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  171. [[NCService shared] startRequestServicesServer];
  172. });
  173. }
  174. //
  175. // L' applicazione entrerà in primo piano (attivo sempre)
  176. //
  177. - (void)applicationDidBecomeActive:(UIApplication *)application
  178. {
  179. if (self.account.length == 0) { return; }
  180. // Brand
  181. #if defined(HC)
  182. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  183. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  184. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  185. vc.account = account;
  186. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  187. }
  188. #endif
  189. [[NCNetworking shared] verifyUploadZombie];
  190. }
  191. //
  192. // L' applicazione è entrata nello sfondo
  193. //
  194. - (void)applicationDidEnterBackground:(UIApplication *)application
  195. {
  196. if (self.account.length == 0) { return; }
  197. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  198. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  199. }
  200. //
  201. // L'applicazione terminerà
  202. //
  203. - (void)applicationWillTerminate:(UIApplication *)application
  204. {
  205. [[NCCommunicationCommon shared] writeLog:@"bye bye"];
  206. }
  207. // NotificationCenter
  208. - (void)initializeMain:(NSNotification *)notification
  209. {
  210. if (self.account.length == 0) return;
  211. // Clear error certificate
  212. [CCUtility setCertificateError:self.account error:NO];
  213. // Setting Theming
  214. [[NCBrandColor sharedInstance] settingThemingColor];
  215. // close detail
  216. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  217. // Not Photos Video in library ? then align and Init Auto Upload
  218. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", self.account]];
  219. if ([recordsPhotoLibrary count] == 0) {
  220. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  221. }
  222. // Start Auto Upload
  223. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  224. // Start services
  225. [[NCService shared] startRequestServicesServer];
  226. // Registeration push notification
  227. [self pushNotification];
  228. // Registeration domain File Provider
  229. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  230. //[fileProviderDomain removeAllDomains];
  231. //[fileProviderDomain registerDomains];
  232. [[NCCommunicationCommon shared] writeLog:@"initialize Main"];
  233. }
  234. #pragma --------------------------------------------------------------------------------------------
  235. #pragma mark ===== Login / checkErrorNetworking =====
  236. #pragma --------------------------------------------------------------------------------------------
  237. - (void)checkErrorNetworking
  238. {
  239. // test
  240. if (self.account.length == 0) return;
  241. // check unauthorized server (401)
  242. if ([CCUtility getPassword:self.account].length == 0) {
  243. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  244. }
  245. // check certificate untrusted (-1202)
  246. if ([CCUtility getCertificateError:self.account]) {
  247. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  248. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  249. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  250. [self startTimerErrorNetworking];
  251. }]];
  252. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  253. [self startTimerErrorNetworking];
  254. }]];
  255. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  256. // Stop timer error network
  257. [self.timerErrorNetworking invalidate];
  258. }];
  259. }
  260. }
  261. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  262. {
  263. // use appConfig [MDM]
  264. if ([NCBrandOptions sharedInstance].use_configuration) {
  265. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  266. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  267. [self showLoginViewController:self.appConfigView forContext:viewController];
  268. }
  269. return;
  270. }
  271. // only for personalized LoginWeb [customer]
  272. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  273. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  274. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  275. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  276. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  277. }
  278. return;
  279. }
  280. // normal login
  281. if (selector == k_intro_signup) {
  282. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  283. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  284. if (selector == k_intro_signup) {
  285. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  286. } else {
  287. self.activeLoginWeb.urlBase = self.urlBase;
  288. }
  289. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  290. }
  291. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  292. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  293. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  294. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  295. } else if (openLoginWeb) {
  296. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  297. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  298. self.activeLoginWeb.urlBase = self.urlBase;
  299. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  300. }
  301. } else {
  302. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  303. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  304. [self showLoginViewController:_activeLogin forContext:viewController];
  305. }
  306. }
  307. }
  308. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  309. {
  310. if (contextViewController == NULL) {
  311. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  312. navigationController.navigationBar.barStyle = UIBarStyleBlack;
  313. navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  314. navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  315. [navigationController.navigationBar setTranslucent:false];
  316. self.window.rootViewController = navigationController;
  317. [self.window makeKeyAndVisible];
  318. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  319. UINavigationController *navigationController = ((UINavigationController *)contextViewController);
  320. [navigationController pushViewController:viewController animated:true];
  321. } else {
  322. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  323. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  324. navigationController.navigationBar.barStyle = UIBarStyleBlack;
  325. navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  326. navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  327. [navigationController.navigationBar setTranslucent:false];
  328. [contextViewController presentViewController:navigationController animated:true completion:nil];
  329. }
  330. }
  331. - (void)startTimerErrorNetworking
  332. {
  333. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  334. }
  335. #pragma --------------------------------------------------------------------------------------------
  336. #pragma mark ===== Account & Communication =====
  337. #pragma --------------------------------------------------------------------------------------------
  338. - (void)settingAccount:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user userID:(NSString *)userID password:(NSString *)password
  339. {
  340. self.account = account;
  341. self.urlBase = urlBase;
  342. self.user = user;
  343. self.userID = userID;
  344. self.password = password;
  345. (void)[NCNetworkingNotificationCenter shared];
  346. [[NCCommunicationCommon shared] setupWithAccount:account user:user userId:userID password:password urlBase:urlBase];
  347. [self settingSetupCommunication:account];
  348. }
  349. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  350. {
  351. // Push Notification
  352. tableAccount *accountPN = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  353. [self unsubscribingNextcloudServerPushNotification:accountPN.account urlBase:accountPN.urlBase user:accountPN.user withSubscribing:false];
  354. [self settingAccount:nil urlBase:nil user:nil userID:nil password:nil];
  355. /* DELETE ALL FILES LOCAL FS */
  356. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  357. for (tableLocalFile *result in results) {
  358. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  359. }
  360. // Clear database
  361. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  362. [CCUtility clearAllKeysEndToEnd:account];
  363. [CCUtility clearAllKeysPushNotification:account];
  364. [CCUtility setCertificateError:account error:false];
  365. [CCUtility setPassword:account password:nil];
  366. if (wipe) {
  367. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  368. if ([listAccount count] > 0) {
  369. NSString *newAccount = listAccount[0];
  370. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  371. [self settingAccount:newAccount urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  372. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  373. } else {
  374. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  375. }
  376. }
  377. }
  378. - (void)settingSetupCommunication:(NSString *)account
  379. {
  380. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  381. if (serverVersionMajor > 0) {
  382. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  383. }
  384. [[NCCommunicationCommon shared] setupWithWebDav:[[NCUtility shared] getWebDAVWithAccount:account]];
  385. [[NCCommunicationCommon shared] setupWithDav:[[NCUtility shared] getDAV]];
  386. }
  387. #pragma --------------------------------------------------------------------------------------------
  388. #pragma mark ===== Push Notifications =====
  389. #pragma --------------------------------------------------------------------------------------------
  390. - (void)pushNotification
  391. {
  392. // test
  393. if (self.account.length == 0 || self.pushKitToken.length == 0) return;
  394. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  395. NSString *token = [CCUtility getPushNotificationToken:result.account];
  396. if (![token isEqualToString:self.pushKitToken]) {
  397. if (token != nil) {
  398. // unsubscribing + subscribing
  399. [self unsubscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user withSubscribing:true];
  400. } else {
  401. [self subscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user];
  402. }
  403. }
  404. }
  405. }
  406. - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user
  407. {
  408. // test
  409. if (self.account.length == 0 || self.pushKitToken.length == 0) return;
  410. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  411. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  412. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  413. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  414. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  415. [[NCCommunication shared] subscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSInteger errorCode, NSString *errorDescription) {
  416. if (errorCode == 0) {
  417. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  418. [[NCCommunication shared] subscribingPushProxyWithProxyServerUrl:proxyServerPath pushToken:self.pushKitToken deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  419. if (errorCode == 0) {
  420. [[NCCommunicationCommon shared] writeLog:@"Subscribed to Push Notification server & proxy successfully"];
  421. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  422. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  423. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:signature];
  424. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  425. }
  426. }];
  427. }
  428. }];
  429. }
  430. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user withSubscribing:(BOOL)subscribing
  431. {
  432. if (self.account.length == 0) return;
  433. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  434. NSString *signature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  435. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  436. [[NCCommunication shared] unsubscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDescription) {
  437. if (errorCode == 0) {
  438. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  439. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  440. [[NCCommunication shared] unsubscribingPushProxyWithProxyServerUrl:proxyServerPath deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  441. if (errorCode == 0) {
  442. [[NCCommunicationCommon shared] writeLog:@"Unsubscribed to Push Notification server & proxy successfully."];
  443. [CCUtility setPushNotificationPublicKey:account data:nil];
  444. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  445. [CCUtility setPushNotificationPrivateKey:account data:nil];
  446. [CCUtility setPushNotificationToken:account token:nil];
  447. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  448. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  449. if (self.pushKitToken != nil && subscribing) {
  450. [self subscribingNextcloudServerPushNotification:account urlBase:urlBase user:user];
  451. }
  452. }
  453. }];
  454. }
  455. }];
  456. }
  457. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  458. {
  459. //Called when a notification is delivered to a foreground app.
  460. completionHandler(UNNotificationPresentationOptionAlert);
  461. }
  462. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  463. {
  464. completionHandler();
  465. }
  466. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  467. {
  468. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  469. [self pushNotification];
  470. }
  471. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  472. {
  473. NSString *message = [userInfo objectForKey:@"subject"];
  474. if (message) {
  475. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  476. for (tableAccount *result in results) {
  477. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  478. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  479. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  480. if (decryptedMessage) {
  481. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  482. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  483. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  484. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  485. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  486. if (delete) {
  487. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  488. } else if (deleteAll) {
  489. [self cleanAllNotifications];
  490. }
  491. }
  492. }
  493. }
  494. }
  495. completionHandler(UIBackgroundFetchResultNoData);
  496. }
  497. - (void)cleanAllNotifications
  498. {
  499. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  500. }
  501. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  502. {
  503. // Check in pending notifications
  504. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  505. for (UNNotificationRequest *notificationRequest in requests) {
  506. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  507. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  508. if (decryptedMessage) {
  509. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  510. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  511. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  512. if (nid == notificationId) {
  513. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  514. }
  515. }
  516. }
  517. }];
  518. // Check in delivered notifications
  519. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  520. for (UNNotification *notification in notifications) {
  521. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  522. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  523. if (decryptedMessage) {
  524. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  525. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  526. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  527. if (nid == notificationId) {
  528. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  529. }
  530. }
  531. }
  532. }];
  533. }
  534. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  535. {
  536. const char *data = [deviceToken bytes];
  537. NSMutableString *token = [NSMutableString string];
  538. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  539. [token appendFormat:@"%02.2hhX", data[i]];
  540. }
  541. return [token copy];
  542. }
  543. #pragma --------------------------------------------------------------------------------------------
  544. #pragma mark ===== ApplicationIconBadgeNumber =====
  545. #pragma --------------------------------------------------------------------------------------------
  546. - (void)updateApplicationIconBadgeNumber
  547. {
  548. if (self.account.length == 0) return;
  549. NSInteger counterDownload = [[NCOperationQueue shared] downloadCount];
  550. NSInteger counterUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading]].count;
  551. NSInteger total = counterDownload + counterUpload;
  552. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  553. UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
  554. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  555. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  556. if (total > 0) {
  557. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  558. } else {
  559. [tabBarItem setBadgeValue:nil];
  560. }
  561. }
  562. }
  563. #pragma --------------------------------------------------------------------------------------------
  564. #pragma mark ===== Fetch =====
  565. #pragma --------------------------------------------------------------------------------------------
  566. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  567. {
  568. if (self.account.length == 0) {
  569. completionHandler(UIBackgroundFetchResultNoData);
  570. return;
  571. }
  572. [[NCCommunicationCommon shared] writeLog:@"Start perform Fetch With Completion Handler"];
  573. // Verify new photo
  574. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  575. // after 20 sec
  576. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  577. [[NCCommunicationCommon shared] writeLog:@"End 20 sec. perform Fetch With Completion Handler"];
  578. completionHandler(UIBackgroundFetchResultNoData);
  579. });
  580. }
  581. #pragma --------------------------------------------------------------------------------------------
  582. #pragma mark ===== Operation Networking & Session =====
  583. #pragma --------------------------------------------------------------------------------------------
  584. //
  585. // Method called by the system when all the background task has end
  586. //
  587. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  588. {
  589. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start handle Events For Background URLSession: %@", identifier]];
  590. [self updateApplicationIconBadgeNumber];
  591. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  592. self.backgroundSessionCompletionHandler = completionHandler;
  593. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  594. self.backgroundSessionCompletionHandler = nil;
  595. completionHandler();
  596. });
  597. }
  598. #pragma --------------------------------------------------------------------------------------------
  599. #pragma mark ===== OpenURL =====
  600. #pragma --------------------------------------------------------------------------------------------
  601. // Method called from iOS system to send a file from other app.
  602. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  603. {
  604. if (self.account.length == 0) return YES;
  605. NSString *scheme = url.scheme;
  606. NSString *fileName;
  607. NSString *serverUrl;
  608. if ([scheme isEqualToString:@"nextcloud"]) {
  609. NSString *action = url.host;
  610. if ([action isEqualToString:@"open-file"]) {
  611. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  612. NSArray *queryItems = urlComponents.queryItems;
  613. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  614. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  615. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  616. tableAccount *matchedAccount = nil;
  617. // verify parameter
  618. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  619. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  620. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  621. [alertController addAction:okAction];
  622. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  623. } else {
  624. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  625. if (account) {
  626. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  627. NSString *accountUser = account.user;
  628. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  629. matchedAccount = account;
  630. } else {
  631. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  632. for (tableAccount *account in accounts) {
  633. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  634. NSString *accountUser = account.user;
  635. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  636. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  637. [self settingAccount:matchedAccount.account urlBase:matchedAccount.urlBase user:matchedAccount.user userID:matchedAccount.userID password:[CCUtility getPassword:matchedAccount.account]];
  638. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  639. }
  640. }
  641. }
  642. if (matchedAccount) {
  643. NSString *webDAV = [[NCUtility shared] getWebDAVWithAccount:self.account];
  644. if ([path containsString:@"/"]) {
  645. fileName = [path lastPathComponent];
  646. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, [path stringByDeletingLastPathComponent]];
  647. } else {
  648. fileName = path;
  649. serverUrl = [NSString stringWithFormat:@"%@/%@", matchedAccount.urlBase, webDAV];
  650. }
  651. [[NCCollectionCommon shared] openFileViewInFolderWithServerUrl:serverUrl fileName:fileName];
  652. } else {
  653. NSString *domain = [[NSURL URLWithString:link] host];
  654. NSString *fileName = [path lastPathComponent];
  655. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  656. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  657. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  658. [alertController addAction:okAction];
  659. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  660. }
  661. }
  662. }
  663. }
  664. return YES;
  665. }
  666. NSError *error;
  667. NSLog(@"[LOG] the path is: %@", url.path);
  668. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  669. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  670. if (self.account) {
  671. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  672. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  673. if (error == nil) {
  674. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  675. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  676. [self.window.rootViewController presentViewController:uploadNavigationViewController animated:YES completion:nil];
  677. });
  678. }
  679. }
  680. return YES;
  681. }
  682. #pragma --------------------------------------------------------------------------------------------
  683. #pragma mark ===== Passcode + Delegate =====
  684. #pragma --------------------------------------------------------------------------------------------
  685. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  686. {
  687. LAContext *laContext = [LAContext new];
  688. NSError *error;
  689. BOOL isBiometryAvailable = false;
  690. if ([[CCUtility getPasscode] length] == 0 || [self.account length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  691. if (self.passcodeViewController == nil) {
  692. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  693. if (@available(iOS 13.0, *)) {
  694. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  695. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  696. }
  697. }
  698. self.passcodeViewController.delegate = self;
  699. self.passcodeViewController.keypadButtonShowLettering = false;
  700. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  701. if (error == NULL) {
  702. if (laContext.biometryType == LABiometryTypeFaceID) {
  703. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  704. self.passcodeViewController.allowBiometricValidation = true;
  705. isBiometryAvailable = true;
  706. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  707. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  708. self.passcodeViewController.allowBiometricValidation = true;
  709. isBiometryAvailable = true;
  710. } else {
  711. isBiometryAvailable = false;
  712. NSLog(@"No Biometric support");
  713. }
  714. }
  715. }
  716. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:^{
  717. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  718. }];
  719. } else {
  720. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  721. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  722. });
  723. }
  724. }
  725. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  726. {
  727. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  728. self.passcodeViewController = nil;
  729. }];
  730. }
  731. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  732. {
  733. return [code isEqualToString:[CCUtility getPasscode]];
  734. }
  735. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  736. {
  737. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  738. if (success) {
  739. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  740. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  741. self.passcodeViewController = nil;
  742. }];
  743. });
  744. }
  745. }];
  746. }
  747. - (void)enableTouchFaceID:(BOOL)automaticallyPromptForBiometricValidation
  748. {
  749. if (CCUtility.getEnableTouchFaceID && automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  750. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  751. if (success) {
  752. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  753. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  754. self.passcodeViewController = nil;
  755. }];
  756. });
  757. }
  758. }];
  759. }
  760. }
  761. @end