AppDelegate.m 66 KB

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