AppDelegate.m 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. //
  2. // AppDelegate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import <JDStatusBarNotification/JDStatusBarNotification.h>
  25. #import "AFURLSessionManager.h"
  26. #import "CCNetworking.h"
  27. #import "CCGraphics.h"
  28. #import "CCMedia.h"
  29. #import "CCSynchronize.h"
  30. #import "CCMain.h"
  31. #import "CCDetail.h"
  32. #import <Fabric/Fabric.h>
  33. #import <Crashlytics/Crashlytics.h>
  34. #import "NCBridgeSwift.h"
  35. #import "NCAutoUpload.h"
  36. #import "Firebase.h"
  37. #import "NCPushNotificationEncryption.h"
  38. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  39. @end
  40. @implementation AppDelegate
  41. + (void)initialize
  42. {
  43. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  44. }
  45. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  46. {
  47. NSString *path;
  48. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  49. NSLog(@"[LOG] Start program group -----------------");
  50. NSLog(@"%@", [dirGroup path]);
  51. NSLog(@"[LOG] Start program application -----------");
  52. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  53. NSLog(@"[LOG] -------------------------------------");
  54. // create Directory Documents
  55. path = [CCUtility getDirectoryDocuments];
  56. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  57. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  58. // create Directory audio => Library, Application Support, audio
  59. path = [CCUtility getDirectoryAudio];
  60. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  61. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  62. // create Directory database Nextcloud
  63. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  64. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  65. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  66. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  67. // create Directory User Data
  68. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  69. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  70. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  71. // create Directory Provider Storage
  72. path = [CCUtility getDirectoryProviderStorage];
  73. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  74. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  75. // create Directory Scan
  76. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  77. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  78. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  79. // Verify upgrade
  80. if ([self upgrade]) {
  81. // Set account, if no exists clear all
  82. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  83. if (account == nil) {
  84. // remove all the keys Chain
  85. [CCUtility deleteAllChainStore];
  86. // remove all the App group key
  87. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  88. } else {
  89. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  90. }
  91. }
  92. #ifdef DEBUG
  93. NSLog(@"[LOG] Copy DB on Documents directory");
  94. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  95. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  96. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  97. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  98. #endif
  99. // UserDefaults
  100. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  101. // Initialization Share
  102. self.sharesID = [NSMutableDictionary new];
  103. self.sharesLink = [NSMutableDictionary new];
  104. self.sharesUserAndGroup = [NSMutableDictionary new];
  105. // Filter fileID
  106. self.filterFileID = [NSMutableArray new];
  107. // Upload Pending In Upload (crash)
  108. self.sessionPendingStatusInUpload = [NSMutableArray new];
  109. // Initialization Notification
  110. self.listOfNotifications = [NSMutableArray new];
  111. // Background Fetch
  112. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  113. // Initialization List
  114. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  115. self.listMainVC = [[NSMutableDictionary alloc] init];
  116. // Firebase - Push Notification
  117. @try {
  118. [FIRApp configure];
  119. } @catch (NSException *exception) {
  120. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  121. }
  122. // Display notification (sent via APNS)
  123. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  124. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  125. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  126. }];
  127. [application registerForRemoteNotifications];
  128. [FIRMessaging messaging].delegate = self;
  129. // setting Reachable in back
  130. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  131. self.reachability = [Reachability reachabilityForInternetConnection];
  132. self.lastReachability = [self.reachability isReachable];
  133. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  134. [self.reachability startNotifier];
  135. });
  136. //AV Session
  137. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  138. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  139. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  140. // How to hide UINavigationBar 1px bottom line < iOS 11
  141. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  142. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  143. // passcode
  144. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  145. dispatch_async(dispatch_get_main_queue(), ^{
  146. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  147. });
  148. // Quick Actions
  149. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  150. [self configDynamicShortcutItems];
  151. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  152. if (shortcutItem)
  153. [self handleShortCutItem:shortcutItem];
  154. }
  155. // Start Timer
  156. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  157. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  158. // Fabric
  159. [Fabric with:@[[Crashlytics class]]];
  160. [self logUser];
  161. // Store review
  162. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  163. NCStoreReview *review = [NCStoreReview new];
  164. [review incrementAppRuns];
  165. [review showStoreReview];
  166. }
  167. return YES;
  168. }
  169. //
  170. // L' applicazione si dimetterà dallo stato di attivo
  171. //
  172. - (void)applicationWillResignActive:(UIApplication *)application
  173. {
  174. [_activeMain closeAllMenu];
  175. [self updateApplicationIconBadgeNumber];
  176. }
  177. //
  178. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  179. //
  180. - (void)applicationWillEnterForeground:(UIApplication *)application
  181. {
  182. // Test Maintenance
  183. if (self.activeAccount.length == 0 || self.maintenanceMode)
  184. return;
  185. NSLog(@"[LOG] Request Service Server Nextcloud");
  186. [[NCService sharedInstance] startRequestServicesServer];
  187. NSLog(@"[LOG] Initialize Auto upload");
  188. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  189. NSLog(@"[LOG] Read active directory");
  190. [self.activeMain readFileReloadFolder];
  191. }
  192. //
  193. // L' applicazione entrerà in primo piano (attivo sempre)
  194. //
  195. - (void)applicationDidBecomeActive:(UIApplication *)application
  196. {
  197. // Test Maintenance
  198. if (self.activeAccount.length == 0 || self.maintenanceMode)
  199. return;
  200. // middelware ping
  201. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  202. NSLog(@"[LOG] Middleware Ping");
  203. [[NCService sharedInstance] middlewarePing];
  204. }
  205. }
  206. //
  207. // L' applicazione è entrata nello sfondo
  208. //
  209. - (void)applicationDidEnterBackground:(UIApplication *)application
  210. {
  211. NSLog(@"[LOG] Enter in Background");
  212. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  213. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  214. __block UIBackgroundTaskIdentifier background_task;
  215. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  216. //Clean up code. Tell the system that we are done.
  217. [application endBackgroundTask: background_task];
  218. background_task = UIBackgroundTaskInvalid;
  219. }];
  220. }
  221. }
  222. //
  223. // L'applicazione terminerà
  224. //
  225. - (void)applicationWillTerminate:(UIApplication *)application
  226. {
  227. NSLog(@"[LOG] bye bye, Nextcloud !");
  228. }
  229. #pragma --------------------------------------------------------------------------------------------
  230. #pragma mark ===== Login =====
  231. #pragma --------------------------------------------------------------------------------------------
  232. - (void)openLoginView:(id)delegate loginType:(NSInteger)loginType selector:(NSInteger)selector
  233. {
  234. BOOL loginWebFlow = NO;
  235. @synchronized (self) {
  236. // only for personalized LoginWeb [customer]
  237. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  238. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  239. _activeLoginWeb = [CCLoginWeb new];
  240. _activeLoginWeb.delegate = delegate;
  241. _activeLoginWeb.loginType = loginType;
  242. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  243. dispatch_async(dispatch_get_main_queue(), ^ {
  244. [_activeLoginWeb open:delegate];
  245. });
  246. }
  247. return;
  248. }
  249. // ------------------- Nextcloud -------------------------
  250. //
  251. // Login flow : LoginWeb
  252. if (loginType == k_login_Modify_Password) {
  253. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  254. if (account.loginFlow)
  255. loginWebFlow = YES;
  256. }
  257. if (loginWebFlow || selector == k_intro_signup) {
  258. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  259. _activeLoginWeb = [CCLoginWeb new];
  260. _activeLoginWeb.delegate = delegate;
  261. _activeLoginWeb.loginType = loginType;
  262. if (selector == k_intro_signup) {
  263. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  264. } else {
  265. _activeLoginWeb.urlBase = self.activeUrl;
  266. }
  267. dispatch_async(dispatch_get_main_queue(), ^ {
  268. [_activeLoginWeb open:delegate];
  269. });
  270. }
  271. } else {
  272. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  273. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  274. _activeLogin.delegate = delegate;
  275. _activeLogin.loginType = loginType;
  276. dispatch_async(dispatch_get_main_queue(), ^ {
  277. [delegate presentViewController:_activeLogin animated:YES completion:nil];
  278. });
  279. }
  280. }
  281. }
  282. }
  283. #pragma --------------------------------------------------------------------------------------------
  284. #pragma mark ===== Setting Active Account for all APP =====
  285. #pragma --------------------------------------------------------------------------------------------
  286. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  287. {
  288. self.activeAccount = activeAccount;
  289. self.activeUrl = activeUrl;
  290. self.activeUser = activeUser;
  291. self.activeUserID = activeUserID;
  292. self.activePassword = activePassword;
  293. // Setting Account to CCNetworking
  294. [CCNetworking sharedNetworking].delegate = [NCNetworkingMain sharedInstance];
  295. }
  296. #pragma --------------------------------------------------------------------------------------------
  297. #pragma mark ===== Push Notification =====
  298. #pragma --------------------------------------------------------------------------------------------
  299. - (void)subscribingNextcloudServerPushNotification
  300. {
  301. // test
  302. if (self.activeAccount.length == 0 || self.maintenanceMode)
  303. return;
  304. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair];
  305. NSString *pushToken = [CCUtility getPushNotificationToken];
  306. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:pushToken];
  307. NSString *devicePublicKey = [[NSString alloc] initWithData:[NCPushNotificationEncryption sharedInstance].ncPNPublicKey encoding:NSUTF8StringEncoding];
  308. self.pnDeviceIdentifier = nil;
  309. self.pnDeviceIdentifierSignature = nil;
  310. self.pnPublicKey = nil;
  311. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:self.activeAccount url:self.activeUrl pushToken:pushToken Hash:pushTokenHash devicePublicKey:devicePublicKey completion:^(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  312. if (errorCode == 0 && [account isEqualToString:self.activeAccount]) {
  313. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  314. self.pnDeviceIdentifier = deviceIdentifier;
  315. self.pnDeviceIdentifierSignature = deviceIdentifierSignature;
  316. self.pnPublicKey = publicKey;
  317. } else if (errorCode != 0) {
  318. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  319. } else {
  320. NSLog(@"[LOG] It has been changed user during networking process, error.");
  321. }
  322. }];
  323. }
  324. - (void)unsubscribingNextcloudServerPushNotification
  325. {
  326. // test
  327. if (self.activeAccount.length == 0 || self.maintenanceMode)
  328. return;
  329. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:self.activeAccount url:self.activeUrl deviceIdentifier:self.pnDeviceIdentifier deviceIdentifierSignature:self.pnDeviceIdentifierSignature publicKey:self.pnPublicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  330. if (errorCode == 0) {
  331. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  332. } else if (errorCode != 0) {
  333. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  334. } else {
  335. NSLog(@"[LOG] It has been changed user during networking process, error.");
  336. }
  337. }];
  338. }
  339. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  340. {
  341. //Called when a notification is delivered to a foreground app.
  342. completionHandler(UNNotificationPresentationOptionAlert);
  343. }
  344. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  345. {
  346. /*
  347. NSString *message = [response.notification.request.content.userInfo objectForKey:@"subject"];
  348. if (message && [NCPushNotificationEncryption sharedInstance].ncPNPrivateKey) {
  349. NSData *privateKey = [CCUtility getPushNotificationPrivateKey];
  350. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:privateKey];
  351. if (decryptedMessage) {
  352. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  353. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  354. NSString *app = [json objectForKey:@"app"];
  355. if ([app isEqualToString:@"spreed"] == NO) {
  356. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  357. UINavigationController *navigationControllerMore;
  358. UITabBarController *tabBarController;
  359. if (splitViewController.isCollapsed) {
  360. tabBarController = splitViewController.viewControllers.firstObject;
  361. for (UINavigationController *nvc in tabBarController.viewControllers) {
  362. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  363. [nvc popToRootViewControllerAnimated:NO];
  364. if ([nvc.topViewController isKindOfClass:[CCMore class]])
  365. navigationControllerMore = nvc;
  366. }
  367. } else {
  368. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  369. [nvcDetail popToRootViewControllerAnimated:NO];
  370. tabBarController = splitViewController.viewControllers.firstObject;
  371. }
  372. if (tabBarController)
  373. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMore];
  374. if (navigationControllerMore)
  375. [navigationControllerMore performSegueWithIdentifier:@"segueActivity" sender:navigationControllerMore];
  376. }
  377. }
  378. }
  379. */
  380. completionHandler();
  381. }
  382. #pragma FIREBASE
  383. - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
  384. {
  385. // test
  386. if (self.activeAccount.length == 0 || self.maintenanceMode)
  387. return;
  388. NSLog(@"FCM registration token: %@", fcmToken);
  389. [CCUtility setPushNotificationToken:fcmToken];
  390. [self subscribingNextcloudServerPushNotification];
  391. }
  392. #pragma --------------------------------------------------------------------------------------------
  393. #pragma mark ===== Quick Actions - ShotcutItem =====
  394. #pragma --------------------------------------------------------------------------------------------
  395. - (void)configDynamicShortcutItems
  396. {
  397. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  398. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionMedia"];
  399. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  400. // add the array to our app
  401. if (shortcutMedia)
  402. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  403. }
  404. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  405. {
  406. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  407. completionHandler(handledShortCutItem);
  408. }
  409. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  410. {
  411. BOOL handled = NO;
  412. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  413. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  414. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  415. dispatch_async(dispatch_get_main_queue(), ^{
  416. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  417. if (splitViewController.isCollapsed) {
  418. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  419. for (UINavigationController *nvc in tbc.viewControllers) {
  420. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  421. [nvc popToRootViewControllerAnimated:NO];
  422. }
  423. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  424. } else {
  425. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  426. [nvcDetail popToRootViewControllerAnimated:NO];
  427. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  428. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  429. }
  430. });
  431. handled = YES;
  432. }
  433. return handled;
  434. }
  435. #pragma --------------------------------------------------------------------------------------------
  436. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  437. #pragma --------------------------------------------------------------------------------------------
  438. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  439. {
  440. static NSInteger errorCodePrev = 0;
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. if (visible) {
  443. switch (errorcode) {
  444. // JDStatusBarNotification
  445. case kCFURLErrorNotConnectedToInternet :
  446. if (errorCodePrev != errorcode)
  447. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  448. errorCodePrev = errorcode;
  449. break;
  450. // TWMessageBarManager
  451. default:
  452. if (description.length > 0) {
  453. [TWMessageBarManager sharedInstance].styleSheet = self;
  454. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  455. }
  456. break;
  457. }
  458. } else {
  459. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  460. }
  461. });
  462. }
  463. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  464. {
  465. UIColor *backgroundColor = nil;
  466. switch (type)
  467. {
  468. case TWMessageBarMessageTypeError:
  469. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  470. break;
  471. case TWMessageBarMessageTypeSuccess:
  472. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  473. break;
  474. case TWMessageBarMessageTypeInfo:
  475. backgroundColor = [NCBrandColor sharedInstance].brand;
  476. break;
  477. default:
  478. break;
  479. }
  480. return backgroundColor;
  481. }
  482. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  483. {
  484. UIColor *strokeColor = nil;
  485. switch (type)
  486. {
  487. case TWMessageBarMessageTypeError:
  488. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  489. break;
  490. case TWMessageBarMessageTypeSuccess:
  491. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  492. break;
  493. case TWMessageBarMessageTypeInfo:
  494. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  495. break;
  496. default:
  497. break;
  498. }
  499. return strokeColor;
  500. }
  501. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  502. {
  503. UIImage *iconImage = nil;
  504. switch (type)
  505. {
  506. case TWMessageBarMessageTypeError:
  507. iconImage = [UIImage imageNamed:@"icon-error.png"];
  508. break;
  509. case TWMessageBarMessageTypeSuccess:
  510. iconImage = [UIImage imageNamed:@"icon-success.png"];
  511. break;
  512. case TWMessageBarMessageTypeInfo:
  513. iconImage = [UIImage imageNamed:@"icon-info.png"];
  514. break;
  515. default:
  516. break;
  517. }
  518. return iconImage;
  519. }
  520. - (void)updateApplicationIconBadgeNumber
  521. {
  522. if (self.activeAccount.length == 0 || self.maintenanceMode)
  523. return;
  524. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  525. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  526. NSInteger counterUpload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  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] getCapabilitesWithAccount:self.activeAccount];
  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. #pragma --------------------------------------------------------------------------------------------
  875. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  876. #pragma --------------------------------------------------------------------------------------------
  877. - (void)loadAutoDownloadUpload
  878. {
  879. if (self.activeAccount.length == 0 || self.maintenanceMode)
  880. return;
  881. tableMetadata *metadataForUpload, *metadataForDownload;
  882. long counterDownload = 0, counterUpload = 0;
  883. NSUInteger sizeDownload = 0, sizeUpload = 0;
  884. BOOL isE2EE = false;
  885. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  886. // Detect E2EE
  887. NSString *saveserverUrl = @"";
  888. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d", self.activeAccount, k_metadataStatusNormal] sorted:nil ascending:NO];
  889. for (tableMetadata *metadata in metadatasForE2EE) {
  890. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  891. saveserverUrl = metadata.serverUrl;
  892. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  893. isE2EE = true;
  894. break;
  895. }
  896. }
  897. }
  898. // E2EE : not in background
  899. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  900. return;
  901. }
  902. // E2EE : only 1 operation
  903. if (isE2EE) {
  904. maxConcurrentOperationDownloadUpload = 1;
  905. }
  906. // Stop Timer
  907. [_timerProcessAutoDownloadUpload invalidate];
  908. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  909. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  910. // Counter
  911. counterDownload = [metadatasDownload count];
  912. counterUpload = [metadatasUpload count];
  913. // Size
  914. for (tableMetadata *metadata in metadatasDownload) {
  915. sizeDownload = sizeDownload + metadata.size;
  916. }
  917. for (tableMetadata *metadata in metadatasUpload) {
  918. sizeUpload = sizeUpload + metadata.size;
  919. }
  920. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  921. // ------------------------- <selector Download> -------------------------
  922. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  923. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status == %d", _activeAccount, k_metadataStatusWaitDownload]];
  924. if (metadataForDownload) {
  925. metadataForDownload.status = k_metadataStatusInDownload;
  926. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  927. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  928. counterDownload++;
  929. sizeDownload = sizeDownload + metadata.size;
  930. } else {
  931. break;
  932. }
  933. }
  934. // ------------------------- <selector Upload> -------------------------
  935. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  936. if (sizeUpload > k_maxSizeOperationUpload) {
  937. break;
  938. }
  939. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadFile, k_metadataStatusWaitUpload]];
  940. if (metadataForUpload) {
  941. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  942. metadataForUpload.session = k_upload_session;
  943. }
  944. metadataForUpload.status = k_metadataStatusInUpload;
  945. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  946. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  947. counterUpload++;
  948. sizeUpload = sizeUpload + metadata.size;
  949. } else {
  950. break;
  951. }
  952. }
  953. // ------------------------- <selector Auto Upload> -------------------------
  954. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  955. if (sizeUpload > k_maxSizeOperationUpload) {
  956. break;
  957. }
  958. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUpload, k_metadataStatusWaitUpload]];
  959. if (metadataForUpload) {
  960. metadataForUpload.status = k_metadataStatusInUpload;
  961. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  962. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  963. counterUpload++;
  964. sizeUpload = sizeUpload + metadata.size;
  965. } else {
  966. break;
  967. }
  968. }
  969. // ------------------------- <selector Auto Upload All> ----------------------
  970. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  971. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %i", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  972. NSInteger errorCount = [metadatas count];
  973. if (errorCount >= k_maxErrorAutoUploadAll) {
  974. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  975. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  976. } else {
  977. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  978. if (sizeUpload > k_maxSizeOperationUpload) {
  979. break;
  980. }
  981. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusWaitUpload]];
  982. if (metadataForUpload) {
  983. metadataForUpload.status = k_metadataStatusInUpload;
  984. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  985. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  986. counterUpload++;
  987. sizeUpload = sizeUpload + metadata.size;
  988. } else {
  989. break;
  990. }
  991. }
  992. }
  993. // No Download/upload available ? --> remove errors for retry
  994. //
  995. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  996. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", _activeAccount, k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  997. for (tableMetadata *metadata in metadatas) {
  998. if (metadata.status == k_metadataStatusDownloadError)
  999. metadata.status = k_metadataStatusWaitDownload;
  1000. else if (metadata.status == k_metadataStatusUploadError)
  1001. metadata.status = k_metadataStatusWaitUpload;
  1002. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1003. }
  1004. }
  1005. // Verify internal error download (lost task)
  1006. //
  1007. 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];
  1008. for (tableMetadata *metadata in matadatasInDownloading) {
  1009. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1010. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1011. NSURLSessionTask *findTask;
  1012. for (NSURLSessionTask *task in downloadTasks) {
  1013. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1014. findTask = task;
  1015. }
  1016. }
  1017. if (!findTask) {
  1018. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1019. metadata.status = k_metadataStatusWaitDownload;
  1020. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1021. }
  1022. }];
  1023. }
  1024. // Verify internal error upload (lost task)
  1025. //
  1026. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1027. for (tableMetadata *metadata in metadatasUploading) {
  1028. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1029. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1030. NSURLSessionTask *findTask;
  1031. for (NSURLSessionTask *task in uploadTasks) {
  1032. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1033. findTask = task;
  1034. }
  1035. }
  1036. if (!findTask) {
  1037. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1038. metadata.status = k_metadataStatusWaitUpload;
  1039. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1040. }
  1041. }];
  1042. }
  1043. // Upload in pending
  1044. //
  1045. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d AND sessionTaskIdentifier == 0", self.activeAccount, k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1046. for (tableMetadata *metadata in metadatasInUpload) {
  1047. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1048. metadata.status = k_metadataStatusWaitUpload;
  1049. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1050. } else {
  1051. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1052. }
  1053. }
  1054. if (metadatasInUpload.count == 0) {
  1055. [self.sessionPendingStatusInUpload removeAllObjects];
  1056. }
  1057. // Start Timer
  1058. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1059. }
  1060. #pragma --------------------------------------------------------------------------------------------
  1061. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1062. #pragma --------------------------------------------------------------------------------------------
  1063. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1064. {
  1065. return YES;
  1066. }
  1067. // Method called from iOS system to send a file from other app.
  1068. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1069. {
  1070. NSError *error;
  1071. NSLog(@"[LOG] the path is: %@", url.path);
  1072. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1073. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1074. if (self.activeAccount) {
  1075. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1076. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1077. if (error == nil) {
  1078. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1079. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1080. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1081. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1082. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1083. });
  1084. }
  1085. }
  1086. return YES;
  1087. }
  1088. #pragma --------------------------------------------------------------------------------------------
  1089. #pragma mark ===== Crashlytics =====
  1090. #pragma --------------------------------------------------------------------------------------------
  1091. - (void) logUser
  1092. {
  1093. if (self.activeAccount.length > 0)
  1094. [CrashlyticsKit setUserName:self.activeAccount];
  1095. }
  1096. #pragma --------------------------------------------------------------------------------------------
  1097. #pragma mark ===== Maintenance Mode =====
  1098. #pragma --------------------------------------------------------------------------------------------
  1099. - (void)maintenanceMode:(BOOL)mode
  1100. {
  1101. self.maintenanceMode = mode;
  1102. }
  1103. #pragma --------------------------------------------------------------------------------------------
  1104. #pragma mark ===== UPGRADE =====
  1105. #pragma --------------------------------------------------------------------------------------------
  1106. - (BOOL)upgrade
  1107. {
  1108. #ifdef DEBUG
  1109. //self.maintenanceMode = YES;
  1110. #endif
  1111. NSString *actualVersion = [CCUtility getVersion];
  1112. NSString *actualBuild = [CCUtility getBuild];
  1113. /* ---------------------- UPGRADE VERSION ----------------------- */
  1114. // VERSION < 2.17.6
  1115. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1116. // Remove All old Photo Library
  1117. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1118. }
  1119. // VERSION == 2.17.6
  1120. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1121. // Build < 10
  1122. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1123. // Remove All old Photo Library
  1124. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1125. }
  1126. }
  1127. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1128. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1129. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1130. }
  1131. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1132. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1133. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1134. NSString *account = @"";
  1135. NSString *directoryUser = @"";
  1136. NSString *fileName;
  1137. for (tableLocalFile *record in records) {
  1138. if (![account isEqualToString:record.account]) {
  1139. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1140. if (tableAccount) {
  1141. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1142. account = record.account;
  1143. }
  1144. }
  1145. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1146. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1147. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1148. }
  1149. }
  1150. });
  1151. }
  1152. // VERSION == 2.22.8
  1153. if ([actualVersion isEqualToString:@"2.22.8"]) {
  1154. // Build < 20
  1155. if (([actualBuild compare:@"20" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1156. NSArray *directories = [[NCManageDatabase sharedInstance] getTablesDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl != ''"] sorted:@"account" ascending:NO];
  1157. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1158. [[NCManageDatabase sharedInstance] clearTable:[tablePhotos class] account:nil];
  1159. [[NCManageDatabase sharedInstance] clearTable:[tableDirectory class] account:nil];
  1160. for (tableDirectory *directory in directories) {
  1161. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:directory.e2eEncrypted favorite:directory.favorite fileID:directory.fileID permissions:directory.permissions serverUrl:directory.serverUrl account:directory.account];
  1162. [[NCManageDatabase sharedInstance] setLockOfflineDirectoryWithServerUrl:directory.serverUrl account:directory.account lock:directory.lock offline:directory.offline];
  1163. }
  1164. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1165. }
  1166. }
  1167. return YES;
  1168. }
  1169. @end