AppDelegate.m 66 KB

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