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