AppDelegate.m 66 KB

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