AppDelegate.m 44 KB

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