AppDelegate.m 67 KB

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