AppDelegate.m 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import "CCGraphics.h"
  25. #import "CCMain.h"
  26. #import "NCBridgeSwift.h"
  27. #import "NCAutoUpload.h"
  28. #import "NCPushNotificationEncryption.h"
  29. #import <QuartzCore/QuartzCore.h>
  30. @import Sentry;
  31. @class NCViewerRichdocument;
  32. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  33. @end
  34. @implementation AppDelegate
  35. + (void)initialize
  36. {
  37. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  38. }
  39. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  40. {
  41. if ([[NCUtility shared] isSimulatorOrTestFlight]) {
  42. NCBrandOptions.sharedInstance.disable_crash_service = false;
  43. }
  44. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  45. [SentrySDK startWithOptions: @{
  46. @"dsn": @"https://42eaf570ec2646b1a564a4c4bfc8c279@o394108.ingest.sentry.io/5243836",
  47. @"debug": @(YES),
  48. @"enableAutoSessionTracking": @(YES)
  49. /* PRIVACY : https://github.com/getsentry/sentry-cocoa
  50. By default, we don’t apply the user identification provided to the SDK via the API. Instead, we use
  51. the installation ID generated with the first use of the application. The ID doesn’t contain any
  52. private or public data of your users or any public or shared data of their device.
  53. */
  54. }];
  55. }
  56. [CCUtility createDirectoryStandard];
  57. [CCUtility emptyTemporaryDirectory];
  58. // Networking
  59. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  60. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups];
  61. NSInteger logLevel = [CCUtility getLogLevel];
  62. [[NCCommunicationCommon shared] setFileLogWithLevel:logLevel echo:true];
  63. NSString *versionApp = [NSString stringWithFormat:@"%@.%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
  64. NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions sharedInstance].textCopyrightNextcloudiOS, versionApp];
  65. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"%@ %lu %@", @"[LOG] Start session with level", (unsigned long)logLevel, versionNextcloudiOS]];
  66. // Set account, if no exists clear all
  67. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  68. if (tableAccount == nil) {
  69. // remove all the keys Chain
  70. [CCUtility deleteAllChainStore];
  71. // remove all the App group key
  72. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  73. } else {
  74. [self settingAccount:tableAccount.account urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  75. }
  76. // UserDefaults
  77. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  78. // Background Fetch
  79. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  80. self.listProgressMetadata = [NSMutableDictionary new];
  81. self.listMainVC = [NSMutableDictionary new];
  82. // Push Notification
  83. [application registerForRemoteNotifications];
  84. // Display notification
  85. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  86. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  87. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  88. //AV Session
  89. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  90. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  91. // ProgressView Detail
  92. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  93. // Quick Actions
  94. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  95. [self configDynamicShortcutItems];
  96. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  97. if (shortcutItem)
  98. [self handleShortCutItem:shortcutItem];
  99. }
  100. // Start Timer
  101. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  102. [self startTimerErrorNetworking];
  103. // Store review
  104. if ([[NCUtility shared] isSimulatorOrTestFlight] == false) {
  105. NCStoreReview *review = [NCStoreReview new];
  106. [review incrementAppRuns];
  107. [review showStoreReview];
  108. }
  109. // Detect Dark mode
  110. if (@available(iOS 13.0, *)) {
  111. if ([CCUtility getDarkModeDetect]) {
  112. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  113. [CCUtility setDarkMode:YES];
  114. } else {
  115. [CCUtility setDarkMode:NO];
  116. }
  117. }
  118. }
  119. if ([NCBrandOptions sharedInstance].disable_intro) {
  120. [CCUtility setIntro:YES];
  121. if (self.account.length == 0) {
  122. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  123. }
  124. } else {
  125. if ([CCUtility getIntro] == NO) {
  126. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  127. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  128. self.window.rootViewController = navController;
  129. [self.window makeKeyAndVisible];
  130. }
  131. }
  132. // init home
  133. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  134. // Passcode
  135. dispatch_async(dispatch_get_main_queue(), ^{
  136. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  137. });
  138. // Auto upload
  139. self.networkingAutoUpload = [NCNetworkingAutoUpload new];
  140. return YES;
  141. }
  142. //
  143. // L' applicazione si dimetterà dallo stato di attivo
  144. //
  145. - (void)applicationWillResignActive:(UIApplication *)application
  146. {
  147. // Test Maintenance
  148. if (self.account.length == 0 || self.maintenanceMode)
  149. return;
  150. [self updateApplicationIconBadgeNumber];
  151. }
  152. //
  153. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  154. //
  155. - (void)applicationWillEnterForeground:(UIApplication *)application
  156. {
  157. if (self.account.length == 0 || self.maintenanceMode) { return; }
  158. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationWillEnterForeground object:nil];
  159. // Request Passcode
  160. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  161. // Request Service Server Nextcloud
  162. [[NCService shared] startRequestServicesServer];
  163. // Initialize Auto upload
  164. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  165. // Read active directory
  166. [self.activeMain readFileReloadFolder];
  167. // Required unsubscribing / subscribing
  168. [self pushNotification];
  169. // RichDocument
  170. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  171. }
  172. //
  173. // L' applicazione entrerà in primo piano (attivo sempre)
  174. //
  175. - (void)applicationDidBecomeActive:(UIApplication *)application
  176. {
  177. if (self.account.length == 0 || self.maintenanceMode) { return; }
  178. // Brand
  179. #if defined(HC)
  180. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  181. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  182. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  183. vc.account = account;
  184. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  185. }
  186. #endif
  187. [[NCNetworking shared] verifyUploadZombie];
  188. }
  189. //
  190. // L' applicazione è entrata nello sfondo
  191. //
  192. - (void)applicationDidEnterBackground:(UIApplication *)application
  193. {
  194. if (self.account.length == 0 || self.maintenanceMode) { return; }
  195. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  196. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  197. }
  198. //
  199. // L'applicazione terminerà
  200. //
  201. - (void)applicationWillTerminate:(UIApplication *)application
  202. {
  203. [[NCCommunicationCommon shared] writeLog:@"[LOG] bye bye"];
  204. }
  205. #pragma --------------------------------------------------------------------------------------------
  206. #pragma mark ===== Login / checkErrorNetworking =====
  207. #pragma --------------------------------------------------------------------------------------------
  208. - (void)checkErrorNetworking
  209. {
  210. // test
  211. if (self.account.length == 0 || self.maintenanceMode)
  212. return;
  213. // check unauthorized server (401)
  214. if ([CCUtility getPassword:self.account].length == 0) {
  215. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  216. }
  217. // check certificate untrusted (-1202)
  218. if ([CCUtility getCertificateError:self.account]) {
  219. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  220. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  221. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  222. [self startTimerErrorNetworking];
  223. }]];
  224. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  225. [self startTimerErrorNetworking];
  226. }]];
  227. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  228. // Stop timer error network
  229. [self.timerErrorNetworking invalidate];
  230. }];
  231. }
  232. }
  233. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  234. {
  235. // use appConfig [MDM]
  236. if ([NCBrandOptions sharedInstance].use_configuration) {
  237. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  238. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  239. [self showLoginViewController:self.appConfigView forContext:viewController];
  240. }
  241. return;
  242. }
  243. // only for personalized LoginWeb [customer]
  244. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  245. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  246. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  247. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  248. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  249. }
  250. return;
  251. }
  252. // normal login
  253. if (selector == k_intro_signup) {
  254. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  255. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  256. if (selector == k_intro_signup) {
  257. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  258. } else {
  259. self.activeLoginWeb.urlBase = self.urlBase;
  260. }
  261. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  262. }
  263. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  264. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  265. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  266. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  267. } else if (openLoginWeb) {
  268. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  269. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  270. self.activeLoginWeb.urlBase = self.urlBase;
  271. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  272. }
  273. } else {
  274. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  275. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  276. [self showLoginViewController:_activeLogin forContext:viewController];
  277. }
  278. }
  279. }
  280. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  281. {
  282. if (contextViewController == NULL) {
  283. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  284. navController.navigationBar.barStyle = UIBarStyleBlack;
  285. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  286. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  287. [navController.navigationBar setTranslucent:false];
  288. self.window.rootViewController = navController;
  289. [self.window makeKeyAndVisible];
  290. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  291. UINavigationController *navController = ((UINavigationController *)contextViewController);
  292. [navController pushViewController:viewController animated:true];
  293. } else {
  294. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  295. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  296. navController.navigationBar.barStyle = UIBarStyleBlack;
  297. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  298. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  299. [navController.navigationBar setTranslucent:false];
  300. [contextViewController presentViewController:navController animated:true completion:nil];
  301. }
  302. }
  303. - (void)startTimerErrorNetworking
  304. {
  305. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  306. }
  307. #pragma --------------------------------------------------------------------------------------------
  308. #pragma mark ===== Account & Communication =====
  309. #pragma --------------------------------------------------------------------------------------------
  310. - (void)settingAccount:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user userID:(NSString *)userID password:(NSString *)password
  311. {
  312. self.account = account;
  313. self.urlBase = urlBase;
  314. self.user = user;
  315. self.userID = userID;
  316. self.password = password;
  317. (void)[NCNetworkingNotificationCenter shared];
  318. [[NCCommunicationCommon shared] setupWithAccount:account user:user userId:userID password:password urlBase:urlBase];
  319. [self settingSetupCommunication:account];
  320. }
  321. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  322. {
  323. // Push Notification
  324. tableAccount *accountPN = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  325. [self unsubscribingNextcloudServerPushNotification:accountPN.account urlBase:accountPN.urlBase user:accountPN.user withSubscribing:false];
  326. [self settingAccount:nil urlBase:nil user:nil userID:nil password:nil];
  327. /* DELETE ALL FILES LOCAL FS */
  328. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  329. for (tableLocalFile *result in results) {
  330. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  331. }
  332. // Clear database
  333. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  334. [CCUtility clearAllKeysEndToEnd:account];
  335. [CCUtility clearAllKeysPushNotification:account];
  336. [CCUtility setCertificateError:account error:false];
  337. [CCUtility setPassword:account password:nil];
  338. if (wipe) {
  339. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  340. if ([listAccount count] > 0) {
  341. NSString *newAccount = listAccount[0];
  342. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  343. [self settingAccount:newAccount urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  344. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  345. } else {
  346. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  347. }
  348. }
  349. }
  350. - (void)settingSetupCommunication:(NSString *)account
  351. {
  352. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  353. if (serverVersionMajor > 0) {
  354. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  355. }
  356. [[NCCommunicationCommon shared] setupWithWebDav:[[NCUtility shared] getWebDAVWithAccount:account]];
  357. [[NCCommunicationCommon shared] setupWithDav:[[NCUtility shared] getDAV]];
  358. }
  359. #pragma --------------------------------------------------------------------------------------------
  360. #pragma mark ===== Push Notifications =====
  361. #pragma --------------------------------------------------------------------------------------------
  362. - (void)pushNotification
  363. {
  364. // test
  365. if (self.account.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  366. return;
  367. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  368. NSString *token = [CCUtility getPushNotificationToken:result.account];
  369. if (![token isEqualToString:self.pushKitToken]) {
  370. if (token != nil) {
  371. // unsubscribing + subscribing
  372. [self unsubscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user withSubscribing:true];
  373. } else {
  374. [self subscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user];
  375. }
  376. }
  377. }
  378. }
  379. - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user
  380. {
  381. // test
  382. if (self.account.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  383. return;
  384. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  385. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  386. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  387. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  388. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  389. [[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) {
  390. if (errorCode == 0) {
  391. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  392. [[NCCommunication shared] subscribingPushProxyWithProxyServerUrl:proxyServerPath pushToken:self.pushKitToken deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  393. if (errorCode == 0) {
  394. [[NCCommunicationCommon shared] writeLog:@"[LOG] Subscribed to Push Notification server & proxy successfully"];
  395. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  396. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  397. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:signature];
  398. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  399. }
  400. }];
  401. }
  402. }];
  403. }
  404. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user withSubscribing:(BOOL)subscribing
  405. {
  406. // test
  407. if (self.account.length == 0 || self.maintenanceMode)
  408. return;
  409. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  410. NSString *signature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  411. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  412. [[NCCommunication shared] unsubscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDescription) {
  413. if (errorCode == 0) {
  414. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  415. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  416. [[NCCommunication shared] unsubscribingPushProxyWithProxyServerUrl:proxyServerPath deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  417. if (errorCode == 0) {
  418. [[NCCommunicationCommon shared] writeLog:@"[LOG] Unsubscribed to Push Notification server & proxy successfully."];
  419. [CCUtility setPushNotificationPublicKey:account data:nil];
  420. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  421. [CCUtility setPushNotificationPrivateKey:account data:nil];
  422. [CCUtility setPushNotificationToken:account token:nil];
  423. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  424. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  425. if (self.pushKitToken != nil && subscribing) {
  426. [self subscribingNextcloudServerPushNotification:account urlBase:urlBase user:user];
  427. }
  428. }
  429. }];
  430. }
  431. }];
  432. }
  433. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  434. {
  435. //Called when a notification is delivered to a foreground app.
  436. completionHandler(UNNotificationPresentationOptionAlert);
  437. }
  438. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  439. {
  440. completionHandler();
  441. }
  442. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  443. {
  444. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  445. [self pushNotification];
  446. }
  447. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  448. {
  449. NSString *message = [userInfo objectForKey:@"subject"];
  450. if (message) {
  451. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  452. for (tableAccount *result in results) {
  453. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  454. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  455. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  456. if (decryptedMessage) {
  457. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  458. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  459. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  460. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  461. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  462. if (delete) {
  463. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  464. } else if (deleteAll) {
  465. [self cleanAllNotifications];
  466. }
  467. }
  468. }
  469. }
  470. }
  471. completionHandler(UIBackgroundFetchResultNoData);
  472. }
  473. - (void)cleanAllNotifications
  474. {
  475. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  476. }
  477. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  478. {
  479. // Check in pending notifications
  480. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  481. for (UNNotificationRequest *notificationRequest in requests) {
  482. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  483. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  484. if (decryptedMessage) {
  485. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  486. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  487. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  488. if (nid == notificationId) {
  489. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  490. }
  491. }
  492. }
  493. }];
  494. // Check in delivered notifications
  495. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  496. for (UNNotification *notification in notifications) {
  497. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  498. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] 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] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  505. }
  506. }
  507. }
  508. }];
  509. }
  510. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  511. {
  512. const char *data = [deviceToken bytes];
  513. NSMutableString *token = [NSMutableString string];
  514. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  515. [token appendFormat:@"%02.2hhX", data[i]];
  516. }
  517. return [token copy];
  518. }
  519. #pragma --------------------------------------------------------------------------------------------
  520. #pragma mark ===== Quick Actions - ShotcutItem =====
  521. #pragma --------------------------------------------------------------------------------------------
  522. - (void)configDynamicShortcutItems
  523. {
  524. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  525. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  526. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  527. // add the array to our app
  528. if (shortcutMedia)
  529. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  530. }
  531. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  532. {
  533. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  534. completionHandler(handledShortCutItem);
  535. }
  536. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  537. {
  538. BOOL handled = NO;
  539. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  540. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  541. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.account) {
  542. dispatch_async(dispatch_get_main_queue(), ^{
  543. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  544. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  545. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  546. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  547. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  548. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  549. if (splitViewController.isCollapsed) {
  550. [navigationControllerMaster popToRootViewControllerAnimated:false];
  551. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  552. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  553. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  554. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  555. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  556. }
  557. }
  558. } else {
  559. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  560. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  561. }
  562. }
  563. }
  564. }
  565. }
  566. });
  567. handled = YES;
  568. }
  569. return handled;
  570. }
  571. #pragma --------------------------------------------------------------------------------------------
  572. #pragma mark ===== ApplicationIconBadgeNumber =====
  573. #pragma --------------------------------------------------------------------------------------------
  574. - (void)updateApplicationIconBadgeNumber
  575. {
  576. if (self.account.length == 0 || self.maintenanceMode) return;
  577. NSInteger counterDownload = [[NCOperationQueue shared] downloadCount];
  578. NSInteger counterUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] page:0 limit:0 sorted:@"fileName" ascending:NO].count;
  579. NSInteger total = counterDownload + counterUpload;
  580. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  581. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  582. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  583. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  584. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  585. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  586. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  587. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  588. if (total > 0) {
  589. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  590. } else {
  591. [tabBarItem setBadgeValue:nil];
  592. }
  593. }
  594. }
  595. }
  596. }
  597. #pragma --------------------------------------------------------------------------------------------
  598. #pragma mark ===== TabBarController =====
  599. #pragma --------------------------------------------------------------------------------------------
  600. - (void)createTabBarController:(UITabBarController *)tabBarController
  601. {
  602. UITabBarItem *item;
  603. NSLayoutConstraint *constraint;
  604. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  605. // File
  606. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  607. [item setTitle:NSLocalizedString(@"_home_", nil)];
  608. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  609. item.selectedImage = item.image;
  610. // Favorites
  611. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  612. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  613. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  614. item.selectedImage = item.image;
  615. // (PLUS INVISIBLE)
  616. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  617. item.title = @"";
  618. item.image = nil;
  619. item.enabled = false;
  620. // Media
  621. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  622. [item setTitle:NSLocalizedString(@"_media_", nil)];
  623. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"media"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  624. item.selectedImage = item.image;
  625. // More
  626. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  627. [item setTitle:NSLocalizedString(@"_more_", nil)];
  628. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  629. item.selectedImage = item.image;
  630. // Plus Button
  631. int buttonSize = 57;
  632. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  633. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  634. buttonPlus.tag = 99;
  635. buttonPlus.accessibilityLabel = NSLocalizedString(@"_accessibility_add_upload_", nil);
  636. [buttonPlus setImage:buttonImage forState:UIControlStateNormal];
  637. buttonPlus.backgroundColor = NCBrandColor.sharedInstance.brandElement;
  638. buttonPlus.layer.cornerRadius = buttonSize / 2;
  639. buttonPlus.layer.masksToBounds = NO;
  640. buttonPlus.layer.shadowOffset = CGSizeMake(0, 0);
  641. buttonPlus.layer.shadowRadius = 3.0f;
  642. buttonPlus.layer.shadowOpacity = 0.5;
  643. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  644. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  645. [tabBarController.tabBar addSubview:buttonPlus];
  646. if (safeAreaBottom > 0) {
  647. // X
  648. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  649. [tabBarController.view addConstraint:constraint];
  650. // Y
  651. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:-(buttonSize / 2)];
  652. [tabBarController.view addConstraint:constraint];
  653. // Width
  654. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  655. [tabBarController.view addConstraint:constraint];
  656. // Height
  657. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  658. [tabBarController.view addConstraint:constraint];
  659. } else {
  660. // X
  661. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  662. [tabBarController.view addConstraint:constraint];
  663. // Y
  664. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-(buttonSize / 2)];
  665. [tabBarController.view addConstraint:constraint];
  666. // Width
  667. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  668. [tabBarController.view addConstraint:constraint];
  669. // Height
  670. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  671. [tabBarController.view addConstraint:constraint];
  672. }
  673. }
  674. - (void)handleTouchTabbarCenter:(id)sender
  675. {
  676. // Test Maintenance
  677. if (self.maintenanceMode)
  678. return;
  679. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.account, self.activeMain.serverUrl]];
  680. if ([tableDirectory.permissions containsString:@"CK"]) {
  681. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  682. [self showMenuInViewController: vc];
  683. } else {
  684. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorInternalError forced:false];
  685. }
  686. }
  687. - (NSString *)getTabBarControllerActiveServerUrl
  688. {
  689. NSString *serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:self.urlBase account:self.account];
  690. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  691. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  692. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  693. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  694. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  695. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  696. NSInteger index = tabBarController.selectedIndex;
  697. // select active serverUrl
  698. if (index == k_tabBarApplicationIndexFile) {
  699. serverUrl = self.activeMain.serverUrl;
  700. } else if (index == k_tabBarApplicationIndexFavorite) {
  701. if (self.activeFavorites.serverUrl)
  702. serverUrl = self.activeFavorites.serverUrl;
  703. } else if (index == k_tabBarApplicationIndexMedia) {
  704. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPathWithUrlBase:self.urlBase account:self.account];
  705. }
  706. }
  707. }
  708. }
  709. return serverUrl;
  710. }
  711. #pragma --------------------------------------------------------------------------------------------
  712. #pragma mark ===== Theming Color =====
  713. #pragma --------------------------------------------------------------------------------------------
  714. - (void)settingThemingColorBrand
  715. {
  716. if (self.account.length == 0 || self.maintenanceMode)
  717. return;
  718. if ([NCBrandOptions sharedInstance].use_themingColor) {
  719. NSString *themingColor = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColor];
  720. NSString *themingColorElement = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  721. NSString *themingColorText = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorText];
  722. [CCGraphics settingThemingColor:themingColor themingColorElement:themingColorElement themingColorText:themingColorText];
  723. BOOL isTooLight = NCBrandColor.sharedInstance.brandElement.isTooLight;
  724. BOOL isTooDark = NCBrandColor.sharedInstance.brandElement.isTooDark;
  725. if (isTooLight) {
  726. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.brandElement darkerBy:10];
  727. } else if (isTooDark) {
  728. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.brandElement lighterBy:25];
  729. }
  730. } else {
  731. BOOL isTooLight = NCBrandColor.sharedInstance.customer.isTooLight;
  732. BOOL isTooDark = NCBrandColor.sharedInstance.customer.isTooDark;
  733. if (isTooLight) {
  734. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.customer darkerBy:10];
  735. } else if (isTooDark) {
  736. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.customer lighterBy:25];
  737. } else {
  738. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  739. }
  740. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  741. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  742. }
  743. [NCBrandColor.sharedInstance setDarkMode];
  744. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  745. [[NCMainCommon sharedInstance] createImagesThemingColor];
  746. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  747. });
  748. }
  749. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  750. {
  751. [NCBrandColor.sharedInstance setDarkMode];
  752. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  753. //Tab bar
  754. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  755. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  756. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  757. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  758. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  759. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  760. tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.backgroundView;
  761. tabBarController.tabBar.backgroundColor = NCBrandColor.sharedInstance.tabBar;
  762. tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  763. [tabBarController.tabBar viewWithTag:99].backgroundColor = NCBrandColor.sharedInstance.brandElement;
  764. }
  765. }
  766. }
  767. // Nav bar
  768. [self configureNavBarForViewController:viewController];
  769. // View
  770. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  771. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  772. // TableView
  773. if (tableView) {
  774. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  775. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  776. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  777. [tableView reloadData];
  778. }
  779. // CollectionView
  780. if (collectionView) {
  781. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  782. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  783. [collectionView reloadData];
  784. }
  785. }
  786. #pragma --------------------------------------------------------------------------------------------
  787. #pragma mark ===== Fetch =====
  788. #pragma --------------------------------------------------------------------------------------------
  789. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  790. {
  791. // Test Maintenance
  792. if (self.account.length == 0 || self.maintenanceMode) {
  793. completionHandler(UIBackgroundFetchResultNoData);
  794. return;
  795. }
  796. [[NCCommunicationCommon shared] writeLog:@"[LOG] Start perform Fetch With Completion Handler"];
  797. // Verify new photo
  798. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  799. // after 20 sec
  800. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  801. NSInteger results = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] page:0 limit:0 sorted:@"fileName" ascending:NO].count;
  802. if (results > 0) {
  803. completionHandler(UIBackgroundFetchResultNewData);
  804. } else {
  805. completionHandler(UIBackgroundFetchResultNoData);
  806. }
  807. [[NCCommunicationCommon shared] writeLog:@"[LOG] End 20 sec. perform Fetch With Completion Handler"];
  808. });
  809. }
  810. #pragma --------------------------------------------------------------------------------------------
  811. #pragma mark ===== Operation Networking & Session =====
  812. #pragma --------------------------------------------------------------------------------------------
  813. //
  814. // Method called by the system when all the background task has end
  815. //
  816. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  817. {
  818. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"[LOG] Start handle Events For Background URLSession: %@", identifier]];
  819. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  820. self.backgroundSessionCompletionHandler = completionHandler;
  821. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  822. self.backgroundSessionCompletionHandler = nil;
  823. completionHandler();
  824. });
  825. }
  826. #pragma --------------------------------------------------------------------------------------------
  827. #pragma mark ===== OpenURL =====
  828. #pragma --------------------------------------------------------------------------------------------
  829. // Method called from iOS system to send a file from other app.
  830. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  831. {
  832. if (self.account.length == 0 || self.maintenanceMode)
  833. return YES;
  834. NSString *scheme = url.scheme;
  835. dispatch_time_t timer = 0;
  836. if (self.activeMain == nil) timer = 1;
  837. if ([scheme isEqualToString:@"nextcloud"]) {
  838. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  839. NSString *action = url.host;
  840. if ([action isEqualToString:@"open-file"]) {
  841. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  842. NSArray *queryItems = urlComponents.queryItems;
  843. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  844. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  845. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  846. tableAccount *matchedAccount = nil;
  847. // verify parameter
  848. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  849. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  850. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  851. [alertController addAction:okAction];
  852. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  853. } else {
  854. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  855. if (account) {
  856. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  857. NSString *accountUser = account.user;
  858. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  859. matchedAccount = account;
  860. } else {
  861. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  862. for (tableAccount *account in accounts) {
  863. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  864. NSString *accountUser = account.user;
  865. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  866. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  867. [self settingAccount:matchedAccount.account urlBase:matchedAccount.urlBase user:matchedAccount.user userID:matchedAccount.userID password:[CCUtility getPassword:matchedAccount.account]];
  868. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  869. }
  870. }
  871. }
  872. if (matchedAccount) {
  873. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  874. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  875. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  876. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  877. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  878. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  879. if (splitViewController.isCollapsed) {
  880. [navigationControllerMaster popToRootViewControllerAnimated:false];
  881. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  882. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  883. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  884. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  885. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  886. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  887. }
  888. }
  889. }
  890. } else {
  891. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  892. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  893. }
  894. }
  895. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  896. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  897. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  898. NSString *webDAV = [[NCUtility shared] getWebDAVWithAccount:self.account];
  899. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, path];
  900. if ([path containsString:@"/"]) {
  901. // Push
  902. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  903. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, [path stringByDeletingLastPathComponent]]];
  904. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase: @"" url:@"" contentType:@"" livePhoto:false];
  905. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  906. } else {
  907. // Reload folder
  908. NSString *serverUrl = [NSString stringWithFormat:@"%@/%@", matchedAccount.urlBase, webDAV];
  909. self.activeMain.blinkFileNamePath = fileNamePath;
  910. [self.activeMain readFolder:serverUrl];
  911. }
  912. });
  913. });
  914. }
  915. }
  916. }
  917. } else {
  918. NSString *domain = [[NSURL URLWithString:link] host];
  919. NSString *fileName = [path lastPathComponent];
  920. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  921. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  922. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  923. [alertController addAction:okAction];
  924. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  925. }
  926. }
  927. }
  928. }
  929. });
  930. return YES;
  931. }
  932. NSError *error;
  933. NSLog(@"[LOG] the path is: %@", url.path);
  934. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  935. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  936. if (self.account) {
  937. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  938. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  939. if (error == nil) {
  940. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  941. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  942. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  943. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  944. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  945. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  946. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  947. });
  948. }
  949. }
  950. }
  951. }
  952. return YES;
  953. }
  954. #pragma --------------------------------------------------------------------------------------------
  955. #pragma mark ===== Passcode + Delegate =====
  956. #pragma --------------------------------------------------------------------------------------------
  957. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  958. {
  959. LAContext *laContext = [LAContext new];
  960. NSError *error;
  961. BOOL isBiometryAvailable = false;
  962. if ([[CCUtility getPasscode] length] == 0 || [self.account length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  963. if (self.passcodeViewController == nil) {
  964. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  965. if (@available(iOS 13.0, *)) {
  966. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  967. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  968. }
  969. }
  970. self.passcodeViewController.delegate = self;
  971. self.passcodeViewController.keypadButtonShowLettering = false;
  972. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  973. if (error == NULL) {
  974. if (laContext.biometryType == LABiometryTypeFaceID) {
  975. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  976. self.passcodeViewController.allowBiometricValidation = true;
  977. isBiometryAvailable = true;
  978. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  979. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  980. self.passcodeViewController.allowBiometricValidation = true;
  981. isBiometryAvailable = true;
  982. } else {
  983. isBiometryAvailable = false;
  984. NSLog(@"No Biometric support");
  985. }
  986. }
  987. }
  988. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  989. }
  990. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  991. if (CCUtility.getEnableTouchFaceID && automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  992. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  993. if (success) {
  994. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  995. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  996. self.passcodeViewController = nil;
  997. }];
  998. });
  999. }
  1000. }];
  1001. }
  1002. });
  1003. }
  1004. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1005. {
  1006. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1007. self.passcodeViewController = nil;
  1008. }];
  1009. }
  1010. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1011. {
  1012. return [code isEqualToString:[CCUtility getPasscode]];
  1013. }
  1014. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1015. {
  1016. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1017. if (success) {
  1018. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1019. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1020. self.passcodeViewController = nil;
  1021. }];
  1022. });
  1023. }
  1024. }];
  1025. }
  1026. #pragma --------------------------------------------------------------------------------------------
  1027. #pragma mark ===== Maintenance Mode =====
  1028. #pragma --------------------------------------------------------------------------------------------
  1029. - (void)maintenanceMode:(BOOL)mode
  1030. {
  1031. self.maintenanceMode = mode;
  1032. }
  1033. @end