AppDelegate.m 66 KB

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