AppDelegate.m 66 KB

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