AppDelegate.m 66 KB

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