AppDelegate.m 66 KB

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