AppDelegate.m 61 KB

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