AppDelegate.m 76 KB

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