AppDelegate.m 45 KB

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