AppDelegate.m 67 KB

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