AppDelegate.m 50 KB

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