AppDelegate.m 46 KB

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