AppDelegate.m 67 KB

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