AppDelegate.m 68 KB

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