AppDelegate.m 67 KB

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