AppDelegate.m 66 KB

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