AppDelegate.m 66 KB

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