AppDelegate.m 46 KB

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