AppDelegate.m 66 KB

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