AppDelegate.m 67 KB

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