AppDelegate.m 66 KB

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