AppDelegate.m 66 KB

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