AppDelegate.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. //
  2. // AppDelegate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import <JDStatusBarNotification/JDStatusBarNotification.h>
  25. #import "AFURLSessionManager.h"
  26. #import "CCNetworking.h"
  27. #import "CCGraphics.h"
  28. #import "CCMedia.h"
  29. #import "CCSynchronize.h"
  30. #import "CCMain.h"
  31. #import "CCDetail.h"
  32. #import <Fabric/Fabric.h>
  33. #import <Crashlytics/Crashlytics.h>
  34. #import "NCBridgeSwift.h"
  35. #import "NCAutoUpload.h"
  36. #import "Firebase.h"
  37. #import "NCPushNotificationEncryption.h"
  38. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  39. @end
  40. @implementation AppDelegate
  41. + (void)initialize
  42. {
  43. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  44. }
  45. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  46. {
  47. NSString *path;
  48. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  49. NSLog(@"[LOG] Start program group -----------------");
  50. NSLog(@"%@", [dirGroup path]);
  51. NSLog(@"[LOG] Start program application -----------");
  52. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  53. NSLog(@"[LOG] -------------------------------------");
  54. // create Directory Documents
  55. path = [CCUtility getDirectoryDocuments];
  56. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  57. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  58. // create Directory audio => Library, Application Support, audio
  59. path = [CCUtility getDirectoryAudio];
  60. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  61. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  62. // create Directory database Nextcloud
  63. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  64. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  65. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  66. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  67. // create Directory User Data
  68. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  69. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  70. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  71. // create Directory Provider Storage
  72. path = [CCUtility getDirectoryProviderStorage];
  73. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  74. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  75. // create Directory Scan
  76. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  77. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  78. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  79. // Verify upgrade
  80. if ([self upgrade]) {
  81. // Set account, if no exists clear all
  82. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  83. if (account == nil) {
  84. // remove all the keys Chain
  85. [CCUtility deleteAllChainStore];
  86. // remove all the App group key
  87. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  88. } else {
  89. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  90. }
  91. }
  92. #ifdef DEBUG
  93. NSLog(@"[LOG] Copy DB on Documents directory");
  94. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  95. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  96. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  97. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  98. #endif
  99. // 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. // Upload Pending In Upload (crash)
  112. self.sessionPendingStatusInUpload = [NSMutableArray new];
  113. // Initialization Notification
  114. self.listOfNotifications = [NSMutableArray new];
  115. // Background Fetch
  116. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  117. // Initialization List
  118. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  119. self.listMainVC = [[NSMutableDictionary alloc] init];
  120. // Firebase - Push Notification
  121. @try {
  122. [FIRApp configure];
  123. } @catch (NSException *exception) {
  124. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  125. }
  126. // Display notification (sent via APNS)
  127. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  128. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  129. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  130. }];
  131. [application registerForRemoteNotifications];
  132. [FIRMessaging messaging].delegate = self;
  133. // setting Reachable in back
  134. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  135. self.reachability = [Reachability reachabilityForInternetConnection];
  136. self.lastReachability = [self.reachability isReachable];
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  138. [self.reachability startNotifier];
  139. });
  140. //AV Session
  141. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  142. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  143. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  144. // How to hide UINavigationBar 1px bottom line < iOS 11
  145. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  146. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  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. [self logUser];
  165. // Store review
  166. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  167. NCStoreReview *review = [NCStoreReview new];
  168. [review incrementAppRuns];
  169. [review showStoreReview];
  170. }
  171. return YES;
  172. }
  173. //
  174. // L' applicazione si dimetterà dallo stato di attivo
  175. //
  176. - (void)applicationWillResignActive:(UIApplication *)application
  177. {
  178. [_activeMain closeAllMenu];
  179. [self updateApplicationIconBadgeNumber];
  180. }
  181. //
  182. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  183. //
  184. - (void)applicationWillEnterForeground:(UIApplication *)application
  185. {
  186. // Test Maintenance
  187. if (self.activeAccount.length == 0 || self.maintenanceMode)
  188. return;
  189. NSLog(@"[LOG] Request Service Server Nextcloud");
  190. [[NCService sharedInstance] startRequestServicesServer];
  191. NSLog(@"[LOG] Initialize Auto upload");
  192. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  193. NSLog(@"[LOG] Read active directory");
  194. [self.activeMain readFileReloadFolder];
  195. }
  196. //
  197. // L' applicazione entrerà in primo piano (attivo sempre)
  198. //
  199. - (void)applicationDidBecomeActive:(UIApplication *)application
  200. {
  201. // Test Maintenance
  202. if (self.activeAccount.length == 0 || self.maintenanceMode)
  203. return;
  204. // middelware ping
  205. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  206. NSLog(@"[LOG] Middleware Ping");
  207. [[NCService sharedInstance] middlewarePing];
  208. }
  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. if (self.activeAccount.length == 0 || self.maintenanceMode)
  522. return;
  523. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  524. 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];
  525. 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];
  526. NSInteger total = counterDownload + counterUpload;
  527. dispatch_async(dispatch_get_main_queue(), ^{
  528. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  529. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  530. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  531. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  532. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  533. if (total > 0) {
  534. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  535. } else {
  536. [tbItem setBadgeValue:nil];
  537. }
  538. }
  539. });
  540. });
  541. }
  542. #pragma --------------------------------------------------------------------------------------------
  543. #pragma mark ===== TabBarController =====
  544. #pragma --------------------------------------------------------------------------------------------
  545. - (void)createTabBarController:(UITabBarController *)tabBarController
  546. {
  547. UITabBarItem *item;
  548. NSLayoutConstraint *constraint;
  549. CGFloat multiplier = 0;
  550. CGFloat safeAreaBottom = 0;
  551. if (@available(iOS 11, *)) {
  552. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  553. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  554. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  555. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  556. } else {
  557. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  558. }
  559. }
  560. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  561. // File
  562. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  563. [item setTitle:NSLocalizedString(@"_home_", nil)];
  564. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  565. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  566. // Favorites
  567. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  568. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  569. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  570. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  571. // (PLUS)
  572. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  573. item.title = @"";
  574. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  575. item.enabled = false;
  576. // Media
  577. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  578. [item setTitle:NSLocalizedString(@"_media_", nil)];
  579. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  580. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  581. // More
  582. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  583. [item setTitle:NSLocalizedString(@"_more_", nil)];
  584. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  585. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  586. // Plus Button
  587. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  588. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  589. buttonPlus.tag = 99;
  590. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  591. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  592. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  593. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  594. [tabBarController.tabBar addSubview:buttonPlus];
  595. multiplier = 1.0;
  596. // X
  597. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  598. [tabBarController.view addConstraint:constraint];
  599. // Y
  600. if (safeAreaBottom == 0) {
  601. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  602. } else {
  603. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  604. }
  605. [tabBarController.view addConstraint:constraint];
  606. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  607. // Width
  608. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  609. [tabBarController.view addConstraint:constraint];
  610. // Height
  611. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  612. [tabBarController.view addConstraint:constraint];
  613. }
  614. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  615. {
  616. nav.translucent = NO;
  617. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  618. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  619. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  620. // Change bar bottom line shadow
  621. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  622. if (!online)
  623. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  624. nav.hidden = hidden;
  625. [nav setAlpha:1];
  626. }
  627. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  628. {
  629. tab.translucent = NO;
  630. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  631. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  632. tab.hidden = hidden;
  633. [tab setAlpha:1];
  634. }
  635. - (void)plusButtonVisibile:(BOOL)visible
  636. {
  637. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  638. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  639. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  640. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  641. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  642. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  643. if (buttonPlus) {
  644. if (visible) {
  645. buttonPlus.hidden = false;
  646. } else {
  647. buttonPlus.hidden = true;
  648. }
  649. }
  650. }
  651. - (void)handleTouchTabbarCenter:(id)sender
  652. {
  653. // Test Maintenance
  654. if (self.maintenanceMode)
  655. return;
  656. UIView *view = [(UIButton *)sender superview];
  657. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  658. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  659. }
  660. - (void)selectedTabBarController:(NSInteger)index
  661. {
  662. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  663. if (splitViewController.isCollapsed) {
  664. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  665. for (UINavigationController *nvc in tbc.viewControllers) {
  666. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  667. [nvc popToRootViewControllerAnimated:NO];
  668. }
  669. [tbc setSelectedIndex: index];
  670. } else {
  671. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  672. [nvcDetail popToRootViewControllerAnimated:NO];
  673. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  674. [tbc setSelectedIndex: index];
  675. }
  676. }
  677. - (NSString *)getTabBarControllerActiveServerUrl
  678. {
  679. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  680. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  681. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  682. NSInteger index = tabBarController.selectedIndex;
  683. // select active serverUrl
  684. if (index == k_tabBarApplicationIndexFile) {
  685. serverUrl = self.activeMain.serverUrl;
  686. } else if (index == k_tabBarApplicationIndexFavorite) {
  687. if (self.activeFavorites.serverUrl)
  688. serverUrl = self.activeFavorites.serverUrl;
  689. } else if (index == k_tabBarApplicationIndexMedia) {
  690. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  691. }
  692. return serverUrl;
  693. }
  694. #pragma --------------------------------------------------------------------------------------------
  695. #pragma mark ===== Theming Color =====
  696. #pragma --------------------------------------------------------------------------------------------
  697. - (void)settingThemingColorBrand
  698. {
  699. if (self.activeAccount.length == 0 || self.maintenanceMode)
  700. return;
  701. if ([NCBrandOptions sharedInstance].use_themingColor) {
  702. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  703. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  704. } else {
  705. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  706. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  707. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  708. }
  709. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  710. }
  711. - (void)changeTheming:(UIViewController *)vc
  712. {
  713. // Change Navigation & TabBar color
  714. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  715. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  716. // Change bar bottom line shadow
  717. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  718. // Change button Plus
  719. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  720. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  721. UIButton *button = [tabBarController.view viewWithTag:99];
  722. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  723. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  724. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  725. // Tint Color GLOBAL WINDOW
  726. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  727. }
  728. #pragma --------------------------------------------------------------------------------------------
  729. #pragma mark ===== Manager Passcode =====
  730. #pragma --------------------------------------------------------------------------------------------
  731. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  732. {
  733. // ServerUrl active
  734. NSString *serverUrl = self.activeMain.serverUrl;
  735. BOOL isBlockZone = false;
  736. // fermiamo la data della sessione
  737. self.sessionePasscodeLock = nil;
  738. // se il block code è a zero esci con NON attivare la richiesta password
  739. if ([[CCUtility getBlockCode] length] == 0) return NO;
  740. // se non c'è attivo un account esci con NON attivare la richiesta password
  741. if ([self.activeAccount length] == 0) return NO;
  742. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  743. if (serverUrl && _activeUrl) {
  744. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  745. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  746. if (directory.lock) {
  747. isBlockZone = true;
  748. break;
  749. } else {
  750. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  751. if (serverUrl == self.activeUrl)
  752. break;
  753. }
  754. }
  755. }
  756. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  757. return YES;
  758. }
  759. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  760. {
  761. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  762. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  763. viewController.delegate = self;
  764. viewController.title = [NCBrandOptions sharedInstance].brand;
  765. viewController.fromType = CCBKPasscodeFromLockScreen;
  766. viewController.inputViewTitlePassword = YES;
  767. if ([CCUtility getSimplyBlockCode]) {
  768. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  769. viewController.passcodeInputView.maximumLength = 6;
  770. } else {
  771. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  772. viewController.passcodeInputView.maximumLength = 64;
  773. }
  774. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  775. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  776. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  777. return navigationController;
  778. }
  779. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  780. {
  781. [aViewController dismissViewControllerAnimated:YES completion:nil];
  782. // is a lock screen
  783. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  784. [aViewController dismissViewControllerAnimated:YES completion:nil];
  785. // start session Passcode Lock
  786. BOOL isBlockZone = false;
  787. NSString *serverUrl = self.activeMain.serverUrl;
  788. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  789. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  790. if (directory.lock) {
  791. isBlockZone = true;
  792. break;
  793. } else {
  794. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  795. if (serverUrl == self.activeUrl)
  796. break;
  797. }
  798. }
  799. if (isBlockZone)
  800. self.sessionePasscodeLock = [NSDate date];
  801. }
  802. }
  803. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  804. {
  805. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  806. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  807. //self.lockUntilDate = nil;
  808. //self.failedAttempts = 0;
  809. aResultHandler(YES);
  810. } else aResultHandler(NO);
  811. } else aResultHandler(YES);
  812. }
  813. #pragma --------------------------------------------------------------------------------------------
  814. #pragma mark ===== reachabilityChanged =====
  815. #pragma --------------------------------------------------------------------------------------------
  816. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  817. {
  818. if ([self.reachability isReachable]) {
  819. if (self.lastReachability == NO) {
  820. NSLog(@"[LOG] Request Service Server Nextcloud");
  821. [[NCService sharedInstance] startRequestServicesServer];
  822. }
  823. NSLog(@"[LOG] Reachability Changed: Reachable");
  824. self.lastReachability = YES;
  825. } else {
  826. if (self.lastReachability == YES) {
  827. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  828. }
  829. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  830. self.lastReachability = NO;
  831. }
  832. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  833. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  834. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  835. }
  836. #pragma --------------------------------------------------------------------------------------------
  837. #pragma mark ===== Fetch =====
  838. #pragma --------------------------------------------------------------------------------------------
  839. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  840. {
  841. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  842. // Verify new photo
  843. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  844. // after 20 sec
  845. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  846. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  847. if ([records count] > 0) {
  848. completionHandler(UIBackgroundFetchResultNewData);
  849. } else {
  850. completionHandler(UIBackgroundFetchResultNoData);
  851. }
  852. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  853. });
  854. }
  855. #pragma --------------------------------------------------------------------------------------------
  856. #pragma mark ===== Operation Networking & Session =====
  857. #pragma --------------------------------------------------------------------------------------------
  858. //
  859. // Method called by the system when all the background task has end
  860. //
  861. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  862. {
  863. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  864. // after 20 sec
  865. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  866. self.backgroundSessionCompletionHandler = completionHandler;
  867. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  868. self.backgroundSessionCompletionHandler = nil;
  869. completionHandler();
  870. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  871. });
  872. }
  873. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  874. {
  875. id operation;
  876. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  877. [operation setQueuePriority:metadataNet.priority];
  878. [netQueue addOperation:operation];
  879. }
  880. #pragma --------------------------------------------------------------------------------------------
  881. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  882. #pragma --------------------------------------------------------------------------------------------
  883. - (void)loadAutoDownloadUpload
  884. {
  885. if (self.activeAccount.length == 0 || self.maintenanceMode)
  886. return;
  887. tableMetadata *metadataForUpload, *metadataForDownload;
  888. long counterDownload = 0, counterUpload = 0;
  889. NSUInteger sizeDownload = 0, sizeUpload = 0;
  890. BOOL isE2EE = false;
  891. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperationDownloadUpload;
  892. // Detect E2EE
  893. NSString *saveserverUrl = @"";
  894. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d", self.activeAccount, k_metadataStatusNormal] sorted:nil ascending:NO];
  895. for (tableMetadata *metadata in metadatasForE2EE) {
  896. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  897. saveserverUrl = metadata.serverUrl;
  898. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  899. isE2EE = true;
  900. break;
  901. }
  902. }
  903. }
  904. // E2EE : not in background
  905. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  906. return;
  907. }
  908. // E2EE : only 1 operation
  909. if (isE2EE) {
  910. maxConcurrentOperationDownloadUpload = 1;
  911. }
  912. // Stop Timer
  913. [_timerProcessAutoDownloadUpload invalidate];
  914. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  915. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  916. // Counter
  917. counterDownload = [metadatasDownload count];
  918. counterUpload = [metadatasUpload count];
  919. // Size
  920. for (tableMetadata *metadata in metadatasDownload) {
  921. sizeDownload = sizeDownload + metadata.size;
  922. }
  923. for (tableMetadata *metadata in metadatasUpload) {
  924. sizeUpload = sizeUpload + metadata.size;
  925. }
  926. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  927. // ------------------------- <selector Download> -------------------------
  928. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  929. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status == %d", _activeAccount, k_metadataStatusWaitDownload]];
  930. if (metadataForDownload) {
  931. metadataForDownload.status = k_metadataStatusInDownload;
  932. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  933. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  934. counterDownload++;
  935. sizeDownload = sizeDownload + metadata.size;
  936. } else {
  937. break;
  938. }
  939. }
  940. // ------------------------- <selector Upload> -------------------------
  941. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  942. if (sizeUpload > k_maxSizeOperationUpload) {
  943. break;
  944. }
  945. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadFile, k_metadataStatusWaitUpload]];
  946. if (metadataForUpload) {
  947. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  948. metadataForUpload.session = k_upload_session;
  949. }
  950. metadataForUpload.status = k_metadataStatusInUpload;
  951. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  952. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  953. counterUpload++;
  954. sizeUpload = sizeUpload + metadata.size;
  955. } else {
  956. break;
  957. }
  958. }
  959. // ------------------------- <selector Auto Upload> -------------------------
  960. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  961. if (sizeUpload > k_maxSizeOperationUpload) {
  962. break;
  963. }
  964. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUpload, k_metadataStatusWaitUpload]];
  965. if (metadataForUpload) {
  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 All> ----------------------
  976. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  977. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %i", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  978. NSInteger errorCount = [metadatas count];
  979. if (errorCount >= k_maxErrorAutoUploadAll) {
  980. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  981. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  982. } else {
  983. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  984. if (sizeUpload > k_maxSizeOperationUpload) {
  985. break;
  986. }
  987. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusWaitUpload]];
  988. if (metadataForUpload) {
  989. metadataForUpload.status = k_metadataStatusInUpload;
  990. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  991. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  992. counterUpload++;
  993. sizeUpload = sizeUpload + metadata.size;
  994. } else {
  995. break;
  996. }
  997. }
  998. }
  999. // No Download/upload available ? --> remove errors for retry
  1000. //
  1001. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1002. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", _activeAccount, k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1003. for (tableMetadata *metadata in metadatas) {
  1004. if (metadata.status == k_metadataStatusDownloadError)
  1005. metadata.status = k_metadataStatusWaitDownload;
  1006. else if (metadata.status == k_metadataStatusUploadError)
  1007. metadata.status = k_metadataStatusWaitUpload;
  1008. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1009. }
  1010. }
  1011. // Verify internal error download (lost task)
  1012. //
  1013. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1014. for (tableMetadata *metadata in matadatasInDownloading) {
  1015. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1016. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1017. NSURLSessionTask *findTask;
  1018. for (NSURLSessionTask *task in downloadTasks) {
  1019. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1020. findTask = task;
  1021. }
  1022. }
  1023. if (!findTask) {
  1024. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1025. metadata.status = k_metadataStatusWaitDownload;
  1026. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1027. }
  1028. }];
  1029. }
  1030. // Verify internal error upload (lost task)
  1031. //
  1032. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d", self.activeAccount, k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1033. for (tableMetadata *metadata in metadatasUploading) {
  1034. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1035. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1036. NSURLSessionTask *findTask;
  1037. for (NSURLSessionTask *task in uploadTasks) {
  1038. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1039. findTask = task;
  1040. }
  1041. }
  1042. if (!findTask) {
  1043. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1044. metadata.status = k_metadataStatusWaitUpload;
  1045. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1046. }
  1047. }];
  1048. }
  1049. // Upload in pending
  1050. //
  1051. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != %@ AND status == %d AND sessionTaskIdentifier == 0", self.activeAccount, k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1052. for (tableMetadata *metadata in metadatasInUpload) {
  1053. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1054. metadata.status = k_metadataStatusWaitUpload;
  1055. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1056. } else {
  1057. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1058. }
  1059. }
  1060. if (metadatasInUpload.count == 0) {
  1061. [self.sessionPendingStatusInUpload removeAllObjects];
  1062. }
  1063. // Start Timer
  1064. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1065. }
  1066. #pragma --------------------------------------------------------------------------------------------
  1067. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1068. #pragma --------------------------------------------------------------------------------------------
  1069. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1070. {
  1071. return YES;
  1072. }
  1073. // Method called from iOS system to send a file from other app.
  1074. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1075. {
  1076. NSError *error;
  1077. NSLog(@"[LOG] the path is: %@", url.path);
  1078. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1079. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1080. if (self.activeAccount) {
  1081. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1082. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1083. if (error == nil) {
  1084. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1085. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1086. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1087. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1088. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1089. });
  1090. }
  1091. }
  1092. return YES;
  1093. }
  1094. #pragma --------------------------------------------------------------------------------------------
  1095. #pragma mark ===== Crashlytics =====
  1096. #pragma --------------------------------------------------------------------------------------------
  1097. - (void) logUser
  1098. {
  1099. if (self.activeAccount.length > 0)
  1100. [CrashlyticsKit setUserName:self.activeAccount];
  1101. }
  1102. #pragma --------------------------------------------------------------------------------------------
  1103. #pragma mark ===== Maintenance Mode =====
  1104. #pragma --------------------------------------------------------------------------------------------
  1105. - (void)maintenanceMode:(BOOL)mode
  1106. {
  1107. self.maintenanceMode = mode;
  1108. }
  1109. #pragma --------------------------------------------------------------------------------------------
  1110. #pragma mark ===== UPGRADE =====
  1111. #pragma --------------------------------------------------------------------------------------------
  1112. - (BOOL)upgrade
  1113. {
  1114. #ifdef DEBUG
  1115. //self.maintenanceMode = YES;
  1116. #endif
  1117. NSString *actualVersion = [CCUtility getVersion];
  1118. NSString *actualBuild = [CCUtility getBuild];
  1119. /* ---------------------- UPGRADE VERSION ----------------------- */
  1120. // VERSION < 2.17.6
  1121. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1122. // Remove All old Photo Library
  1123. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1124. }
  1125. // VERSION == 2.17.6
  1126. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1127. // Build < 10
  1128. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1129. // Remove All old Photo Library
  1130. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1131. }
  1132. }
  1133. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1134. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1135. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1136. }
  1137. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1138. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1139. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1140. NSString *account = @"";
  1141. NSString *directoryUser = @"";
  1142. NSString *fileName;
  1143. for (tableLocalFile *record in records) {
  1144. if (![account isEqualToString:record.account]) {
  1145. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1146. if (tableAccount) {
  1147. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1148. account = record.account;
  1149. }
  1150. }
  1151. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1152. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1153. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1154. }
  1155. }
  1156. });
  1157. }
  1158. // VERSION == 2.22.8
  1159. if ([actualVersion isEqualToString:@"2.22.8"]) {
  1160. // Build < 19
  1161. if (([actualBuild compare:@"19" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1162. NSArray *directories = [[NCManageDatabase sharedInstance] getTablesDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl != ''"] sorted:@"account" ascending:NO];
  1163. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1164. [[NCManageDatabase sharedInstance] clearTable:[tablePhotos class] account:nil];
  1165. [[NCManageDatabase sharedInstance] clearTable:[tableDirectory class] account:nil];
  1166. for (tableDirectory *directory in directories) {
  1167. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:directory.e2eEncrypted favorite:directory.favorite lock:directory.lock offline:directory.offline fileID:directory.fileID permissions:directory.permissions serverUrl:directory.serverUrl account:directory.account];
  1168. }
  1169. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1170. }
  1171. }
  1172. return YES;
  1173. }
  1174. @end