AppDelegate.m 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. //
  2. // AppDelegate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 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 <JDStatusBarNotification/JDStatusBarNotification.h>
  25. #import "AFURLSessionManager.h"
  26. #import "CCNetworking.h"
  27. #import "CCGraphics.h"
  28. #import "CCMedia.h"
  29. #import "CCSynchronize.h"
  30. #import "CCMain.h"
  31. #import "CCDetail.h"
  32. #import <Fabric/Fabric.h>
  33. #import <Crashlytics/Crashlytics.h>
  34. #import "NCBridgeSwift.h"
  35. #import "NCAutoUpload.h"
  36. #import "Firebase.h"
  37. #import "NCPushNotificationEncryption.h"
  38. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  39. @end
  40. @implementation AppDelegate
  41. + (void)initialize
  42. {
  43. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  44. }
  45. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  46. {
  47. NSString *path;
  48. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  49. NSLog(@"[LOG] Start program group -----------------");
  50. NSLog(@"%@", [dirGroup path]);
  51. NSLog(@"[LOG] Start program application -----------");
  52. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  53. NSLog(@"[LOG] -------------------------------------");
  54. // create Directory Documents
  55. path = [CCUtility getDirectoryDocuments];
  56. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  57. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  58. // create Directory audio => Library, Application Support, audio
  59. path = [CCUtility getDirectoryAudio];
  60. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  61. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  62. // create Directory database Nextcloud
  63. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  64. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  65. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  66. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  67. // create Directory User Data
  68. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  69. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  70. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  71. // create Directory Provider Storage
  72. path = [CCUtility getDirectoryProviderStorage];
  73. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  74. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  75. // create Directory Scan
  76. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  77. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  78. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  79. // Verify upgrade
  80. if ([self upgrade]) {
  81. // Set account, if no exists clear all
  82. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  83. if (account == nil) {
  84. // remove all the keys Chain
  85. [CCUtility deleteAllChainStore];
  86. // remove all the App group key
  87. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  88. } else {
  89. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  90. }
  91. }
  92. #ifdef DEBUG
  93. NSLog(@"[LOG] Copy DB on Documents directory");
  94. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  95. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  96. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  97. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  98. #endif
  99. // UserDefaults
  100. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  101. // Initialization Share
  102. self.sharesID = [NSMutableDictionary new];
  103. self.sharesLink = [NSMutableDictionary new];
  104. self.sharesUserAndGroup = [NSMutableDictionary new];
  105. // Filter fileID
  106. self.filterFileID = [NSMutableArray new];
  107. // Upload Pending In Upload (crash)
  108. self.sessionPendingStatusInUpload = [NSMutableArray new];
  109. // Initialization Notification
  110. self.listOfNotifications = [NSMutableArray new];
  111. // Background Fetch
  112. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  113. // Initialization List
  114. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  115. self.listMainVC = [[NSMutableDictionary alloc] init];
  116. // Firebase - Push Notification
  117. @try {
  118. [FIRApp configure];
  119. } @catch (NSException *exception) {
  120. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  121. }
  122. // Display notification (sent via APNS)
  123. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  124. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  125. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  126. }];
  127. [application registerForRemoteNotifications];
  128. [FIRMessaging messaging].delegate = self;
  129. // setting Reachable in back
  130. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  131. self.reachability = [Reachability reachabilityForInternetConnection];
  132. self.lastReachability = [self.reachability isReachable];
  133. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  134. [self.reachability startNotifier];
  135. });
  136. //AV Session
  137. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  138. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  139. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  140. // How to hide UINavigationBar 1px bottom line < iOS 11
  141. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  142. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  143. // passcode
  144. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  145. dispatch_async(dispatch_get_main_queue(), ^{
  146. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  147. });
  148. // Quick Actions
  149. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  150. [self configDynamicShortcutItems];
  151. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  152. if (shortcutItem)
  153. [self handleShortCutItem:shortcutItem];
  154. }
  155. // Start Timer
  156. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  157. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  158. // Fabric
  159. [Fabric with:@[[Crashlytics class]]];
  160. [self logUser];
  161. // Store review
  162. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  163. NCStoreReview *review = [NCStoreReview new];
  164. [review incrementAppRuns];
  165. [review showStoreReview];
  166. }
  167. return YES;
  168. }
  169. //
  170. // L' applicazione si dimetterà dallo stato di attivo
  171. //
  172. - (void)applicationWillResignActive:(UIApplication *)application
  173. {
  174. [_activeMain closeAllMenu];
  175. [self updateApplicationIconBadgeNumber];
  176. }
  177. //
  178. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  179. //
  180. - (void)applicationWillEnterForeground:(UIApplication *)application
  181. {
  182. // Test Maintenance
  183. if (self.activeAccount.length == 0 || self.maintenanceMode)
  184. return;
  185. NSLog(@"[LOG] Request Service Server Nextcloud");
  186. [[NCService sharedInstance] startRequestServicesServer];
  187. NSLog(@"[LOG] Initialize Auto upload");
  188. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  189. NSLog(@"[LOG] Read active directory");
  190. [self.activeMain readFileReloadFolder];
  191. }
  192. //
  193. // L' applicazione entrerà in primo piano (attivo sempre)
  194. //
  195. - (void)applicationDidBecomeActive:(UIApplication *)application
  196. {
  197. // Test Maintenance
  198. if (self.activeAccount.length == 0 || self.maintenanceMode)
  199. return;
  200. // middelware ping
  201. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  202. NSLog(@"[LOG] Middleware Ping");
  203. [[NCService sharedInstance] middlewarePing];
  204. }
  205. }
  206. //
  207. // L' applicazione è entrata nello sfondo
  208. //
  209. - (void)applicationDidEnterBackground:(UIApplication *)application
  210. {
  211. NSLog(@"[LOG] Enter in Background");
  212. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  213. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  214. __block UIBackgroundTaskIdentifier background_task;
  215. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  216. //Clean up code. Tell the system that we are done.
  217. [application endBackgroundTask: background_task];
  218. background_task = UIBackgroundTaskInvalid;
  219. }];
  220. }
  221. }
  222. //
  223. // L'applicazione terminerà
  224. //
  225. - (void)applicationWillTerminate:(UIApplication *)application
  226. {
  227. NSLog(@"[LOG] bye bye, Nextcloud !");
  228. }
  229. #pragma --------------------------------------------------------------------------------------------
  230. #pragma mark ===== Login =====
  231. #pragma --------------------------------------------------------------------------------------------
  232. - (void)openLoginView:(id)delegate loginType:(NSInteger)loginType selector:(NSInteger)selector
  233. {
  234. BOOL loginWebFlow = NO;
  235. @synchronized (self) {
  236. // only for personalized LoginWeb [customer]
  237. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  238. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  239. _activeLoginWeb = [CCLoginWeb new];
  240. _activeLoginWeb.delegate = delegate;
  241. _activeLoginWeb.loginType = loginType;
  242. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  243. dispatch_async(dispatch_get_main_queue(), ^ {
  244. [_activeLoginWeb open:delegate];
  245. });
  246. }
  247. return;
  248. }
  249. // ------------------- Nextcloud -------------------------
  250. //
  251. // Login flow : LoginWeb
  252. if (loginType == k_login_Modify_Password) {
  253. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  254. if (account.loginFlow)
  255. loginWebFlow = YES;
  256. }
  257. if (loginWebFlow || selector == k_intro_signup) {
  258. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  259. _activeLoginWeb = [CCLoginWeb new];
  260. _activeLoginWeb.delegate = delegate;
  261. _activeLoginWeb.loginType = loginType;
  262. if (selector == k_intro_signup) {
  263. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  264. } else {
  265. _activeLoginWeb.urlBase = self.activeUrl;
  266. }
  267. dispatch_async(dispatch_get_main_queue(), ^ {
  268. [_activeLoginWeb open:delegate];
  269. });
  270. }
  271. } else {
  272. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  273. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  274. _activeLogin.delegate = delegate;
  275. _activeLogin.loginType = loginType;
  276. dispatch_async(dispatch_get_main_queue(), ^ {
  277. [delegate presentViewController:_activeLogin animated:YES completion:nil];
  278. });
  279. }
  280. }
  281. }
  282. }
  283. #pragma --------------------------------------------------------------------------------------------
  284. #pragma mark ===== Setting Active Account for all APP =====
  285. #pragma --------------------------------------------------------------------------------------------
  286. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  287. {
  288. self.activeAccount = activeAccount;
  289. self.activeUrl = activeUrl;
  290. self.activeUser = activeUser;
  291. self.activeUserID = activeUserID;
  292. self.activePassword = activePassword;
  293. // Setting Account to CCNetworking
  294. [CCNetworking sharedNetworking].delegate = [NCNetworkingMain sharedInstance];
  295. }
  296. #pragma --------------------------------------------------------------------------------------------
  297. #pragma mark ===== Push Notification =====
  298. #pragma --------------------------------------------------------------------------------------------
  299. - (void)subscribingNextcloudServerPushNotification
  300. {
  301. // test
  302. if (self.activeAccount.length == 0 || self.maintenanceMode)
  303. return;
  304. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair];
  305. NSString *pushToken = [CCUtility getPushNotificationToken];
  306. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:pushToken];
  307. NSString *devicePublicKey = [[NSString alloc] initWithData:[NCPushNotificationEncryption sharedInstance].ncPNPublicKey encoding:NSUTF8StringEncoding];
  308. self.pnDeviceIdentifier = nil;
  309. self.pnDeviceIdentifierSignature = nil;
  310. self.pnPublicKey = nil;
  311. [[OCnetworking sharedManager] subscribingPushNotificationWithAccount:self.activeAccount url:self.activeUrl pushToken:pushToken Hash:pushTokenHash devicePublicKey:devicePublicKey completion:^(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  312. if (errorCode == 0 && [account isEqualToString:self.activeAccount]) {
  313. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  314. self.pnDeviceIdentifier = deviceIdentifier;
  315. self.pnDeviceIdentifierSignature = deviceIdentifierSignature;
  316. self.pnPublicKey = publicKey;
  317. } else if (errorCode != 0) {
  318. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  319. }
  320. }];
  321. }
  322. - (void)unsubscribingNextcloudServerPushNotification
  323. {
  324. // test
  325. if (self.activeAccount.length == 0 || self.maintenanceMode)
  326. return;
  327. [[OCnetworking sharedManager] unsubscribingPushNotificationWithAccount:self.activeAccount url:self.activeUrl deviceIdentifier:self.pnDeviceIdentifier deviceIdentifierSignature:self.pnDeviceIdentifierSignature publicKey:self.pnPublicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  328. if (errorCode == 0) {
  329. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  330. } else {
  331. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  332. }
  333. }];
  334. }
  335. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  336. {
  337. //Called when a notification is delivered to a foreground app.
  338. completionHandler(UNNotificationPresentationOptionAlert);
  339. }
  340. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  341. {
  342. /*
  343. NSString *message = [response.notification.request.content.userInfo objectForKey:@"subject"];
  344. if (message && [NCPushNotificationEncryption sharedInstance].ncPNPrivateKey) {
  345. NSData *privateKey = [CCUtility getPushNotificationPrivateKey];
  346. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:privateKey];
  347. if (decryptedMessage) {
  348. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  349. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  350. NSString *app = [json objectForKey:@"app"];
  351. if ([app isEqualToString:@"spreed"] == NO) {
  352. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  353. UINavigationController *navigationControllerMore;
  354. UITabBarController *tabBarController;
  355. if (splitViewController.isCollapsed) {
  356. tabBarController = splitViewController.viewControllers.firstObject;
  357. for (UINavigationController *nvc in tabBarController.viewControllers) {
  358. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  359. [nvc popToRootViewControllerAnimated:NO];
  360. if ([nvc.topViewController isKindOfClass:[CCMore class]])
  361. navigationControllerMore = nvc;
  362. }
  363. } else {
  364. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  365. [nvcDetail popToRootViewControllerAnimated:NO];
  366. tabBarController = splitViewController.viewControllers.firstObject;
  367. }
  368. if (tabBarController)
  369. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMore];
  370. if (navigationControllerMore)
  371. [navigationControllerMore performSegueWithIdentifier:@"segueActivity" sender:navigationControllerMore];
  372. }
  373. }
  374. }
  375. */
  376. completionHandler();
  377. }
  378. #pragma FIREBASE
  379. - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
  380. {
  381. // test
  382. if (self.activeAccount.length == 0 || self.maintenanceMode)
  383. return;
  384. NSLog(@"FCM registration token: %@", fcmToken);
  385. [CCUtility setPushNotificationToken:fcmToken];
  386. [self subscribingNextcloudServerPushNotification];
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ===== Quick Actions - ShotcutItem =====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)configDynamicShortcutItems
  392. {
  393. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  394. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionMedia"];
  395. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  396. // add the array to our app
  397. if (shortcutMedia)
  398. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  399. }
  400. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  401. {
  402. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  403. completionHandler(handledShortCutItem);
  404. }
  405. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  406. {
  407. BOOL handled = NO;
  408. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  409. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  410. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  411. dispatch_async(dispatch_get_main_queue(), ^{
  412. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  413. if (splitViewController.isCollapsed) {
  414. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  415. for (UINavigationController *nvc in tbc.viewControllers) {
  416. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  417. [nvc popToRootViewControllerAnimated:NO];
  418. }
  419. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  420. } else {
  421. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  422. [nvcDetail popToRootViewControllerAnimated:NO];
  423. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  424. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  425. }
  426. });
  427. handled = YES;
  428. }
  429. return handled;
  430. }
  431. #pragma --------------------------------------------------------------------------------------------
  432. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  433. #pragma --------------------------------------------------------------------------------------------
  434. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  435. {
  436. static NSInteger errorCodePrev = 0;
  437. dispatch_async(dispatch_get_main_queue(), ^{
  438. if (visible) {
  439. switch (errorcode) {
  440. // JDStatusBarNotification
  441. case kCFURLErrorNotConnectedToInternet :
  442. if (errorCodePrev != errorcode)
  443. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  444. errorCodePrev = errorcode;
  445. break;
  446. // TWMessageBarManager
  447. default:
  448. if (description.length > 0) {
  449. [TWMessageBarManager sharedInstance].styleSheet = self;
  450. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  451. }
  452. break;
  453. }
  454. } else {
  455. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  456. }
  457. });
  458. }
  459. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  460. {
  461. UIColor *backgroundColor = nil;
  462. switch (type)
  463. {
  464. case TWMessageBarMessageTypeError:
  465. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  466. break;
  467. case TWMessageBarMessageTypeSuccess:
  468. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  469. break;
  470. case TWMessageBarMessageTypeInfo:
  471. backgroundColor = [NCBrandColor sharedInstance].brand;
  472. break;
  473. default:
  474. break;
  475. }
  476. return backgroundColor;
  477. }
  478. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  479. {
  480. UIColor *strokeColor = nil;
  481. switch (type)
  482. {
  483. case TWMessageBarMessageTypeError:
  484. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  485. break;
  486. case TWMessageBarMessageTypeSuccess:
  487. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  488. break;
  489. case TWMessageBarMessageTypeInfo:
  490. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  491. break;
  492. default:
  493. break;
  494. }
  495. return strokeColor;
  496. }
  497. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  498. {
  499. UIImage *iconImage = nil;
  500. switch (type)
  501. {
  502. case TWMessageBarMessageTypeError:
  503. iconImage = [UIImage imageNamed:@"icon-error.png"];
  504. break;
  505. case TWMessageBarMessageTypeSuccess:
  506. iconImage = [UIImage imageNamed:@"icon-success.png"];
  507. break;
  508. case TWMessageBarMessageTypeInfo:
  509. iconImage = [UIImage imageNamed:@"icon-info.png"];
  510. break;
  511. default:
  512. break;
  513. }
  514. return iconImage;
  515. }
  516. - (void)updateApplicationIconBadgeNumber
  517. {
  518. if (self.activeAccount.length == 0 || self.maintenanceMode)
  519. return;
  520. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  521. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  522. 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];
  523. NSInteger total = counterDownload + counterUpload;
  524. dispatch_async(dispatch_get_main_queue(), ^{
  525. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  526. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  527. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  528. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  529. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  530. if (total > 0) {
  531. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  532. } else {
  533. [tbItem setBadgeValue:nil];
  534. }
  535. }
  536. });
  537. });
  538. }
  539. #pragma --------------------------------------------------------------------------------------------
  540. #pragma mark ===== TabBarController =====
  541. #pragma --------------------------------------------------------------------------------------------
  542. - (void)createTabBarController:(UITabBarController *)tabBarController
  543. {
  544. UITabBarItem *item;
  545. NSLayoutConstraint *constraint;
  546. CGFloat multiplier = 0;
  547. CGFloat safeAreaBottom = 0;
  548. if (@available(iOS 11, *)) {
  549. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  550. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  551. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  552. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  553. } else {
  554. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  555. }
  556. }
  557. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  558. // File
  559. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  560. [item setTitle:NSLocalizedString(@"_home_", nil)];
  561. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  562. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  563. // Favorites
  564. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  565. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  566. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  567. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  568. // (PLUS)
  569. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  570. item.title = @"";
  571. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  572. item.enabled = false;
  573. // Media
  574. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  575. [item setTitle:NSLocalizedString(@"_media_", nil)];
  576. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  577. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  578. // More
  579. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  580. [item setTitle:NSLocalizedString(@"_more_", nil)];
  581. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  582. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  583. // Plus Button
  584. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  585. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  586. buttonPlus.tag = 99;
  587. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  588. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  589. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  590. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  591. [tabBarController.tabBar addSubview:buttonPlus];
  592. multiplier = 1.0;
  593. // X
  594. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  595. [tabBarController.view addConstraint:constraint];
  596. // Y
  597. if (safeAreaBottom == 0) {
  598. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  599. } else {
  600. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  601. }
  602. [tabBarController.view addConstraint:constraint];
  603. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  604. // Width
  605. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  606. [tabBarController.view addConstraint:constraint];
  607. // Height
  608. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  609. [tabBarController.view addConstraint:constraint];
  610. }
  611. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  612. {
  613. nav.translucent = NO;
  614. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  615. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  616. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  617. // Change bar bottom line shadow
  618. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  619. if (!online)
  620. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  621. nav.hidden = hidden;
  622. [nav setAlpha:1];
  623. }
  624. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  625. {
  626. tab.translucent = NO;
  627. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  628. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  629. tab.hidden = hidden;
  630. [tab setAlpha:1];
  631. }
  632. - (void)plusButtonVisibile:(BOOL)visible
  633. {
  634. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  635. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  636. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  637. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  638. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  639. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  640. if (buttonPlus) {
  641. if (visible) {
  642. buttonPlus.hidden = false;
  643. } else {
  644. buttonPlus.hidden = true;
  645. }
  646. }
  647. }
  648. - (void)handleTouchTabbarCenter:(id)sender
  649. {
  650. // Test Maintenance
  651. if (self.maintenanceMode)
  652. return;
  653. UIView *view = [(UIButton *)sender superview];
  654. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  655. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  656. }
  657. - (void)selectedTabBarController:(NSInteger)index
  658. {
  659. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  660. if (splitViewController.isCollapsed) {
  661. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  662. for (UINavigationController *nvc in tbc.viewControllers) {
  663. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  664. [nvc popToRootViewControllerAnimated:NO];
  665. }
  666. [tbc setSelectedIndex: index];
  667. } else {
  668. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  669. [nvcDetail popToRootViewControllerAnimated:NO];
  670. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  671. [tbc setSelectedIndex: index];
  672. }
  673. }
  674. - (NSString *)getTabBarControllerActiveServerUrl
  675. {
  676. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  677. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  678. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  679. NSInteger index = tabBarController.selectedIndex;
  680. // select active serverUrl
  681. if (index == k_tabBarApplicationIndexFile) {
  682. serverUrl = self.activeMain.serverUrl;
  683. } else if (index == k_tabBarApplicationIndexFavorite) {
  684. if (self.activeFavorites.serverUrl)
  685. serverUrl = self.activeFavorites.serverUrl;
  686. } else if (index == k_tabBarApplicationIndexMedia) {
  687. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  688. }
  689. return serverUrl;
  690. }
  691. #pragma --------------------------------------------------------------------------------------------
  692. #pragma mark ===== Theming Color =====
  693. #pragma --------------------------------------------------------------------------------------------
  694. - (void)settingThemingColorBrand
  695. {
  696. if (self.activeAccount.length == 0 || self.maintenanceMode)
  697. return;
  698. if ([NCBrandOptions sharedInstance].use_themingColor) {
  699. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  700. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  701. } else {
  702. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  703. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  704. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  705. }
  706. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  707. }
  708. - (void)changeTheming:(UIViewController *)vc
  709. {
  710. // Change Navigation & TabBar color
  711. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  712. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  713. // Change bar bottom line shadow
  714. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  715. // Change button Plus
  716. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  717. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  718. UIButton *button = [tabBarController.view viewWithTag:99];
  719. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  720. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  721. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  722. // Tint Color GLOBAL WINDOW
  723. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  724. }
  725. #pragma --------------------------------------------------------------------------------------------
  726. #pragma mark ===== Manager Passcode =====
  727. #pragma --------------------------------------------------------------------------------------------
  728. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  729. {
  730. // ServerUrl active
  731. NSString *serverUrl = self.activeMain.serverUrl;
  732. BOOL isBlockZone = false;
  733. // fermiamo la data della sessione
  734. self.sessionePasscodeLock = nil;
  735. // se il block code è a zero esci con NON attivare la richiesta password
  736. if ([[CCUtility getBlockCode] length] == 0) return NO;
  737. // se non c'è attivo un account esci con NON attivare la richiesta password
  738. if ([self.activeAccount length] == 0) return NO;
  739. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  740. if (serverUrl && _activeUrl) {
  741. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  742. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  743. if (directory.lock) {
  744. isBlockZone = true;
  745. break;
  746. } else {
  747. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  748. if (serverUrl == self.activeUrl)
  749. break;
  750. }
  751. }
  752. }
  753. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  754. return YES;
  755. }
  756. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  757. {
  758. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  759. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  760. viewController.delegate = self;
  761. viewController.title = [NCBrandOptions sharedInstance].brand;
  762. viewController.fromType = CCBKPasscodeFromLockScreen;
  763. viewController.inputViewTitlePassword = YES;
  764. if ([CCUtility getSimplyBlockCode]) {
  765. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  766. viewController.passcodeInputView.maximumLength = 6;
  767. } else {
  768. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  769. viewController.passcodeInputView.maximumLength = 64;
  770. }
  771. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  772. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  773. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  774. return navigationController;
  775. }
  776. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  777. {
  778. [aViewController dismissViewControllerAnimated:YES completion:nil];
  779. // is a lock screen
  780. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  781. [aViewController dismissViewControllerAnimated:YES completion:nil];
  782. // start session Passcode Lock
  783. BOOL isBlockZone = false;
  784. NSString *serverUrl = self.activeMain.serverUrl;
  785. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  786. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  787. if (directory.lock) {
  788. isBlockZone = true;
  789. break;
  790. } else {
  791. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  792. if (serverUrl == self.activeUrl)
  793. break;
  794. }
  795. }
  796. if (isBlockZone)
  797. self.sessionePasscodeLock = [NSDate date];
  798. }
  799. }
  800. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  801. {
  802. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  803. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  804. //self.lockUntilDate = nil;
  805. //self.failedAttempts = 0;
  806. aResultHandler(YES);
  807. } else aResultHandler(NO);
  808. } else aResultHandler(YES);
  809. }
  810. #pragma --------------------------------------------------------------------------------------------
  811. #pragma mark ===== reachabilityChanged =====
  812. #pragma --------------------------------------------------------------------------------------------
  813. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  814. {
  815. if ([self.reachability isReachable]) {
  816. if (self.lastReachability == NO) {
  817. NSLog(@"[LOG] Request Service Server Nextcloud");
  818. [[NCService sharedInstance] startRequestServicesServer];
  819. }
  820. NSLog(@"[LOG] Reachability Changed: Reachable");
  821. self.lastReachability = YES;
  822. } else {
  823. if (self.lastReachability == YES) {
  824. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  825. }
  826. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  827. self.lastReachability = NO;
  828. }
  829. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  830. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  831. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  832. }
  833. #pragma --------------------------------------------------------------------------------------------
  834. #pragma mark ===== Fetch =====
  835. #pragma --------------------------------------------------------------------------------------------
  836. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  837. {
  838. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  839. // Verify new photo
  840. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  841. // after 20 sec
  842. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  843. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  844. if ([records count] > 0) {
  845. completionHandler(UIBackgroundFetchResultNewData);
  846. } else {
  847. completionHandler(UIBackgroundFetchResultNoData);
  848. }
  849. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  850. });
  851. }
  852. #pragma --------------------------------------------------------------------------------------------
  853. #pragma mark ===== Operation Networking & Session =====
  854. #pragma --------------------------------------------------------------------------------------------
  855. //
  856. // Method called by the system when all the background task has end
  857. //
  858. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  859. {
  860. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  861. // after 20 sec
  862. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  863. self.backgroundSessionCompletionHandler = completionHandler;
  864. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  865. self.backgroundSessionCompletionHandler = nil;
  866. completionHandler();
  867. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  868. });
  869. }
  870. #pragma --------------------------------------------------------------------------------------------
  871. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  872. #pragma --------------------------------------------------------------------------------------------
  873. - (void)loadAutoDownloadUpload
  874. {
  875. if (self.activeAccount.length == 0 || self.maintenanceMode)
  876. return;
  877. tableMetadata *metadataForUpload, *metadataForDownload;
  878. long counterDownload = 0, counterUpload = 0;
  879. NSUInteger sizeDownload = 0, sizeUpload = 0;
  880. BOOL isE2EE = false;
  881. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  882. // Detect E2EE
  883. NSString *saveserverUrl = @"";
  884. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d", self.activeAccount, k_metadataStatusNormal] sorted:nil ascending:NO];
  885. for (tableMetadata *metadata in metadatasForE2EE) {
  886. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  887. saveserverUrl = metadata.serverUrl;
  888. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  889. isE2EE = true;
  890. break;
  891. }
  892. }
  893. }
  894. // E2EE : not in background
  895. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  896. return;
  897. }
  898. // E2EE : only 1 operation
  899. if (isE2EE) {
  900. maxConcurrentOperationDownloadUpload = 1;
  901. }
  902. // Stop Timer
  903. [_timerProcessAutoDownloadUpload invalidate];
  904. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  905. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  906. // Counter
  907. counterDownload = [metadatasDownload count];
  908. counterUpload = [metadatasUpload count];
  909. // Size
  910. for (tableMetadata *metadata in metadatasDownload) {
  911. sizeDownload = sizeDownload + metadata.size;
  912. }
  913. for (tableMetadata *metadata in metadatasUpload) {
  914. sizeUpload = sizeUpload + metadata.size;
  915. }
  916. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  917. // ------------------------- <selector Download> -------------------------
  918. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  919. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status == %d", _activeAccount, k_metadataStatusWaitDownload]];
  920. if (metadataForDownload) {
  921. metadataForDownload.status = k_metadataStatusInDownload;
  922. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  923. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  924. counterDownload++;
  925. sizeDownload = sizeDownload + metadata.size;
  926. } else {
  927. break;
  928. }
  929. }
  930. // ------------------------- <selector Upload> -------------------------
  931. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  932. if (sizeUpload > k_maxSizeOperationUpload) {
  933. break;
  934. }
  935. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadFile, k_metadataStatusWaitUpload]];
  936. if (metadataForUpload) {
  937. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  938. metadataForUpload.session = k_upload_session;
  939. }
  940. metadataForUpload.status = k_metadataStatusInUpload;
  941. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  942. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  943. counterUpload++;
  944. sizeUpload = sizeUpload + metadata.size;
  945. } else {
  946. break;
  947. }
  948. }
  949. // ------------------------- <selector Auto Upload> -------------------------
  950. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  951. if (sizeUpload > k_maxSizeOperationUpload) {
  952. break;
  953. }
  954. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUpload, k_metadataStatusWaitUpload]];
  955. if (metadataForUpload) {
  956. metadataForUpload.status = k_metadataStatusInUpload;
  957. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  958. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  959. counterUpload++;
  960. sizeUpload = sizeUpload + metadata.size;
  961. } else {
  962. break;
  963. }
  964. }
  965. // ------------------------- <selector Auto Upload All> ----------------------
  966. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  967. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %i", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  968. NSInteger errorCount = [metadatas count];
  969. if (errorCount >= k_maxErrorAutoUploadAll) {
  970. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  971. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  972. } else {
  973. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  974. if (sizeUpload > k_maxSizeOperationUpload) {
  975. break;
  976. }
  977. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusWaitUpload]];
  978. if (metadataForUpload) {
  979. metadataForUpload.status = k_metadataStatusInUpload;
  980. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  981. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  982. counterUpload++;
  983. sizeUpload = sizeUpload + metadata.size;
  984. } else {
  985. break;
  986. }
  987. }
  988. }
  989. // No Download/upload available ? --> remove errors for retry
  990. //
  991. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  992. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", _activeAccount, k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  993. for (tableMetadata *metadata in metadatas) {
  994. if (metadata.status == k_metadataStatusDownloadError)
  995. metadata.status = k_metadataStatusWaitDownload;
  996. else if (metadata.status == k_metadataStatusUploadError)
  997. metadata.status = k_metadataStatusWaitUpload;
  998. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  999. }
  1000. }
  1001. // Verify internal error download (lost task)
  1002. //
  1003. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1004. for (tableMetadata *metadata in matadatasInDownloading) {
  1005. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1006. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1007. NSURLSessionTask *findTask;
  1008. for (NSURLSessionTask *task in downloadTasks) {
  1009. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1010. findTask = task;
  1011. }
  1012. }
  1013. if (!findTask) {
  1014. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1015. metadata.status = k_metadataStatusWaitDownload;
  1016. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1017. }
  1018. }];
  1019. }
  1020. // Verify internal error upload (lost task)
  1021. //
  1022. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1023. for (tableMetadata *metadata in metadatasUploading) {
  1024. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1025. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1026. NSURLSessionTask *findTask;
  1027. for (NSURLSessionTask *task in uploadTasks) {
  1028. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1029. findTask = task;
  1030. }
  1031. }
  1032. if (!findTask) {
  1033. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1034. metadata.status = k_metadataStatusWaitUpload;
  1035. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1036. }
  1037. }];
  1038. }
  1039. // Upload in pending
  1040. //
  1041. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d AND sessionTaskIdentifier == 0", self.activeAccount, k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1042. for (tableMetadata *metadata in metadatasInUpload) {
  1043. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1044. metadata.status = k_metadataStatusWaitUpload;
  1045. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1046. } else {
  1047. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1048. }
  1049. }
  1050. if (metadatasInUpload.count == 0) {
  1051. [self.sessionPendingStatusInUpload removeAllObjects];
  1052. }
  1053. // Start Timer
  1054. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1055. }
  1056. #pragma --------------------------------------------------------------------------------------------
  1057. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1058. #pragma --------------------------------------------------------------------------------------------
  1059. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1060. {
  1061. return YES;
  1062. }
  1063. // Method called from iOS system to send a file from other app.
  1064. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1065. {
  1066. NSError *error;
  1067. NSLog(@"[LOG] the path is: %@", url.path);
  1068. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1069. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1070. if (self.activeAccount) {
  1071. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1072. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1073. if (error == nil) {
  1074. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1075. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1076. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1077. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1078. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1079. });
  1080. }
  1081. }
  1082. return YES;
  1083. }
  1084. #pragma --------------------------------------------------------------------------------------------
  1085. #pragma mark ===== Crashlytics =====
  1086. #pragma --------------------------------------------------------------------------------------------
  1087. - (void) logUser
  1088. {
  1089. if (self.activeAccount.length > 0)
  1090. [CrashlyticsKit setUserName:self.activeAccount];
  1091. }
  1092. #pragma --------------------------------------------------------------------------------------------
  1093. #pragma mark ===== Maintenance Mode =====
  1094. #pragma --------------------------------------------------------------------------------------------
  1095. - (void)maintenanceMode:(BOOL)mode
  1096. {
  1097. self.maintenanceMode = mode;
  1098. }
  1099. #pragma --------------------------------------------------------------------------------------------
  1100. #pragma mark ===== UPGRADE =====
  1101. #pragma --------------------------------------------------------------------------------------------
  1102. - (BOOL)upgrade
  1103. {
  1104. #ifdef DEBUG
  1105. //self.maintenanceMode = YES;
  1106. #endif
  1107. NSString *actualVersion = [CCUtility getVersion];
  1108. NSString *actualBuild = [CCUtility getBuild];
  1109. /* ---------------------- UPGRADE VERSION ----------------------- */
  1110. // VERSION < 2.17.6
  1111. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1112. // Remove All old Photo Library
  1113. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1114. }
  1115. // VERSION == 2.17.6
  1116. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1117. // Build < 10
  1118. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1119. // Remove All old Photo Library
  1120. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1121. }
  1122. }
  1123. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1124. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1125. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1126. }
  1127. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1128. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1129. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1130. NSString *account = @"";
  1131. NSString *directoryUser = @"";
  1132. NSString *fileName;
  1133. for (tableLocalFile *record in records) {
  1134. if (![account isEqualToString:record.account]) {
  1135. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1136. if (tableAccount) {
  1137. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1138. account = record.account;
  1139. }
  1140. }
  1141. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1142. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1143. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1144. }
  1145. }
  1146. });
  1147. }
  1148. // VERSION == 2.22.8
  1149. if ([actualVersion isEqualToString:@"2.22.8"]) {
  1150. // Build < 20
  1151. if (([actualBuild compare:@"20" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1152. NSArray *directories = [[NCManageDatabase sharedInstance] getTablesDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl != ''"] sorted:@"account" ascending:NO];
  1153. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1154. [[NCManageDatabase sharedInstance] clearTable:[tablePhotos class] account:nil];
  1155. [[NCManageDatabase sharedInstance] clearTable:[tableDirectory class] account:nil];
  1156. for (tableDirectory *directory in directories) {
  1157. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:directory.e2eEncrypted favorite:directory.favorite fileID:directory.fileID permissions:directory.permissions serverUrl:directory.serverUrl account:directory.account];
  1158. [[NCManageDatabase sharedInstance] setLockOfflineDirectoryWithServerUrl:directory.serverUrl account:directory.account lock:directory.lock offline:directory.offline];
  1159. }
  1160. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1161. }
  1162. }
  1163. return YES;
  1164. }
  1165. @end