AppDelegate.m 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. // Initialization Notification
  112. self.listOfNotifications = [NSMutableArray new];
  113. // Background Fetch
  114. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  115. // Initialization List
  116. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  117. self.listMainVC = [[NSMutableDictionary alloc] init];
  118. // Firebase - Push Notification
  119. @try {
  120. [FIRApp configure];
  121. } @catch (NSException *exception) {
  122. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  123. }
  124. // Display notification (sent via APNS)
  125. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  126. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  127. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  128. }];
  129. [application registerForRemoteNotifications];
  130. [FIRMessaging messaging].delegate = self;
  131. // setting Reachable in back
  132. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  133. self.reachability = [Reachability reachabilityForInternetConnection];
  134. self.lastReachability = [self.reachability isReachable];
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  136. [self.reachability startNotifier];
  137. });
  138. //AV Session
  139. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  140. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  141. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  142. // How to hide UINavigationBar 1px bottom line < iOS 11
  143. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  144. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  145. // passcode
  146. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  147. dispatch_async(dispatch_get_main_queue(), ^{
  148. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  149. });
  150. // Quick Actions
  151. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  152. [self configDynamicShortcutItems];
  153. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  154. if (shortcutItem)
  155. [self handleShortCutItem:shortcutItem];
  156. }
  157. // Start Timer
  158. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  159. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  160. // Fabric
  161. [Fabric with:@[[Crashlytics class]]];
  162. [self logUser];
  163. // Store review
  164. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  165. NCStoreReview *review = [NCStoreReview new];
  166. [review incrementAppRuns];
  167. [review showStoreReview];
  168. }
  169. return YES;
  170. }
  171. //
  172. // L' applicazione si dimetterà dallo stato di attivo
  173. //
  174. - (void)applicationWillResignActive:(UIApplication *)application
  175. {
  176. [_activeMain closeAllMenu];
  177. [self updateApplicationIconBadgeNumber];
  178. }
  179. //
  180. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  181. //
  182. - (void)applicationWillEnterForeground:(UIApplication *)application
  183. {
  184. // Test Maintenance
  185. if (self.activeAccount.length == 0 || self.maintenanceMode)
  186. return;
  187. NSLog(@"[LOG] Request Service Server Nextcloud");
  188. [[NCService sharedInstance] startRequestServicesServer];
  189. NSLog(@"[LOG] Initialize Auto upload");
  190. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  191. NSLog(@"[LOG] Read active directory");
  192. [self.activeMain readFileReloadFolder];
  193. }
  194. //
  195. // L' applicazione entrerà in primo piano (attivo sempre)
  196. //
  197. - (void)applicationDidBecomeActive:(UIApplication *)application
  198. {
  199. // Test Maintenance
  200. if (self.activeAccount.length == 0 || self.maintenanceMode)
  201. return;
  202. // middelware ping
  203. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  204. NSLog(@"[LOG] Middleware Ping");
  205. [[NCService sharedInstance] middlewarePing];
  206. }
  207. // Test error task upload / download
  208. [self verifyInternalErrorDownloadingUploading];
  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. // Test Maintenance
  522. if (self.maintenanceMode)
  523. return;
  524. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  525. 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];
  526. 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];
  527. NSInteger total = counterDownload + counterUpload;
  528. dispatch_async(dispatch_get_main_queue(), ^{
  529. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  530. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  531. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  532. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  533. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  534. if (total > 0) {
  535. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  536. } else {
  537. [tbItem setBadgeValue:nil];
  538. }
  539. }
  540. });
  541. });
  542. }
  543. #pragma --------------------------------------------------------------------------------------------
  544. #pragma mark ===== TabBarController =====
  545. #pragma --------------------------------------------------------------------------------------------
  546. - (void)createTabBarController:(UITabBarController *)tabBarController
  547. {
  548. UITabBarItem *item;
  549. NSLayoutConstraint *constraint;
  550. CGFloat multiplier = 0;
  551. CGFloat safeAreaBottom = 0;
  552. if (@available(iOS 11, *)) {
  553. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  554. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  555. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  556. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  557. } else {
  558. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  559. }
  560. }
  561. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  562. // File
  563. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  564. [item setTitle:NSLocalizedString(@"_home_", nil)];
  565. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  566. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  567. // Favorites
  568. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  569. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  570. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  571. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  572. // (PLUS)
  573. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  574. item.title = @"";
  575. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  576. item.enabled = false;
  577. // Media
  578. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  579. [item setTitle:NSLocalizedString(@"_media_", nil)];
  580. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  581. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  582. // More
  583. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  584. [item setTitle:NSLocalizedString(@"_more_", nil)];
  585. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  586. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  587. // Plus Button
  588. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  589. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  590. buttonPlus.tag = 99;
  591. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  592. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  593. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  594. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  595. [tabBarController.tabBar addSubview:buttonPlus];
  596. multiplier = 1.0;
  597. // X
  598. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  599. [tabBarController.view addConstraint:constraint];
  600. // Y
  601. if (safeAreaBottom == 0) {
  602. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  603. } else {
  604. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  605. }
  606. [tabBarController.view addConstraint:constraint];
  607. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  608. // Width
  609. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  610. [tabBarController.view addConstraint:constraint];
  611. // Height
  612. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  613. [tabBarController.view addConstraint:constraint];
  614. }
  615. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  616. {
  617. nav.translucent = NO;
  618. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  619. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  620. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  621. // Change bar bottom line shadow
  622. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  623. if (!online)
  624. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  625. nav.hidden = hidden;
  626. [nav setAlpha:1];
  627. }
  628. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  629. {
  630. tab.translucent = NO;
  631. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  632. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  633. tab.hidden = hidden;
  634. [tab setAlpha:1];
  635. }
  636. - (void)plusButtonVisibile:(BOOL)visible
  637. {
  638. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  639. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  640. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  641. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  642. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  643. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  644. if (buttonPlus) {
  645. if (visible) {
  646. buttonPlus.hidden = false;
  647. } else {
  648. buttonPlus.hidden = true;
  649. }
  650. }
  651. }
  652. - (void)handleTouchTabbarCenter:(id)sender
  653. {
  654. // Test Maintenance
  655. if (self.maintenanceMode)
  656. return;
  657. UIView *view = [(UIButton *)sender superview];
  658. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  659. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  660. }
  661. - (void)selectedTabBarController:(NSInteger)index
  662. {
  663. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  664. if (splitViewController.isCollapsed) {
  665. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  666. for (UINavigationController *nvc in tbc.viewControllers) {
  667. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  668. [nvc popToRootViewControllerAnimated:NO];
  669. }
  670. [tbc setSelectedIndex: index];
  671. } else {
  672. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  673. [nvcDetail popToRootViewControllerAnimated:NO];
  674. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  675. [tbc setSelectedIndex: index];
  676. }
  677. }
  678. - (NSString *)getTabBarControllerActiveServerUrl
  679. {
  680. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  681. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  682. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  683. NSInteger index = tabBarController.selectedIndex;
  684. // select active serverUrl
  685. if (index == k_tabBarApplicationIndexFile) {
  686. serverUrl = self.activeMain.serverUrl;
  687. } else if (index == k_tabBarApplicationIndexFavorite) {
  688. if (self.activeFavorites.serverUrl)
  689. serverUrl = self.activeFavorites.serverUrl;
  690. } else if (index == k_tabBarApplicationIndexMedia) {
  691. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  692. }
  693. return serverUrl;
  694. }
  695. #pragma --------------------------------------------------------------------------------------------
  696. #pragma mark ===== Theming Color =====
  697. #pragma --------------------------------------------------------------------------------------------
  698. - (void)settingThemingColorBrand
  699. {
  700. if (self.activeAccount.length == 0 || self.maintenanceMode)
  701. return;
  702. if ([NCBrandOptions sharedInstance].use_themingColor) {
  703. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  704. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  705. } else {
  706. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  707. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  708. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  709. }
  710. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  711. }
  712. - (void)changeTheming:(UIViewController *)vc
  713. {
  714. // Change Navigation & TabBar color
  715. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  716. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  717. // Change bar bottom line shadow
  718. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  719. // Change button Plus
  720. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  721. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  722. UIButton *button = [tabBarController.view viewWithTag:99];
  723. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  724. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  725. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  726. // Tint Color GLOBAL WINDOW
  727. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  728. }
  729. #pragma --------------------------------------------------------------------------------------------
  730. #pragma mark ===== Manager Passcode =====
  731. #pragma --------------------------------------------------------------------------------------------
  732. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  733. {
  734. // ServerUrl active
  735. NSString *serverUrl = self.activeMain.serverUrl;
  736. BOOL isBlockZone = false;
  737. // fermiamo la data della sessione
  738. self.sessionePasscodeLock = nil;
  739. // se il block code è a zero esci con NON attivare la richiesta password
  740. if ([[CCUtility getBlockCode] length] == 0) return NO;
  741. // se non c'è attivo un account esci con NON attivare la richiesta password
  742. if ([self.activeAccount length] == 0) return NO;
  743. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  744. if (serverUrl && _activeUrl) {
  745. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  746. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  747. if (directory.lock) {
  748. isBlockZone = true;
  749. break;
  750. } else {
  751. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  752. if (serverUrl == self.activeUrl)
  753. break;
  754. }
  755. }
  756. }
  757. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  758. return YES;
  759. }
  760. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  761. {
  762. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  763. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  764. viewController.delegate = self;
  765. viewController.title = [NCBrandOptions sharedInstance].brand;
  766. viewController.fromType = CCBKPasscodeFromLockScreen;
  767. viewController.inputViewTitlePassword = YES;
  768. if ([CCUtility getSimplyBlockCode]) {
  769. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  770. viewController.passcodeInputView.maximumLength = 6;
  771. } else {
  772. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  773. viewController.passcodeInputView.maximumLength = 64;
  774. }
  775. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  776. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  777. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  778. return navigationController;
  779. }
  780. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  781. {
  782. [aViewController dismissViewControllerAnimated:YES completion:nil];
  783. // is a lock screen
  784. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  785. [aViewController dismissViewControllerAnimated:YES completion:nil];
  786. // start session Passcode Lock
  787. BOOL isBlockZone = false;
  788. NSString *serverUrl = self.activeMain.serverUrl;
  789. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  790. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  791. if (directory.lock) {
  792. isBlockZone = true;
  793. break;
  794. } else {
  795. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  796. if (serverUrl == self.activeUrl)
  797. break;
  798. }
  799. }
  800. if (isBlockZone)
  801. self.sessionePasscodeLock = [NSDate date];
  802. }
  803. }
  804. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  805. {
  806. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  807. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  808. //self.lockUntilDate = nil;
  809. //self.failedAttempts = 0;
  810. aResultHandler(YES);
  811. } else aResultHandler(NO);
  812. } else aResultHandler(YES);
  813. }
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ===== reachabilityChanged =====
  816. #pragma --------------------------------------------------------------------------------------------
  817. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  818. {
  819. if ([self.reachability isReachable]) {
  820. if (self.lastReachability == NO) {
  821. NSLog(@"[LOG] Request Service Server Nextcloud");
  822. [[NCService sharedInstance] startRequestServicesServer];
  823. }
  824. NSLog(@"[LOG] Reachability Changed: Reachable");
  825. self.lastReachability = YES;
  826. } else {
  827. if (self.lastReachability == YES) {
  828. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  829. }
  830. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  831. self.lastReachability = NO;
  832. }
  833. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  834. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  835. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  836. }
  837. #pragma --------------------------------------------------------------------------------------------
  838. #pragma mark ===== Fetch =====
  839. #pragma --------------------------------------------------------------------------------------------
  840. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  841. {
  842. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  843. // Verify new photo
  844. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  845. // after 20 sec
  846. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  847. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  848. if ([records count] > 0) {
  849. completionHandler(UIBackgroundFetchResultNewData);
  850. } else {
  851. completionHandler(UIBackgroundFetchResultNoData);
  852. }
  853. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  854. });
  855. }
  856. #pragma --------------------------------------------------------------------------------------------
  857. #pragma mark ===== Operation Networking & Session =====
  858. #pragma --------------------------------------------------------------------------------------------
  859. //
  860. // Method called by the system when all the background task has end
  861. //
  862. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  863. {
  864. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  865. // after 20 sec
  866. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  867. self.backgroundSessionCompletionHandler = completionHandler;
  868. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  869. self.backgroundSessionCompletionHandler = nil;
  870. completionHandler();
  871. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  872. });
  873. }
  874. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  875. {
  876. id operation;
  877. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  878. [operation setQueuePriority:metadataNet.priority];
  879. [netQueue addOperation:operation];
  880. }
  881. #pragma --------------------------------------------------------------------------------------------
  882. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  883. #pragma --------------------------------------------------------------------------------------------
  884. - (void)loadAutoDownloadUpload
  885. {
  886. tableMetadata *metadataForUpload, *metadataForDownload;
  887. long counterDownload = 0, counterUpload = 0;
  888. NSUInteger sizeDownload = 0, sizeUpload = 0;
  889. BOOL isE2EE = false;
  890. long maxConcurrentOperationDownload = k_maxConcurrentOperationDownload;
  891. long maxConcurrentOperationUpload = k_maxConcurrentOperationUpload;
  892. // Test Maintenance
  893. if (self.maintenanceMode)
  894. return;
  895. // Detect E2EE
  896. NSString *saveDirectoryID = @"";
  897. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d", self.activeAccount, k_metadataStatusNormal] sorted:nil ascending:NO];
  898. for (tableMetadata *metadata in metadatasForE2EE) {
  899. if (![saveDirectoryID isEqualToString:metadata.directoryID]) {
  900. saveDirectoryID = metadata.directoryID;
  901. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND e2eEncrypted == 1", metadata.directoryID]] != nil) {
  902. isE2EE = true;
  903. break;
  904. }
  905. }
  906. }
  907. // E2EE : not in background
  908. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  909. return;
  910. }
  911. // E2EE : only 1 operation
  912. if (isE2EE) {
  913. maxConcurrentOperationDownload = 1;
  914. maxConcurrentOperationUpload = 1;
  915. }
  916. // Stop Timer
  917. [_timerProcessAutoDownloadUpload invalidate];
  918. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  919. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  920. // Counter
  921. counterDownload = [metadatasDownload count];
  922. counterUpload = [metadatasUpload count];
  923. // Size
  924. for (tableMetadata *metadata in metadatasDownload) {
  925. sizeDownload = sizeDownload + metadata.size;
  926. }
  927. for (tableMetadata *metadata in metadatasUpload) {
  928. sizeUpload = sizeUpload + metadata.size;
  929. }
  930. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  931. // ------------------------- <selector Download> -------------------------
  932. while (counterDownload < maxConcurrentOperationDownload) {
  933. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status == %d", _activeAccount, k_metadataStatusWaitDownload]];
  934. if (metadataForDownload) {
  935. metadataForDownload.status = k_metadataStatusInDownload;
  936. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  937. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  938. counterDownload++;
  939. sizeDownload = sizeDownload + metadata.size;
  940. } else {
  941. break;
  942. }
  943. }
  944. // ------------------------- <selector Upload> -------------------------
  945. while (counterUpload < maxConcurrentOperationUpload) {
  946. if (sizeUpload > k_maxSizeOperationUpload) {
  947. break;
  948. }
  949. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadFile, k_metadataStatusWaitUpload]];
  950. if (metadataForUpload) {
  951. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  952. metadataForUpload.session = k_upload_session;
  953. }
  954. metadataForUpload.status = k_metadataStatusInUpload;
  955. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  956. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  957. counterUpload++;
  958. sizeUpload = sizeUpload + metadata.size;
  959. } else {
  960. break;
  961. }
  962. }
  963. // ------------------------- <selector Auto Upload> -------------------------
  964. while (counterUpload < maxConcurrentOperationUpload) {
  965. if (sizeUpload > k_maxSizeOperationUpload) {
  966. break;
  967. }
  968. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUpload, k_metadataStatusWaitUpload]];
  969. if (metadataForUpload) {
  970. metadataForUpload.status = k_metadataStatusInUpload;
  971. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  972. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  973. counterUpload++;
  974. sizeUpload = sizeUpload + metadata.size;
  975. } else {
  976. break;
  977. }
  978. }
  979. // ------------------------- <selector Auto Upload All> ----------------------
  980. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  981. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %i", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  982. NSInteger errorCount = [metadatas count];
  983. if (errorCount >= k_maxErrorAutoUploadAll) {
  984. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  985. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  986. } else {
  987. while (counterUpload < maxConcurrentOperationUpload) {
  988. if (sizeUpload > k_maxSizeOperationUpload) {
  989. break;
  990. }
  991. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusWaitUpload]];
  992. if (metadataForUpload) {
  993. metadataForUpload.status = k_metadataStatusInUpload;
  994. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  995. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  996. counterUpload++;
  997. sizeUpload = sizeUpload + metadata.size;
  998. } else {
  999. break;
  1000. }
  1001. }
  1002. }
  1003. // ------------------------- < END > ----------------------
  1004. // No Download/upload available ? --> remove errors for retry
  1005. //
  1006. if (counterDownload+counterUpload == 0) {
  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. // Start Timer
  1017. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1018. }
  1019. #pragma --------------------------------------------------------------------------------------------
  1020. #pragma mark ===== Verify internal error in Download/Upload =====
  1021. #pragma --------------------------------------------------------------------------------------------
  1022. - (void)verifyInternalErrorDownloadingUploading
  1023. {
  1024. // Test Maintenance
  1025. if (self.maintenanceMode || self.activeAccount.length == 0)
  1026. return;
  1027. NSArray *recordsInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1028. for (tableMetadata *metadata in recordsInDownloading) {
  1029. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1030. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1031. NSURLSessionTask *findTask;
  1032. for (NSURLSessionTask *task in downloadTasks) {
  1033. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1034. findTask = task;
  1035. }
  1036. }
  1037. if (!findTask) {
  1038. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1039. metadata.status = k_metadataStatusWaitDownload;
  1040. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1041. }
  1042. }];
  1043. }
  1044. NSArray *recordsInUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1045. for (tableMetadata *metadata in recordsInUploading) {
  1046. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1047. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1048. NSURLSessionTask *findTask;
  1049. for (NSURLSessionTask *task in uploadTasks) {
  1050. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1051. findTask = task;
  1052. }
  1053. }
  1054. if (!findTask) {
  1055. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1056. metadata.status = k_metadataStatusWaitUpload;
  1057. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1058. }
  1059. }];
  1060. }
  1061. }
  1062. #pragma --------------------------------------------------------------------------------------------
  1063. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1064. #pragma --------------------------------------------------------------------------------------------
  1065. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1066. {
  1067. return YES;
  1068. }
  1069. // Method called from iOS system to send a file from other app.
  1070. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1071. {
  1072. NSError *error;
  1073. NSLog(@"[LOG] the path is: %@", url.path);
  1074. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1075. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1076. if (self.activeAccount) {
  1077. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1078. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1079. if (error == nil) {
  1080. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1081. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1082. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1083. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1084. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1085. });
  1086. }
  1087. }
  1088. return YES;
  1089. }
  1090. #pragma --------------------------------------------------------------------------------------------
  1091. #pragma mark ===== Crashlytics =====
  1092. #pragma --------------------------------------------------------------------------------------------
  1093. - (void) logUser
  1094. {
  1095. if (self.activeAccount.length > 0)
  1096. [CrashlyticsKit setUserName:self.activeAccount];
  1097. }
  1098. #pragma --------------------------------------------------------------------------------------------
  1099. #pragma mark ===== Maintenance Mode =====
  1100. #pragma --------------------------------------------------------------------------------------------
  1101. - (void)maintenanceMode:(BOOL)mode
  1102. {
  1103. self.maintenanceMode = mode;
  1104. }
  1105. #pragma --------------------------------------------------------------------------------------------
  1106. #pragma mark ===== UPGRADE =====
  1107. #pragma --------------------------------------------------------------------------------------------
  1108. - (BOOL)upgrade
  1109. {
  1110. #ifdef DEBUG
  1111. //self.maintenanceMode = YES;
  1112. #endif
  1113. NSString *actualVersion = [CCUtility getVersion];
  1114. NSString *actualBuild = [CCUtility getBuild];
  1115. /* ---------------------- UPGRADE VERSION ----------------------- */
  1116. // VERSION < 2.17.6
  1117. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1118. // Remove All old Photo Library
  1119. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1120. }
  1121. // VERSION == 2.17.6
  1122. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1123. // Build < 10
  1124. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1125. // Remove All old Photo Library
  1126. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1127. }
  1128. }
  1129. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1130. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1131. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1132. }
  1133. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1134. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1135. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1136. NSString *account = @"";
  1137. NSString *directoryUser = @"";
  1138. NSString *fileName;
  1139. for (tableLocalFile *record in records) {
  1140. if (![account isEqualToString:record.account]) {
  1141. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1142. if (tableAccount) {
  1143. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1144. account = record.account;
  1145. }
  1146. }
  1147. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1148. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1149. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1150. }
  1151. }
  1152. });
  1153. }
  1154. return YES;
  1155. }
  1156. @end