AppDelegate.m 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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. {
  345. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[pushNotification bodyForRemoteAlerts] message:nil preferredStyle:UIAlertControllerStyleAlert];
  346. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  347. [alertController addAction:okAction];
  348. [self.activeMain presentViewController:alertController animated:YES completion:nil];
  349. }
  350. default:
  351. break;
  352. }
  353. }
  354. }
  355. }
  356. completionHandler();
  357. }
  358. #pragma FIREBASE
  359. - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
  360. {
  361. NSLog(@"FCM registration token: %@", fcmToken);
  362. [CCUtility setPushNotificationToken:fcmToken];
  363. [self subscribingNextcloudServerPushNotification];
  364. }
  365. #pragma --------------------------------------------------------------------------------------------
  366. #pragma mark ===== Quick Actions - ShotcutItem =====
  367. #pragma --------------------------------------------------------------------------------------------
  368. - (void)configDynamicShortcutItems
  369. {
  370. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  371. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  372. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  373. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  374. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  375. // add the array to our app
  376. if (shortcutUpload && shortcutPhotos)
  377. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  378. }
  379. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  380. {
  381. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  382. completionHandler(handledShortCutItem);
  383. }
  384. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  385. {
  386. BOOL handled = NO;
  387. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  388. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  389. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  390. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  391. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  392. dispatch_async(dispatch_get_main_queue(), ^{
  393. if (_activeMain) {
  394. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  395. if (splitViewController.isCollapsed) {
  396. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  397. for (UINavigationController *nvc in tbc.viewControllers) {
  398. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  399. [nvc popToRootViewControllerAnimated:NO];
  400. }
  401. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  402. } else {
  403. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  404. [nvcDetail popToRootViewControllerAnimated:NO];
  405. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  406. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  407. }
  408. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  409. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  410. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  411. });
  412. }
  413. });
  414. handled = YES;
  415. }
  416. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  417. dispatch_async(dispatch_get_main_queue(), ^{
  418. if (_activeMain) {
  419. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  420. if (splitViewController.isCollapsed) {
  421. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  422. for (UINavigationController *nvc in tbc.viewControllers) {
  423. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  424. [nvc popToRootViewControllerAnimated:NO];
  425. }
  426. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  427. } else {
  428. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  429. [nvcDetail popToRootViewControllerAnimated:NO];
  430. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  431. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  432. }
  433. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  434. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  435. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  436. });
  437. }
  438. });
  439. handled = YES;
  440. }
  441. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  442. dispatch_async(dispatch_get_main_queue(), ^{
  443. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  444. if (splitViewController.isCollapsed) {
  445. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  446. for (UINavigationController *nvc in tbc.viewControllers) {
  447. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  448. [nvc popToRootViewControllerAnimated:NO];
  449. }
  450. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  451. } else {
  452. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  453. [nvcDetail popToRootViewControllerAnimated:NO];
  454. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  455. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  456. }
  457. });
  458. handled = YES;
  459. }
  460. return handled;
  461. }
  462. #pragma --------------------------------------------------------------------------------------------
  463. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  464. #pragma --------------------------------------------------------------------------------------------
  465. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  466. {
  467. static NSInteger errorCodePrev = 0;
  468. dispatch_async(dispatch_get_main_queue(), ^{
  469. if (visible) {
  470. switch (errorcode) {
  471. // JDStatusBarNotification
  472. case kCFURLErrorNotConnectedToInternet :
  473. if (errorCodePrev != errorcode)
  474. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  475. errorCodePrev = errorcode;
  476. break;
  477. // TWMessageBarManager
  478. default:
  479. if (description.length > 0) {
  480. [TWMessageBarManager sharedInstance].styleSheet = self;
  481. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  482. }
  483. break;
  484. }
  485. } else {
  486. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  487. }
  488. });
  489. }
  490. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  491. {
  492. UIColor *backgroundColor = nil;
  493. switch (type)
  494. {
  495. case TWMessageBarMessageTypeError:
  496. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  497. break;
  498. case TWMessageBarMessageTypeSuccess:
  499. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  500. break;
  501. case TWMessageBarMessageTypeInfo:
  502. backgroundColor = [NCBrandColor sharedInstance].brand;
  503. break;
  504. default:
  505. break;
  506. }
  507. return backgroundColor;
  508. }
  509. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  510. {
  511. UIColor *strokeColor = nil;
  512. switch (type)
  513. {
  514. case TWMessageBarMessageTypeError:
  515. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  516. break;
  517. case TWMessageBarMessageTypeSuccess:
  518. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  519. break;
  520. case TWMessageBarMessageTypeInfo:
  521. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  522. break;
  523. default:
  524. break;
  525. }
  526. return strokeColor;
  527. }
  528. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  529. {
  530. UIImage *iconImage = nil;
  531. switch (type)
  532. {
  533. case TWMessageBarMessageTypeError:
  534. iconImage = [UIImage imageNamed:@"icon-error.png"];
  535. break;
  536. case TWMessageBarMessageTypeSuccess:
  537. iconImage = [UIImage imageNamed:@"icon-success.png"];
  538. break;
  539. case TWMessageBarMessageTypeInfo:
  540. iconImage = [UIImage imageNamed:@"icon-info.png"];
  541. break;
  542. default:
  543. break;
  544. }
  545. return iconImage;
  546. }
  547. - (void)updateApplicationIconBadgeNumber
  548. {
  549. // Test Maintenance
  550. if (self.maintenanceMode)
  551. return;
  552. 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];
  553. 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];
  554. NSInteger total = counterDownload + counterUpload;
  555. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  556. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  557. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  558. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  559. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  560. if (total > 0) {
  561. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  562. } else {
  563. [tbItem setBadgeValue:nil];
  564. }
  565. }
  566. }
  567. #pragma --------------------------------------------------------------------------------------------
  568. #pragma mark ===== TabBarController =====
  569. #pragma --------------------------------------------------------------------------------------------
  570. - (void)createTabBarController:(UITabBarController *)tabBarController
  571. {
  572. UITabBarItem *item;
  573. NSLayoutConstraint *constraint;
  574. CGFloat multiplier = 0;
  575. CGFloat safeAreaBottom = 0;
  576. if (@available(iOS 11, *)) {
  577. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  578. }
  579. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  580. // File
  581. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  582. [item setTitle:NSLocalizedString(@"_home_", nil)];
  583. item.image = [UIImage imageNamed:@"folder"];
  584. item.selectedImage = [UIImage imageNamed:@"folder"];
  585. // Favorites
  586. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  587. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  588. item.image = [UIImage imageNamed:@"favorite"];
  589. item.selectedImage = [UIImage imageNamed:@"favorite"];
  590. // (PLUS)
  591. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  592. item.title = @"";
  593. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  594. item.enabled = false;
  595. // Photos
  596. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  597. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  598. item.image = [UIImage imageNamed:@"photos"];
  599. item.selectedImage = [UIImage imageNamed:@"photos"];
  600. // More
  601. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  602. [item setTitle:NSLocalizedString(@"_more_", nil)];
  603. item.image = [UIImage imageNamed:@"tabBarMore"];
  604. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  605. // Plus Button
  606. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  607. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  608. buttonPlus.tag = 99;
  609. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  610. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  611. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  612. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  613. [tabBarController.tabBar addSubview:buttonPlus];
  614. multiplier = 1.0;
  615. // X
  616. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  617. [tabBarController.view addConstraint:constraint];
  618. // Y
  619. if (safeAreaBottom == 0) {
  620. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  621. } else {
  622. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:+5];
  623. }
  624. [tabBarController.view addConstraint:constraint];
  625. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  626. // Width
  627. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  628. [tabBarController.view addConstraint:constraint];
  629. // Height
  630. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  631. [tabBarController.view addConstraint:constraint];
  632. }
  633. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  634. {
  635. nav.translucent = NO;
  636. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  637. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  638. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  639. // Change bar bottom line shadow
  640. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  641. if (!online)
  642. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  643. nav.hidden = hidden;
  644. [nav setAlpha:1];
  645. }
  646. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  647. {
  648. tab.translucent = NO;
  649. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  650. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  651. tab.hidden = hidden;
  652. [tab setAlpha:1];
  653. }
  654. - (void)plusButtonVisibile:(BOOL)visible
  655. {
  656. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  657. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  658. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  659. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  660. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  661. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  662. if (buttonPlus) {
  663. if (visible) {
  664. buttonPlus.hidden = false;
  665. } else {
  666. buttonPlus.hidden = true;
  667. }
  668. }
  669. }
  670. - (void)handleTouchTabbarCenter:(id)sender
  671. {
  672. // Test Maintenance
  673. if (self.maintenanceMode)
  674. return;
  675. UIView *view = [[(UIButton *)sender superview] superview];
  676. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  677. [menuAdd createMenuWithView:view];
  678. }
  679. - (void)selectedTabBarController:(NSInteger)index
  680. {
  681. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  682. if (splitViewController.isCollapsed) {
  683. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  684. for (UINavigationController *nvc in tbc.viewControllers) {
  685. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  686. [nvc popToRootViewControllerAnimated:NO];
  687. }
  688. [tbc setSelectedIndex: index];
  689. } else {
  690. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  691. [nvcDetail popToRootViewControllerAnimated:NO];
  692. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  693. [tbc setSelectedIndex: index];
  694. }
  695. }
  696. - (NSString *)getTabBarControllerActiveServerUrl
  697. {
  698. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  699. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  700. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  701. NSInteger index = tabBarController.selectedIndex;
  702. // select active serverUrl
  703. if (index == k_tabBarApplicationIndexFile) {
  704. serverUrl = self.activeMain.serverUrl;
  705. } else if (index == k_tabBarApplicationIndexFavorite) {
  706. if (self.activeFavorites.serverUrl)
  707. serverUrl = self.activeFavorites.serverUrl;
  708. } else if (index == k_tabBarApplicationIndexPhotos) {
  709. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  710. }
  711. return serverUrl;
  712. }
  713. #pragma --------------------------------------------------------------------------------------------
  714. #pragma mark ===== Theming Color =====
  715. #pragma --------------------------------------------------------------------------------------------
  716. - (void)settingThemingColorBrand
  717. {
  718. if (self.activeAccount.length == 0 || self.maintenanceMode)
  719. return;
  720. if ([NCBrandOptions sharedInstance].use_themingColor) {
  721. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  722. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  723. } else {
  724. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  725. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  726. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  727. }
  728. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  729. }
  730. - (void)changeTheming:(UIViewController *)vc
  731. {
  732. // Change Navigation & TabBar color
  733. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  734. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  735. // Change bar bottom line shadow
  736. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  737. // Change button Plus
  738. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  739. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  740. UIButton *button = [tabBarController.view viewWithTag:99];
  741. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  742. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  743. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  744. // Tint Color GLOBAL WINDOW
  745. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  746. }
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== Manager Passcode =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  751. {
  752. // ServerUrl active
  753. NSString *serverUrl = self.activeMain.serverUrl;
  754. BOOL isBlockZone = false;
  755. // fermiamo la data della sessione
  756. self.sessionePasscodeLock = nil;
  757. // se il block code è a zero esci con NON attivare la richiesta password
  758. if ([[CCUtility getBlockCode] length] == 0) return NO;
  759. // se non c'è attivo un account esci con NON attivare la richiesta password
  760. if ([self.activeAccount length] == 0) return NO;
  761. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  762. if (serverUrl && _activeUrl) {
  763. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  764. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  765. if (directory.lock) {
  766. isBlockZone = true;
  767. break;
  768. } else {
  769. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  770. if (serverUrl == self.activeUrl)
  771. break;
  772. }
  773. }
  774. }
  775. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  776. return YES;
  777. }
  778. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  779. {
  780. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  781. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  782. viewController.delegate = self;
  783. viewController.title = [NCBrandOptions sharedInstance].brand;
  784. viewController.fromType = CCBKPasscodeFromLockScreen;
  785. viewController.inputViewTitlePassword = YES;
  786. if ([CCUtility getSimplyBlockCode]) {
  787. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  788. viewController.passcodeInputView.maximumLength = 6;
  789. } else {
  790. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  791. viewController.passcodeInputView.maximumLength = 64;
  792. }
  793. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  794. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  795. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  796. return navigationController;
  797. }
  798. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  799. {
  800. [aViewController dismissViewControllerAnimated:YES completion:nil];
  801. // is a lock screen
  802. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  803. [aViewController dismissViewControllerAnimated:YES completion:nil];
  804. // start session Passcode Lock
  805. BOOL isBlockZone = false;
  806. NSString *serverUrl = self.activeMain.serverUrl;
  807. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  808. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  809. if (directory.lock) {
  810. isBlockZone = true;
  811. break;
  812. } else {
  813. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  814. if (serverUrl == self.activeUrl)
  815. break;
  816. }
  817. }
  818. if (isBlockZone)
  819. self.sessionePasscodeLock = [NSDate date];
  820. }
  821. }
  822. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  823. {
  824. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  825. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  826. //self.lockUntilDate = nil;
  827. //self.failedAttempts = 0;
  828. aResultHandler(YES);
  829. } else aResultHandler(NO);
  830. } else aResultHandler(YES);
  831. }
  832. #pragma --------------------------------------------------------------------------------------------
  833. #pragma mark ===== reachabilityChanged =====
  834. #pragma --------------------------------------------------------------------------------------------
  835. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  836. {
  837. if ([self.reachability isReachable]) {
  838. if (self.lastReachability == NO) {
  839. NSLog(@"[LOG] Request Service Server Nextcloud");
  840. [[NCService sharedInstance] startRequestServicesServer];
  841. }
  842. NSLog(@"[LOG] Reachability Changed: Reachable");
  843. self.lastReachability = YES;
  844. } else {
  845. if (self.lastReachability == YES) {
  846. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  847. }
  848. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  849. self.lastReachability = NO;
  850. }
  851. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  852. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  853. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  854. }
  855. #pragma --------------------------------------------------------------------------------------------
  856. #pragma mark ===== Fetch =====
  857. #pragma --------------------------------------------------------------------------------------------
  858. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  859. {
  860. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  861. // Verify new photo
  862. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  863. // after 20 sec
  864. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  865. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  866. if ([records count] > 0) {
  867. completionHandler(UIBackgroundFetchResultNewData);
  868. } else {
  869. completionHandler(UIBackgroundFetchResultNoData);
  870. }
  871. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  872. });
  873. }
  874. #pragma --------------------------------------------------------------------------------------------
  875. #pragma mark ===== Operation Networking & Session =====
  876. #pragma --------------------------------------------------------------------------------------------
  877. //
  878. // Method called by the system when all the background task has end
  879. //
  880. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  881. {
  882. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  883. // after 20 sec
  884. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  885. self.backgroundSessionCompletionHandler = completionHandler;
  886. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  887. self.backgroundSessionCompletionHandler = nil;
  888. completionHandler();
  889. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  890. });
  891. }
  892. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  893. {
  894. id operation;
  895. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  896. [operation setQueuePriority:metadataNet.priority];
  897. [netQueue addOperation:operation];
  898. }
  899. #pragma --------------------------------------------------------------------------------------------
  900. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  901. #pragma --------------------------------------------------------------------------------------------
  902. - (void)loadAutoDownloadUpload
  903. {
  904. tableMetadata *metadataForUpload, *metadataForDownload;
  905. long counterDownload = 0, counterUpload = 0;
  906. NSUInteger sizeDownload = 0, sizeUpload = 0;
  907. // Test Maintenance
  908. if (self.maintenanceMode)
  909. return;
  910. // E2EE : not in background
  911. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  912. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading]];
  913. if (metadata) {
  914. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND e2eEncrypted == 1", metadata.directoryID]];
  915. if (directory != nil)
  916. return;
  917. }
  918. }
  919. // Stop Timer
  920. [_timerProcessAutoDownloadUpload invalidate];
  921. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  922. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", self.activeAccount, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  923. // Counter
  924. counterDownload = [metadatasDownload count];
  925. counterUpload = [metadatasUpload count];
  926. // Size
  927. for (tableMetadata *metadata in metadatasDownload) {
  928. sizeDownload = sizeDownload + metadata.size;
  929. }
  930. for (tableMetadata *metadata in metadatasUpload) {
  931. sizeUpload = sizeUpload + metadata.size;
  932. }
  933. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  934. // ------------------------- <selector Download> -------------------------
  935. while (counterDownload < k_maxConcurrentOperationDownload) {
  936. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status == %d", _activeAccount, k_metadataStatusWaitDownload]];
  937. if (metadataForDownload) {
  938. metadataForDownload.status = k_metadataStatusInDownload;
  939. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  940. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume delegate:_activeMain];
  941. counterDownload++;
  942. sizeDownload = sizeDownload + metadata.size;
  943. } else {
  944. break;
  945. }
  946. }
  947. // ------------------------- <selector Upload> -------------------------
  948. while (counterUpload < k_maxConcurrentOperationUpload) {
  949. if (sizeUpload > k_maxSizeOperationUpload) {
  950. break;
  951. }
  952. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadFile, k_metadataStatusWaitUpload]];
  953. if (metadataForUpload) {
  954. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  955. metadataForUpload.session = k_upload_session;
  956. }
  957. metadataForUpload.status = k_metadataStatusInUpload;
  958. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  959. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume delegate:_activeMain];
  960. counterUpload++;
  961. sizeUpload = sizeUpload + metadata.size;
  962. } else {
  963. break;
  964. }
  965. }
  966. // ------------------------- <selector Auto Upload> -------------------------
  967. while (counterUpload < k_maxConcurrentOperationUpload) {
  968. if (sizeUpload > k_maxSizeOperationUpload) {
  969. break;
  970. }
  971. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUpload, k_metadataStatusWaitUpload]];
  972. if (metadataForUpload) {
  973. metadataForUpload.status = k_metadataStatusInUpload;
  974. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  975. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume delegate:_activeMain];
  976. counterUpload++;
  977. sizeUpload = sizeUpload + metadata.size;
  978. } else {
  979. break;
  980. }
  981. }
  982. // ------------------------- <selector Auto Upload All> ----------------------
  983. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  984. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %i", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  985. NSInteger errorCount = [metadatas count];
  986. if (errorCount >= k_maxErrorAutoUploadAll) {
  987. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  988. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  989. } else {
  990. while (counterUpload < k_maxConcurrentOperationUpload) {
  991. if (sizeUpload > k_maxSizeOperationUpload) {
  992. break;
  993. }
  994. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND sessionSelector == %@ AND status == %d", _activeAccount, selectorUploadAutoUploadAll, k_metadataStatusWaitUpload]];
  995. if (metadataForUpload) {
  996. metadataForUpload.status = k_metadataStatusInUpload;
  997. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  998. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume delegate:_activeMain];
  999. counterUpload++;
  1000. sizeUpload = sizeUpload + metadata.size;
  1001. } else {
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. // ------------------------- < END > ----------------------
  1007. // No Download/upload available ? --> remove errors for retry
  1008. //
  1009. if (counterDownload+counterUpload == 0) {
  1010. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", _activeAccount, 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. // Start Timer
  1020. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1021. }
  1022. #pragma --------------------------------------------------------------------------------------------
  1023. #pragma mark ===== Verify internal error in Download/Upload =====
  1024. #pragma --------------------------------------------------------------------------------------------
  1025. - (void)verifyInternalErrorDownloadingUploading
  1026. {
  1027. // Test Maintenance
  1028. if (self.maintenanceMode || self.activeAccount.length == 0)
  1029. return;
  1030. 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];
  1031. for (tableMetadata *metadata in recordsInDownloading) {
  1032. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1033. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1034. NSURLSessionTask *findTask;
  1035. for (NSURLSessionTask *task in downloadTasks) {
  1036. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1037. findTask = task;
  1038. }
  1039. }
  1040. if (!findTask) {
  1041. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1042. metadata.status = k_metadataStatusWaitDownload;
  1043. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1044. }
  1045. }];
  1046. }
  1047. 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];
  1048. for (tableMetadata *metadata in recordsInUploading) {
  1049. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1050. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1051. NSURLSessionTask *findTask;
  1052. for (NSURLSessionTask *task in uploadTasks) {
  1053. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1054. findTask = task;
  1055. }
  1056. }
  1057. if (!findTask) {
  1058. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1059. metadata.status = k_metadataStatusWaitUpload;
  1060. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1061. }
  1062. }];
  1063. }
  1064. }
  1065. #pragma --------------------------------------------------------------------------------------------
  1066. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1069. {
  1070. return YES;
  1071. }
  1072. // Method called from iOS system to send a file from other app.
  1073. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1074. {
  1075. NSError *error;
  1076. NSLog(@"[LOG] the path is: %@", url.path);
  1077. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1078. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1079. if (self.activeAccount) {
  1080. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1081. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1082. if (error == nil) {
  1083. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1084. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1085. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1086. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1087. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1088. });
  1089. }
  1090. }
  1091. return YES;
  1092. }
  1093. #pragma --------------------------------------------------------------------------------------------
  1094. #pragma mark ===== Crashlytics =====
  1095. #pragma --------------------------------------------------------------------------------------------
  1096. - (void) logUser
  1097. {
  1098. if (self.activeAccount.length > 0)
  1099. [CrashlyticsKit setUserName:self.activeAccount];
  1100. }
  1101. #pragma --------------------------------------------------------------------------------------------
  1102. #pragma mark ===== Maintenance Mode =====
  1103. #pragma --------------------------------------------------------------------------------------------
  1104. - (void)maintenanceMode:(BOOL)mode
  1105. {
  1106. self.maintenanceMode = mode;
  1107. }
  1108. #pragma --------------------------------------------------------------------------------------------
  1109. #pragma mark ===== UPGRADE =====
  1110. #pragma --------------------------------------------------------------------------------------------
  1111. - (BOOL)upgrade
  1112. {
  1113. #ifdef DEBUG
  1114. //self.maintenanceMode = YES;
  1115. #endif
  1116. NSString *actualVersion = [CCUtility getVersion];
  1117. NSString *actualBuild = [CCUtility getBuild];
  1118. /* ---------------------- UPGRADE VERSION ----------------------- */
  1119. // VERSION < 2.17.6
  1120. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1121. // Remove All old Photo Library
  1122. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1123. }
  1124. // VERSION == 2.17.6
  1125. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1126. // Build < 10
  1127. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1128. // Remove All old Photo Library
  1129. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1130. }
  1131. }
  1132. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1133. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1134. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1135. }
  1136. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1137. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1138. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1139. NSString *account = @"";
  1140. NSString *directoryUser = @"";
  1141. NSString *fileName, *fileNameIco;
  1142. for (tableLocalFile *record in records) {
  1143. if (![account isEqualToString:record.account]) {
  1144. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1145. if (tableAccount) {
  1146. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1147. account = record.account;
  1148. }
  1149. }
  1150. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1151. fileNameIco = [NSString stringWithFormat:@"%@/%@.ico", directoryUser, record.fileID];
  1152. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1153. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileName:record.fileName]];
  1154. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameIco])
  1155. [CCUtility moveFileAtPath:fileNameIco toPath:[CCUtility getDirectoryProviderStorageIconFileID:record.fileID fileNameView:record.fileName]];
  1156. }
  1157. }
  1158. });
  1159. }
  1160. return YES;
  1161. }
  1162. @end