AppDelegate.m 44 KB

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