AppDelegate.m 66 KB

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