AppDelegate.m 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import "CCGraphics.h"
  25. #import "CCMain.h"
  26. #import "NCBridgeSwift.h"
  27. #import "NCAutoUpload.h"
  28. #import "NCPushNotificationEncryption.h"
  29. #import <QuartzCore/QuartzCore.h>
  30. @import Sentry;
  31. @class NCViewerRichdocument;
  32. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  33. @end
  34. @implementation AppDelegate
  35. + (void)initialize
  36. {
  37. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  38. }
  39. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  40. {
  41. if ([[NCUtility shared] isSimulatorOrTestFlight]) {
  42. NCBrandOptions.sharedInstance.disable_crash_service = false;
  43. }
  44. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  45. [SentrySDK startWithOptions: @{
  46. @"dsn": @"https://42eaf570ec2646b1a564a4c4bfc8c279@o394108.ingest.sentry.io/5243836",
  47. @"debug": @(YES),
  48. @"enableAutoSessionTracking": @(YES)
  49. /* PRIVACY : https://github.com/getsentry/sentry-cocoa
  50. By default, we don’t apply the user identification provided to the SDK via the API. Instead, we use
  51. the installation ID generated with the first use of the application. The ID doesn’t contain any
  52. private or public data of your users or any public or shared data of their device.
  53. */
  54. }];
  55. }
  56. [CCUtility createDirectoryStandard];
  57. [CCUtility emptyTemporaryDirectory];
  58. // Networking
  59. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  60. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups];
  61. [[NCCommunicationCommon shared] setFileLogWithLevel:1];
  62. [[NCCommunicationCommon shared] writeLog:@"[LOG] Start session"];
  63. // Set account, if no exists clear all
  64. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  65. if (tableAccount == nil) {
  66. // remove all the keys Chain
  67. [CCUtility deleteAllChainStore];
  68. // remove all the App group key
  69. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  70. } else {
  71. [self settingAccount:tableAccount.account urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  72. }
  73. // UserDefaults
  74. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  75. // Background Fetch
  76. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  77. self.listProgressMetadata = [NSMutableDictionary new];
  78. self.listMainVC = [NSMutableDictionary new];
  79. // Push Notification
  80. [application registerForRemoteNotifications];
  81. // Display notification
  82. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  83. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  84. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  85. //AV Session
  86. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  87. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  88. // ProgressView Detail
  89. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  90. // Quick Actions
  91. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  92. [self configDynamicShortcutItems];
  93. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  94. if (shortcutItem)
  95. [self handleShortCutItem:shortcutItem];
  96. }
  97. // Start Timer
  98. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  99. [self startTimerErrorNetworking];
  100. // Store review
  101. if ([[NCUtility shared] isSimulatorOrTestFlight] == false) {
  102. NCStoreReview *review = [NCStoreReview new];
  103. [review incrementAppRuns];
  104. [review showStoreReview];
  105. }
  106. // Detect Dark mode
  107. if (@available(iOS 13.0, *)) {
  108. if ([CCUtility getDarkModeDetect]) {
  109. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  110. [CCUtility setDarkMode:YES];
  111. } else {
  112. [CCUtility setDarkMode:NO];
  113. }
  114. }
  115. }
  116. if ([NCBrandOptions sharedInstance].disable_intro) {
  117. [CCUtility setIntro:YES];
  118. if (self.account.length == 0) {
  119. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  120. }
  121. } else {
  122. if ([CCUtility getIntro] == NO) {
  123. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  124. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  125. self.window.rootViewController = navController;
  126. [self.window makeKeyAndVisible];
  127. }
  128. }
  129. // init home
  130. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  131. // Passcode
  132. dispatch_async(dispatch_get_main_queue(), ^{
  133. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  134. });
  135. // Auto upload
  136. self.networkingAutoUpload = [NCNetworkingAutoUpload new];
  137. return YES;
  138. }
  139. //
  140. // L' applicazione si dimetterà dallo stato di attivo
  141. //
  142. - (void)applicationWillResignActive:(UIApplication *)application
  143. {
  144. // Test Maintenance
  145. if (self.account.length == 0 || self.maintenanceMode)
  146. return;
  147. [self updateApplicationIconBadgeNumber];
  148. }
  149. //
  150. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  151. //
  152. - (void)applicationWillEnterForeground:(UIApplication *)application
  153. {
  154. if (self.account.length == 0 || self.maintenanceMode) { return; }
  155. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationWillEnterForeground object:nil];
  156. NSLog(@"[LOG] Request Passcode");
  157. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  158. NSLog(@"[LOG] Request Service Server Nextcloud");
  159. [[NCService shared] startRequestServicesServer];
  160. NSLog(@"[LOG] Initialize Auto upload");
  161. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  162. NSLog(@"[LOG] Read active directory");
  163. [self.activeMain readFileReloadFolder];
  164. NSLog(@"[LOG] Required unsubscribing / subscribing");
  165. [self pushNotification];
  166. NSLog(@"[LOG] RichDocument");
  167. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  168. }
  169. //
  170. // L' applicazione entrerà in primo piano (attivo sempre)
  171. //
  172. - (void)applicationDidBecomeActive:(UIApplication *)application
  173. {
  174. if (self.account.length == 0 || self.maintenanceMode) { return; }
  175. // Brand
  176. #if defined(HC)
  177. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  178. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  179. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  180. vc.account = account;
  181. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  182. }
  183. #endif
  184. [[NCNetworking shared] verifyUploadZombie];
  185. }
  186. //
  187. // L' applicazione è entrata nello sfondo
  188. //
  189. - (void)applicationDidEnterBackground:(UIApplication *)application
  190. {
  191. if (self.account.length == 0 || self.maintenanceMode) { return; }
  192. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  193. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  194. }
  195. //
  196. // L'applicazione terminerà
  197. //
  198. - (void)applicationWillTerminate:(UIApplication *)application
  199. {
  200. NSLog(@"[LOG] bye bye, Nextcloud !");
  201. }
  202. #pragma --------------------------------------------------------------------------------------------
  203. #pragma mark ===== Login / checkErrorNetworking =====
  204. #pragma --------------------------------------------------------------------------------------------
  205. - (void)checkErrorNetworking
  206. {
  207. // test
  208. if (self.account.length == 0 || self.maintenanceMode)
  209. return;
  210. // check unauthorized server (401)
  211. if ([CCUtility getPassword:self.account].length == 0) {
  212. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  213. }
  214. // check certificate untrusted (-1202)
  215. if ([CCUtility getCertificateError:self.account]) {
  216. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  217. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  218. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  219. [self startTimerErrorNetworking];
  220. }]];
  221. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  222. [self startTimerErrorNetworking];
  223. }]];
  224. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  225. // Stop timer error network
  226. [self.timerErrorNetworking invalidate];
  227. }];
  228. }
  229. }
  230. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  231. {
  232. // use appConfig [MDM]
  233. if ([NCBrandOptions sharedInstance].use_configuration) {
  234. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  235. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  236. [self showLoginViewController:self.appConfigView forContext:viewController];
  237. }
  238. return;
  239. }
  240. // only for personalized LoginWeb [customer]
  241. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  242. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  243. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  244. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  245. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  246. }
  247. return;
  248. }
  249. // normal login
  250. if (selector == k_intro_signup) {
  251. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  252. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  253. if (selector == k_intro_signup) {
  254. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  255. } else {
  256. self.activeLoginWeb.urlBase = self.urlBase;
  257. }
  258. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  259. }
  260. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  261. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  262. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  263. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  264. } else if (openLoginWeb) {
  265. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  266. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  267. self.activeLoginWeb.urlBase = self.urlBase;
  268. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  269. }
  270. } else {
  271. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  272. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  273. [self showLoginViewController:_activeLogin forContext:viewController];
  274. }
  275. }
  276. }
  277. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  278. {
  279. if (contextViewController == NULL) {
  280. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  281. navController.navigationBar.barStyle = UIBarStyleBlack;
  282. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  283. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  284. [navController.navigationBar setTranslucent:false];
  285. self.window.rootViewController = navController;
  286. [self.window makeKeyAndVisible];
  287. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  288. UINavigationController *navController = ((UINavigationController *)contextViewController);
  289. [navController pushViewController:viewController animated:true];
  290. } else {
  291. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  292. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  293. navController.navigationBar.barStyle = UIBarStyleBlack;
  294. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  295. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  296. [navController.navigationBar setTranslucent:false];
  297. [contextViewController presentViewController:navController animated:true completion:nil];
  298. }
  299. }
  300. - (void)startTimerErrorNetworking
  301. {
  302. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  303. }
  304. #pragma --------------------------------------------------------------------------------------------
  305. #pragma mark ===== Account & Communication =====
  306. #pragma --------------------------------------------------------------------------------------------
  307. - (void)settingAccount:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user userID:(NSString *)userID password:(NSString *)password
  308. {
  309. self.account = account;
  310. self.urlBase = urlBase;
  311. self.user = user;
  312. self.userID = userID;
  313. self.password = password;
  314. (void)[NCNetworkingNotificationCenter shared];
  315. [[NCCommunicationCommon shared] setupWithAccount:account user:user userId:userID password:password urlBase:urlBase];
  316. [self settingSetupCommunication:account];
  317. }
  318. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  319. {
  320. // Push Notification
  321. tableAccount *accountPN = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  322. [self unsubscribingNextcloudServerPushNotification:accountPN.account urlBase:accountPN.urlBase user:accountPN.user withSubscribing:false];
  323. [self settingAccount:nil urlBase:nil user:nil userID:nil password:nil];
  324. /* DELETE ALL FILES LOCAL FS */
  325. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  326. for (tableLocalFile *result in results) {
  327. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  328. }
  329. // Clear database
  330. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  331. [CCUtility clearAllKeysEndToEnd:account];
  332. [CCUtility clearAllKeysPushNotification:account];
  333. [CCUtility setCertificateError:account error:false];
  334. [CCUtility setPassword:account password:nil];
  335. if (wipe) {
  336. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  337. if ([listAccount count] > 0) {
  338. NSString *newAccount = listAccount[0];
  339. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  340. [self settingAccount:newAccount urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  341. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  342. } else {
  343. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  344. }
  345. }
  346. }
  347. - (void)settingSetupCommunication:(NSString *)account
  348. {
  349. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  350. if (serverVersionMajor > 0) {
  351. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  352. }
  353. [[NCCommunicationCommon shared] setupWithWebDav:[[NCUtility shared] getWebDAVWithAccount:account]];
  354. [[NCCommunicationCommon shared] setupWithDav:[[NCUtility shared] getDAV]];
  355. }
  356. #pragma --------------------------------------------------------------------------------------------
  357. #pragma mark ===== Push Notifications =====
  358. #pragma --------------------------------------------------------------------------------------------
  359. - (void)pushNotification
  360. {
  361. // test
  362. if (self.account.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 urlBase:result.urlBase user:result.user withSubscribing:true];
  370. } else {
  371. [self subscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user];
  372. }
  373. }
  374. }
  375. }
  376. - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user
  377. {
  378. // test
  379. if (self.account.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:urlBase account:account user:user password:[CCUtility getPassword:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSInteger errorCode, NSString *errorDescription) {
  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 urlBase:(NSString *)urlBase user:(NSString *)user withSubscribing:(BOOL)subscribing
  402. {
  403. // test
  404. if (self.account.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:urlBase 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 urlBase:urlBase 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.account) {
  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.account.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.account, 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 = [[NCUtility shared] getHomeServerWithUrlBase:self.urlBase account:self.account];
  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] getAccountAutoUploadPathWithUrlBase:self.urlBase account:self.account];
  701. }
  702. }
  703. }
  704. }
  705. return serverUrl;
  706. }
  707. #pragma --------------------------------------------------------------------------------------------
  708. #pragma mark ===== Theming Color =====
  709. #pragma --------------------------------------------------------------------------------------------
  710. - (void)settingThemingColorBrand
  711. {
  712. if (self.account.length == 0 || self.maintenanceMode)
  713. return;
  714. if ([NCBrandOptions sharedInstance].use_themingColor) {
  715. NSString *themingColor = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColor];
  716. NSString *themingColorElement = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  717. NSString *themingColorText = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account 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.account.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.account.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 *accountURL = [NSURL URLWithString:account.urlBase];
  853. NSString *accountUser = account.user;
  854. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  855. matchedAccount = account;
  856. } else {
  857. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  858. for (tableAccount *account in accounts) {
  859. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  860. NSString *accountUser = account.user;
  861. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  862. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  863. [self settingAccount:matchedAccount.account urlBase:matchedAccount.urlBase user:matchedAccount.user userID:matchedAccount.userID password:[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 *webDAV = [[NCUtility shared] getWebDAVWithAccount:self.account];
  895. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, path];
  896. if ([path containsString:@"/"]) {
  897. // Push
  898. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  899. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.urlBase, webDAV, [path stringByDeletingLastPathComponent]]];
  900. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase: @"" url:@"" contentType:@"" livePhoto:false];
  901. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  902. } else {
  903. // Reload folder
  904. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.urlBase, webDAV];
  905. self.activeMain.blinkFileNamePath = fileNamePath;
  906. [self.activeMain readFolder:serverUrl];
  907. }
  908. });
  909. });
  910. }
  911. }
  912. }
  913. } else {
  914. NSString *domain = [[NSURL URLWithString:link] host];
  915. NSString *fileName = [path lastPathComponent];
  916. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  917. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  918. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  919. [alertController addAction:okAction];
  920. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  921. }
  922. }
  923. }
  924. }
  925. });
  926. return YES;
  927. }
  928. NSError *error;
  929. NSLog(@"[LOG] the path is: %@", url.path);
  930. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  931. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  932. if (self.account) {
  933. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  934. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  935. if (error == nil) {
  936. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  937. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  938. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  939. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  940. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  941. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  942. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  943. });
  944. }
  945. }
  946. }
  947. }
  948. return YES;
  949. }
  950. #pragma --------------------------------------------------------------------------------------------
  951. #pragma mark ===== Passcode + Delegate =====
  952. #pragma --------------------------------------------------------------------------------------------
  953. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  954. {
  955. LAContext *laContext = [LAContext new];
  956. NSError *error;
  957. BOOL isBiometryAvailable = false;
  958. if ([[CCUtility getPasscode] length] == 0 || [self.account length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  959. if (self.passcodeViewController == nil) {
  960. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  961. if (@available(iOS 13.0, *)) {
  962. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  963. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  964. }
  965. }
  966. self.passcodeViewController.delegate = self;
  967. self.passcodeViewController.keypadButtonShowLettering = false;
  968. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  969. if (error == NULL) {
  970. if (laContext.biometryType == LABiometryTypeFaceID) {
  971. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  972. self.passcodeViewController.allowBiometricValidation = true;
  973. isBiometryAvailable = true;
  974. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  975. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  976. self.passcodeViewController.allowBiometricValidation = true;
  977. isBiometryAvailable = true;
  978. } else {
  979. isBiometryAvailable = false;
  980. NSLog(@"No Biometric support");
  981. }
  982. }
  983. }
  984. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  985. }
  986. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  987. if (CCUtility.getEnableTouchFaceID && automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  988. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  989. if (success) {
  990. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  991. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  992. self.passcodeViewController = nil;
  993. }];
  994. });
  995. }
  996. }];
  997. }
  998. });
  999. }
  1000. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1001. {
  1002. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1003. self.passcodeViewController = nil;
  1004. }];
  1005. }
  1006. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1007. {
  1008. return [code isEqualToString:[CCUtility getPasscode]];
  1009. }
  1010. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1011. {
  1012. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1013. if (success) {
  1014. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1015. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1016. self.passcodeViewController = nil;
  1017. }];
  1018. });
  1019. }
  1020. }];
  1021. }
  1022. #pragma --------------------------------------------------------------------------------------------
  1023. #pragma mark ===== Maintenance Mode =====
  1024. #pragma --------------------------------------------------------------------------------------------
  1025. - (void)maintenanceMode:(BOOL)mode
  1026. {
  1027. self.maintenanceMode = mode;
  1028. }
  1029. @end