AppDelegate.m 67 KB

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