AppDelegate.m 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. //
  2. // AppDelegate.m
  3. // Crypto Cloud Technology Nextcloud
  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 <MagicalRecord/MagicalRecord.h>
  25. #import "CCCoreData.h"
  26. #import "iRate.h"
  27. #import "AFURLSessionManager.h"
  28. #import "CCNetworking.h"
  29. #import "CCCrypto.h"
  30. #import "CCManageAsset.h"
  31. #import "CCGraphics.h"
  32. #import "CCPhotos.h"
  33. #import "CCSynchronize.h"
  34. #import "CCMain.h"
  35. #import "CCDetail.h"
  36. #import "Firebase.h"
  37. #import <Fabric/Fabric.h>
  38. #import <Crashlytics/Crashlytics.h>
  39. #import "JDStatusBarNotification.h"
  40. #import "NCBridgeSwift.h"
  41. #import "NCAutoUpload.h"
  42. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  43. {
  44. }
  45. @end
  46. @implementation AppDelegate
  47. + (void)initialize
  48. {
  49. [iRate sharedInstance].daysUntilPrompt = 10;
  50. [iRate sharedInstance].usesUntilPrompt = 10;
  51. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  52. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  53. //enable preview mode
  54. //[iRate sharedInstance].previewMode = YES;
  55. }
  56. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  57. {
  58. // Brand
  59. if ([NCBrandOptions sharedInstance].use_firebase) {
  60. /*
  61. In order for this to work, proper GoogleService-Info.plist must be included
  62. */
  63. @try {
  64. [FIRApp configure];
  65. } @catch (NSException *exception) {
  66. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  67. }
  68. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  69. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  70. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  71. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  72. } else {
  73. // iOS 10 or later
  74. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  75. // For iOS 10 display notification (sent via APNS)
  76. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  77. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  78. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  79. }];
  80. // For iOS 10 data message (sent via FCM)
  81. [FIRMessaging messaging].remoteMessageDelegate = self;
  82. #endif
  83. }
  84. }
  85. NSString *dir;
  86. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  87. NSLog(@"[LOG] Start program group -----------------");
  88. NSLog(@"%@", dirGroup);
  89. NSLog(@"[LOG] Start program application -----------");
  90. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  91. NSLog(@"[LOG] -------------------------------------");
  92. // create Directory local => Documents
  93. dir = [CCUtility getDirectoryLocal];
  94. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  95. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  96. // create Directory audio => Library, Application Support, audio
  97. dir = [CCUtility getDirectoryAudio];
  98. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  99. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  100. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  101. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  102. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  103. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  104. // create dir Database Nextcloud
  105. dir = [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path];
  106. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  107. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  108. NSError *error = nil;
  109. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:dir error:&error];
  110. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  111. #ifdef DEBUG
  112. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  113. #else
  114. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  115. #endif
  116. // Verify upgrade
  117. if ([self upgrade]) {
  118. // Set account, if no exists clear all
  119. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  120. if (account == nil) {
  121. // remove all the keys Chain
  122. [CCUtility deleteAllChainStore];
  123. // remove all the App group key
  124. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  125. } else {
  126. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activePassword:account.password];
  127. }
  128. }
  129. // Operation Queue OC Networking
  130. _netQueue = [[NSOperationQueue alloc] init];
  131. _netQueue.name = k_queue;
  132. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  133. _netQueueDownload = [[NSOperationQueue alloc] init];
  134. _netQueueDownload.name = k_download_queue;
  135. _netQueueDownload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  136. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  137. _netQueueDownloadWWan.name = k_download_queuewwan;
  138. _netQueueDownloadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  139. _netQueueUpload = [[NSOperationQueue alloc] init];
  140. _netQueueUpload.name = k_upload_queue;
  141. _netQueueUpload.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  142. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  143. _netQueueUploadWWan.name = k_upload_queuewwan;
  144. _netQueueUploadWWan.maxConcurrentOperationCount = k_maxConcurrentOperationDownloadUpload;
  145. // Add notification change session
  146. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  147. // Initialization Share
  148. self.sharesID = [NSMutableDictionary new];
  149. self.sharesLink = [NSMutableDictionary new];
  150. self.sharesUserAndGroup = [NSMutableDictionary new];
  151. // Initialization Notification
  152. self.listOfNotifications = [NSMutableArray new];
  153. // Background Fetch
  154. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  155. // Initialization List
  156. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  157. self.listChangeTask = [[NSMutableDictionary alloc] init];
  158. self.listMainVC = [[NSMutableDictionary alloc] init];
  159. // Player audio
  160. self.player = [LMMediaPlayerView sharedPlayerView];
  161. self.player.delegate = self;
  162. // ico Image Cache
  163. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  164. // setting Reachable in back
  165. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  166. self.reachability = [Reachability reachabilityForInternetConnection];
  167. self.lastReachability = [self.reachability isReachable];
  168. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  169. [self.reachability startNotifier];
  170. });
  171. //AV Session
  172. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  173. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  174. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  175. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  176. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  177. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  178. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  179. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  180. [app aspectNavigationControllerBar:navigationController.navigationBar encrypted:NO online:YES hidden:NO];
  181. // Settings TabBar
  182. [self createTabBarController];
  183. // passcode
  184. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  185. dispatch_async(dispatch_get_main_queue(), ^{
  186. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  187. });
  188. // Quick Actions
  189. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  190. [self configDynamicShortcutItems];
  191. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  192. if (shortcutItem)
  193. [self handleShortCutItem:shortcutItem];
  194. }
  195. // Start Timer
  196. self.timerProcessAutoUpload = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(processAutoUpload) userInfo:nil repeats:YES];
  197. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  198. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  199. // Registration Push Notification
  200. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  201. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  202. [application registerUserNotificationSettings:notificationSettings];
  203. // Fabric
  204. [Fabric with:@[[Crashlytics class]]];
  205. [self logUser];
  206. return YES;
  207. }
  208. //
  209. // L' applicazione si dimetterà dallo stato di attivo
  210. //
  211. - (void)applicationWillResignActive:(UIApplication *)application
  212. {
  213. [_activeMain closeAllMenu];
  214. [self updateApplicationIconBadgeNumber];
  215. }
  216. //
  217. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  218. //
  219. - (void)applicationWillEnterForeground:(UIApplication *)application
  220. {
  221. // facciamo partire il timer per il controllo delle sessioni e dei Lock
  222. [self.timerVerifySessionInProgress invalidate];
  223. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  224. // refresh active Main
  225. if (_activeMain) {
  226. [_activeMain reloadDatasource];
  227. [_activeMain readFileReloadFolder];
  228. }
  229. // Initializations
  230. [self applicationInitialized];
  231. }
  232. //
  233. // L' applicazione è entrata nello sfondo
  234. //
  235. - (void)applicationDidEnterBackground:(UIApplication *)application
  236. {
  237. NSLog(@"[LOG] Enter in Background");
  238. [[CCQuickActions quickActionsManager] closeAll];
  239. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  240. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  241. __block UIBackgroundTaskIdentifier background_task;
  242. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  243. //Clean up code. Tell the system that we are done.
  244. [application endBackgroundTask: background_task];
  245. background_task = UIBackgroundTaskInvalid;
  246. }];
  247. }
  248. }
  249. //
  250. // L'applicazione terminerà
  251. //
  252. - (void)applicationWillTerminate:(UIApplication *)application
  253. {
  254. [MagicalRecord cleanUp];
  255. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  256. }
  257. //
  258. // Application Initialized
  259. //
  260. - (void)applicationInitialized
  261. {
  262. // Test Maintenance
  263. if (self.maintenanceMode)
  264. return;
  265. // Execute : now
  266. NSLog(@"[LOG] Update Folder Photo");
  267. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:_activeUrl];
  268. if ([autoUploadPath length] > 0)
  269. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  270. // Execute : after 1 sec.
  271. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  272. if (_activeMain) {
  273. NSLog(@"[LOG] Request Server Capabilities");
  274. [_activeMain requestServerCapabilities];
  275. }
  276. if (_activeMain && [[NCBrandOptions sharedInstance] use_middlewarePing]) {
  277. NSLog(@"[LOG] Middleware Ping");
  278. [_activeMain middlewarePing];
  279. }
  280. NSLog(@"[LOG] Initialize Auto upload");
  281. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  282. NSLog(@"[LOG] Listning Favorites");
  283. [_activeFavorites readListingFavorites];
  284. });
  285. // Initialize Auto upload
  286. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateAutoUpload" object:@{@"afterDelay": @(2)}];
  287. }
  288. #pragma --------------------------------------------------------------------------------------------
  289. #pragma mark ===== Process Auto Upload k_timerProcess seconds =====
  290. #pragma --------------------------------------------------------------------------------------------
  291. - (void)processAutoUpload
  292. {
  293. // Test Maintenance
  294. if (self.maintenanceMode)
  295. return;
  296. // BACKGROND & FOREGROUND
  297. NSLog(@"-PROCESS-AUTO-UPLOAD-");
  298. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  299. // ONLY BACKGROUND
  300. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  301. } else {
  302. // ONLY FOREFROUND
  303. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  304. }
  305. }
  306. #pragma --------------------------------------------------------------------------------------------
  307. #pragma mark ===== Setting Active Account =====
  308. #pragma --------------------------------------------------------------------------------------------
  309. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword
  310. {
  311. self.activeAccount = activeAccount;
  312. self.activeUrl = activeUrl;
  313. self.activeUser = activeUser;
  314. self.activePassword = activePassword;
  315. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  316. }
  317. #pragma --------------------------------------------------------------------------------------------
  318. #pragma mark ===== Push Notification =====
  319. #pragma --------------------------------------------------------------------------------------------
  320. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  321. {
  322. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  323. }
  324. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  325. {
  326. [application registerForRemoteNotifications];
  327. }
  328. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  329. {
  330. // test
  331. if (self.activeAccount.length == 0)
  332. return;
  333. // FIREBASE registered token
  334. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  335. NSString *pushToken = [[FIRInstanceID instanceID] token];
  336. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  337. NSString *pushTokenHash = [[CCCrypto sharedManager] createSHA512:pushToken];
  338. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  339. #ifdef DEBUG
  340. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  341. #else
  342. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  343. #endif
  344. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  345. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  346. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  347. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  348. metadataNet.action = actionSubscribingNextcloudServer;
  349. metadataNet.options = options;
  350. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  351. }
  352. }
  353. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  354. {
  355. NSLog(@"[LOG] Error register remote notification %@", error);
  356. }
  357. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  358. UIApplicationState state = [application applicationState];
  359. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  360. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  361. } else {
  362. NSLog(@"[LOG] Receive Notification on Active state");
  363. }
  364. // If you are receiving a notification message while your app is in the background,
  365. // this callback will not be fired till the user taps on the notification launching the application.
  366. // TODO: Handle data of notification
  367. // Print message ID.
  368. //if (userInfo[kGCMMessageIDKey]) {
  369. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  370. //}
  371. // Print full message.
  372. NSLog(@"[LOG] %@", userInfo);
  373. }
  374. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  375. {
  376. UIApplicationState state = [application applicationState];
  377. // Print message ID.
  378. //if (userInfo[kGCMMessageIDKey]) {
  379. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  380. //}
  381. // Print full message.
  382. NSLog(@"[LOG] %@", userInfo);
  383. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  384. } else if (state == UIApplicationStateInactive) {
  385. // user tapped notification
  386. completionHandler(UIBackgroundFetchResultNewData);
  387. } else {
  388. // app is active
  389. completionHandler(UIBackgroundFetchResultNoData);
  390. }
  391. }
  392. #pragma FIREBASE
  393. - (void)tokenRefreshNotification:(NSNotification *)notification {
  394. // Note that this callback will be fired everytime a new token is generated, including the first
  395. // time. So if you need to retrieve the token as soon as it is available this is where that
  396. // should be done.
  397. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  398. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  399. // Connect to FCM since connection may have failed when attempted before having a token.
  400. [self connectToFcm];
  401. // TODO: If necessary send token to application server.
  402. }
  403. - (void)connectToFcm {
  404. // Won't connect since there is no token
  405. if (![[FIRInstanceID instanceID] token]) {
  406. return;
  407. }
  408. // Disconnect previous FCM connection if it exists.
  409. [[FIRMessaging messaging] disconnect];
  410. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  411. if (error != nil) {
  412. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  413. } else {
  414. NSLog(@"[LOG] Connected to FCM.");
  415. }
  416. }];
  417. }
  418. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  419. // Receive data message on iOS 10 devices while app is in the foreground.
  420. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  421. // Print full message
  422. NSLog(@"[LOG] %@", remoteMessage.appData);
  423. }
  424. #endif
  425. #pragma --------------------------------------------------------------------------------------------
  426. #pragma mark ===== Quick Actions - ShotcutItem =====
  427. #pragma --------------------------------------------------------------------------------------------
  428. - (void)configDynamicShortcutItems
  429. {
  430. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  431. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  432. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  433. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUploadEncrypted"];
  434. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  435. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  436. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  437. if (app.isCryptoCloudMode) {
  438. // add the array to our app
  439. [UIApplication sharedApplication].shortcutItems = @[shortcutUploadEncrypted, shortcutUpload, shortcutPhotos];
  440. } else {
  441. // add the array to our app
  442. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  443. }
  444. }
  445. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  446. {
  447. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  448. completionHandler(handledShortCutItem);
  449. }
  450. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  451. {
  452. BOOL handled = NO;
  453. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  454. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  455. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  456. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  457. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  458. dispatch_async(dispatch_get_main_queue(), ^{
  459. if (_activeMain) {
  460. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  461. if (splitViewController.isCollapsed) {
  462. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  463. for (UINavigationController *nvc in tbc.viewControllers) {
  464. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  465. [nvc popToRootViewControllerAnimated:NO];
  466. }
  467. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  468. } else {
  469. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  470. [nvcDetail popToRootViewControllerAnimated:NO];
  471. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  472. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  473. }
  474. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  475. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  476. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  477. });
  478. }
  479. });
  480. handled = YES;
  481. }
  482. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  483. dispatch_async(dispatch_get_main_queue(), ^{
  484. if (_activeMain) {
  485. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  486. if (splitViewController.isCollapsed) {
  487. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  488. for (UINavigationController *nvc in tbc.viewControllers) {
  489. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  490. [nvc popToRootViewControllerAnimated:NO];
  491. }
  492. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  493. } else {
  494. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  495. [nvcDetail popToRootViewControllerAnimated:NO];
  496. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  497. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  498. }
  499. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  500. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  501. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  502. });
  503. }
  504. });
  505. handled = YES;
  506. }
  507. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  508. dispatch_async(dispatch_get_main_queue(), ^{
  509. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  510. if (splitViewController.isCollapsed) {
  511. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  512. for (UINavigationController *nvc in tbc.viewControllers) {
  513. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  514. [nvc popToRootViewControllerAnimated:NO];
  515. }
  516. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  517. } else {
  518. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  519. [nvcDetail popToRootViewControllerAnimated:NO];
  520. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  521. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  522. }
  523. });
  524. handled = YES;
  525. }
  526. return handled;
  527. }
  528. #pragma --------------------------------------------------------------------------------------------
  529. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  530. #pragma --------------------------------------------------------------------------------------------
  531. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  532. {
  533. static NSInteger errorCodePrev = 0;
  534. dispatch_async(dispatch_get_main_queue(), ^{
  535. if (visible) {
  536. if (errorcode == kCFURLErrorNotConnectedToInternet || errorcode == k_CCErrorNetworkNowAvailable) {
  537. if (errorCodePrev != errorcode)
  538. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  539. errorCodePrev = errorcode;
  540. } else {
  541. if (description.length > 0) {
  542. [TWMessageBarManager sharedInstance].styleSheet = self;
  543. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  544. }
  545. }
  546. } else {
  547. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  548. }
  549. });
  550. }
  551. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  552. {
  553. UIColor *backgroundColor = nil;
  554. switch (type)
  555. {
  556. case TWMessageBarMessageTypeError:
  557. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  558. break;
  559. case TWMessageBarMessageTypeSuccess:
  560. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  561. break;
  562. case TWMessageBarMessageTypeInfo:
  563. backgroundColor = [NCBrandColor sharedInstance].brand;
  564. break;
  565. default:
  566. break;
  567. }
  568. return backgroundColor;
  569. }
  570. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  571. {
  572. UIColor *strokeColor = nil;
  573. switch (type)
  574. {
  575. case TWMessageBarMessageTypeError:
  576. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  577. break;
  578. case TWMessageBarMessageTypeSuccess:
  579. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  580. break;
  581. case TWMessageBarMessageTypeInfo:
  582. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  583. break;
  584. default:
  585. break;
  586. }
  587. return strokeColor;
  588. }
  589. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  590. {
  591. UIImage *iconImage = nil;
  592. switch (type)
  593. {
  594. case TWMessageBarMessageTypeError:
  595. iconImage = [UIImage imageNamed:@"icon-error.png"];
  596. break;
  597. case TWMessageBarMessageTypeSuccess:
  598. iconImage = [UIImage imageNamed:@"icon-success.png"];
  599. break;
  600. case TWMessageBarMessageTypeInfo:
  601. iconImage = [UIImage imageNamed:@"icon-info.png"];
  602. break;
  603. default:
  604. break;
  605. }
  606. return iconImage;
  607. }
  608. #pragma --------------------------------------------------------------------------------------------
  609. #pragma mark ===== TabBarController =====
  610. #pragma --------------------------------------------------------------------------------------------
  611. - (void)createTabBarController
  612. {
  613. UITabBarItem *item;
  614. NSLayoutConstraint *constraint;
  615. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  616. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  617. [app aspectTabBar:tabBarController.tabBar hidden:NO];
  618. // File
  619. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  620. [item setTitle:NSLocalizedString(@"_home_", nil)];
  621. item.image = [UIImage imageNamed:@"tabBarFiles"];
  622. item.selectedImage = [UIImage imageNamed:@"tabBarFiles"];
  623. // Favorites
  624. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexOffline];
  625. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  626. item.image = [UIImage imageNamed:@"tabBarFavorite"];
  627. item.selectedImage = [UIImage imageNamed:@"tabBarFavorite"];
  628. // Hide (PLUS)
  629. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexHide];
  630. item.title = nil;
  631. item.image = nil;
  632. item.enabled = false;
  633. // Photos
  634. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  635. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  636. item.image = [UIImage imageNamed:@"tabBarPhotos"];
  637. item.selectedImage = [UIImage imageNamed:@"tabBarPhotos"];
  638. // More
  639. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  640. [item setTitle:NSLocalizedString(@"_more_", nil)];
  641. item.image = [UIImage imageNamed:@"tabBarMore"];
  642. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  643. // Plus Button
  644. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  645. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  646. button.tag = 99;
  647. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  648. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  649. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  650. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  651. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  652. [tabBarController.view addSubview:button];
  653. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  654. [tabBarController.view addConstraint:constraint];
  655. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  656. [tabBarController.view addConstraint:constraint];
  657. }
  658. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav encrypted:(BOOL)encrypted online:(BOOL)online hidden:(BOOL)hidden
  659. {
  660. nav.translucent = NO;
  661. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  662. nav.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  663. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  664. if (encrypted)
  665. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].cryptocloud}];
  666. if (!online)
  667. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  668. nav.hidden = hidden;
  669. [nav setAlpha:1];
  670. }
  671. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  672. {
  673. tab.translucent = NO;
  674. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  675. tab.tintColor = [NCBrandColor sharedInstance].brand;
  676. tab.hidden = hidden;
  677. [tab setAlpha:1];
  678. }
  679. - (void)plusButtonVisibile:(BOOL)visible
  680. {
  681. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  682. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  683. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  684. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  685. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  686. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  687. if (buttonPlus) {
  688. if (visible) {
  689. buttonPlus.hidden = false;
  690. } else {
  691. buttonPlus.hidden = true;
  692. }
  693. }
  694. }
  695. - (void)handleTouchTabbarCenter:(id)sender
  696. {
  697. // Test Maintenance
  698. if (self.maintenanceMode)
  699. return;
  700. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  701. if ([CCUtility getCreateMenuEncrypted])
  702. [menuAdd createMenuEncryptedWithView:self.window.rootViewController.view];
  703. else
  704. [menuAdd createMenuPlainWithView:self.window.rootViewController.view];
  705. }
  706. - (void)updateApplicationIconBadgeNumber
  707. {
  708. // Test Maintenance
  709. if (self.maintenanceMode)
  710. return;
  711. NSInteger queueDownload = [self getNumberDownloadInQueues] + [self getNumberDownloadInQueuesWWan];
  712. NSInteger queueUpload = [self getNumberUploadInQueues] + [self getNumberUploadInQueuesWWan];
  713. // Total
  714. NSInteger total = queueDownload + queueUpload + [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil];
  715. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  716. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  717. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  718. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  719. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  720. if (total > 0)
  721. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  722. else
  723. [tbItem setBadgeValue:nil];
  724. }
  725. }
  726. - (void)selectedTabBarController:(NSInteger)index
  727. {
  728. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  729. if (splitViewController.isCollapsed) {
  730. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  731. for (UINavigationController *nvc in tbc.viewControllers) {
  732. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  733. [nvc popToRootViewControllerAnimated:NO];
  734. }
  735. [tbc setSelectedIndex: index];
  736. } else {
  737. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  738. [nvcDetail popToRootViewControllerAnimated:NO];
  739. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  740. [tbc setSelectedIndex: index];
  741. }
  742. }
  743. #pragma --------------------------------------------------------------------------------------------
  744. #pragma mark ===== Theming Color =====
  745. #pragma --------------------------------------------------------------------------------------------
  746. - (void)settingThemingColorBrand
  747. {
  748. if (self.activeAccount.length > 0) {
  749. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  750. if ([NCBrandOptions sharedInstance].use_themingColor && capabilities.themingColor.length == 7) {
  751. BOOL isLight = [CCGraphics isLight:[CCGraphics colorFromHexString:capabilities.themingColor]];
  752. if (isLight) {
  753. // Activity
  754. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Server Theming" note:NSLocalizedString(@"_theming_is_light_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  755. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  756. } else {
  757. [NCBrandColor sharedInstance].brand = [CCGraphics colorFromHexString:capabilities.themingColor];
  758. }
  759. } else {
  760. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  761. }
  762. } else {
  763. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  764. }
  765. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  766. }
  767. - (void)changeTheming:(UIViewController *)vc
  768. {
  769. UIColor *color = [NCBrandColor sharedInstance].brand;
  770. // Change Navigation & TabBar color
  771. vc.navigationController.navigationBar.barTintColor = color;
  772. vc.tabBarController.tabBar.tintColor = color;
  773. // Change button Plus
  774. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  775. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  776. UIButton *button = [tabBarController.view viewWithTag:99];
  777. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  778. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  779. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  780. // Tint Color GLOBAL WINDOW
  781. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  782. }
  783. #pragma --------------------------------------------------------------------------------------------
  784. #pragma mark ===== Media Player Control =====
  785. #pragma --------------------------------------------------------------------------------------------
  786. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  787. {
  788. switch (event.subtype) {
  789. case UIEventSubtypeRemoteControlPlay:
  790. if (self.player.mediaPlayer) {
  791. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  792. if (self.player.mediaPlayer.nowPlayingItem.title)
  793. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  794. if (self.player.mediaPlayer.nowPlayingItem.artist)
  795. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  796. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  797. [self.player.mediaPlayer play];
  798. }
  799. break;
  800. case UIEventSubtypeRemoteControlPause:
  801. if (self.player.mediaPlayer) {
  802. [self.player.mediaPlayer pause];
  803. }
  804. break;
  805. case UIEventSubtypeRemoteControlNextTrack:
  806. // handle it break;
  807. case UIEventSubtypeRemoteControlPreviousTrack:
  808. // handle it break;
  809. default:
  810. break;
  811. }
  812. }
  813. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  814. {
  815. return YES;
  816. }
  817. #pragma --------------------------------------------------------------------------------------------
  818. #pragma mark ===== Manager Passcode =====
  819. #pragma --------------------------------------------------------------------------------------------
  820. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  821. {
  822. // ServerUrl active
  823. NSString *serverUrl = self.activeMain.serverUrl;
  824. BOOL isBlockZone = false;
  825. // fermiamo la data della sessione
  826. self.sessionePasscodeLock = nil;
  827. // se il block code è a zero esci con NON attivare la richiesta password
  828. if ([[CCUtility getBlockCode] length] == 0) return NO;
  829. // se non c'è attivo un account esci con NON attivare la richiesta password
  830. if ([self.activeAccount length] == 0) return NO;
  831. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  832. if (serverUrl && _activeUrl) {
  833. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  834. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  835. if (directory.lock) {
  836. isBlockZone = true;
  837. break;
  838. } else {
  839. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  840. if (serverUrl == self.activeUrl)
  841. break;
  842. }
  843. }
  844. }
  845. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  846. return YES;
  847. }
  848. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  849. {
  850. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  851. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  852. viewController.delegate = self;
  853. viewController.title = [NCBrandOptions sharedInstance].brand;
  854. viewController.fromType = CCBKPasscodeFromLockScreen;
  855. viewController.inputViewTitlePassword = YES;
  856. if ([CCUtility getSimplyBlockCode]) {
  857. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  858. viewController.passcodeInputView.maximumLength = 6;
  859. } else {
  860. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  861. viewController.passcodeInputView.maximumLength = 64;
  862. }
  863. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  864. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  865. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  866. return navigationController;
  867. }
  868. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  869. {
  870. [aViewController dismissViewControllerAnimated:YES completion:nil];
  871. // is a lock screen
  872. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  873. [aViewController dismissViewControllerAnimated:YES completion:nil];
  874. // start session Passcode Lock
  875. BOOL isBlockZone = false;
  876. NSString *serverUrl = self.activeMain.serverUrl;
  877. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  878. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  879. if (directory.lock) {
  880. isBlockZone = true;
  881. break;
  882. } else {
  883. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  884. if (serverUrl == self.activeUrl)
  885. break;
  886. }
  887. }
  888. if (isBlockZone)
  889. self.sessionePasscodeLock = [NSDate date];
  890. }
  891. }
  892. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  893. {
  894. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  895. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  896. //self.lockUntilDate = nil;
  897. //self.failedAttempts = 0;
  898. aResultHandler(YES);
  899. } else aResultHandler(NO);
  900. } else aResultHandler(YES);
  901. }
  902. #pragma --------------------------------------------------------------------------------------------
  903. #pragma mark ===== reachabilityChanged =====
  904. #pragma --------------------------------------------------------------------------------------------
  905. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  906. {
  907. if ([self.reachability isReachable]) {
  908. if (self.lastReachability == NO) {
  909. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorNetworkNowAvailable];
  910. if (_activeMain)
  911. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  912. }
  913. NSLog(@"[LOG] Reachability Changed: Reachable");
  914. self.lastReachability = YES;
  915. } else {
  916. if (self.lastReachability == YES) {
  917. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  918. }
  919. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  920. self.lastReachability = NO;
  921. }
  922. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  923. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  924. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  925. }
  926. #pragma --------------------------------------------------------------------------------------------
  927. #pragma mark ===== Fetch =====
  928. #pragma --------------------------------------------------------------------------------------------
  929. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  930. {
  931. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  932. // Verify new photo
  933. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  934. // after 20 sec
  935. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  936. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  937. if ([records count] > 0) {
  938. completionHandler(UIBackgroundFetchResultNewData);
  939. } else {
  940. completionHandler(UIBackgroundFetchResultNoData);
  941. }
  942. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  943. });
  944. }
  945. #pragma --------------------------------------------------------------------------------------------
  946. #pragma mark ===== Operation Networking & Session =====
  947. #pragma --------------------------------------------------------------------------------------------
  948. //
  949. // Method called by the system when all the background task has end
  950. //
  951. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  952. {
  953. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  954. // after 20 sec
  955. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  956. self.backgroundSessionCompletionHandler = completionHandler;
  957. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  958. self.backgroundSessionCompletionHandler = nil;
  959. completionHandler();
  960. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  961. });
  962. }
  963. - (void)cancelAllOperations
  964. {
  965. [_netQueue cancelAllOperations];
  966. [_netQueueDownload cancelAllOperations];
  967. [_netQueueDownloadWWan cancelAllOperations];
  968. [_netQueueUpload cancelAllOperations];
  969. [_netQueueUploadWWan cancelAllOperations];
  970. }
  971. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  972. {
  973. id operation;
  974. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl isCryptoCloudMode:_isCryptoCloudMode];
  975. [operation setQueuePriority:metadataNet.priority];
  976. [netQueue addOperation:operation];
  977. }
  978. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  979. {
  980. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  981. for (OCnetworking *operation in [self.netQueueDownload operations])
  982. if ([operation.metadataNet.selector isEqualToString:selector])
  983. [metadatasNet addObject:[operation.metadataNet copy]];
  984. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  985. if ([operation.metadataNet.selector isEqualToString:selector])
  986. [metadatasNet addObject:[operation.metadataNet copy]];
  987. return metadatasNet;
  988. }
  989. - (NSInteger)getNumberDownloadInQueues
  990. {
  991. NSArray *results = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  992. NSInteger queueNunDownload = [results count];
  993. // netQueueDownload
  994. for (NSOperation *operation in [self.netQueueDownload operations])
  995. if (((OCnetworking *)operation).isExecuting == NO) queueNunDownload++;
  996. return queueNunDownload;
  997. }
  998. - (NSInteger)getNumberDownloadInQueuesWWan
  999. {
  1000. NSArray *results = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  1001. NSInteger queueNumDownloadWWan = [results count];
  1002. // netQueueDownloadWWan
  1003. for (NSOperation *operation in [self.netQueueDownloadWWan operations])
  1004. if (((OCnetworking *)operation).isExecuting == NO) queueNumDownloadWWan++;
  1005. return queueNumDownloadWWan;
  1006. }
  1007. - (NSInteger)getNumberUploadInQueues
  1008. {
  1009. NSArray *results = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  1010. NSInteger queueNumUpload = [results count];
  1011. // netQueueUpload
  1012. for (NSOperation *operation in [self.netQueueUpload operations])
  1013. if (((OCnetworking *)operation).isExecuting == NO) queueNumUpload++;
  1014. return queueNumUpload;
  1015. }
  1016. - (NSInteger)getNumberUploadInQueuesWWan
  1017. {
  1018. NSArray *results = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  1019. NSInteger queueNumUploadWWan = [results count];
  1020. // netQueueUploadWWan
  1021. for (NSOperation *operation in [self.netQueueUploadWWan operations])
  1022. if (((OCnetworking *)operation).isExecuting == NO) queueNumUploadWWan++;
  1023. return queueNumUploadWWan;
  1024. }
  1025. - (void)verifyDownloadUploadInProgress
  1026. {
  1027. [self.timerVerifySessionInProgress invalidate];
  1028. // Test Maintenance - Account
  1029. if (self.maintenanceMode == NO || self.activeAccount.length > 0) {
  1030. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  1031. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  1032. }
  1033. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:k_timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  1034. }
  1035. // Notification change session
  1036. - (void)sessionChanged:(NSNotification *)notification
  1037. {
  1038. NSURLSession *session;
  1039. NSString *fileID;
  1040. NSURLSessionTask *task;
  1041. for (id object in notification.object) {
  1042. if ([object isKindOfClass:[NSURLSession class]])
  1043. session = object;
  1044. if ([object isKindOfClass:[NSString class]])
  1045. fileID = object;
  1046. if ([object isKindOfClass:[NSURLSessionTask class]])
  1047. task = object;
  1048. }
  1049. /*
  1050. Task
  1051. */
  1052. if (fileID && [_listChangeTask objectForKey:fileID])
  1053. dispatch_async(dispatch_get_main_queue(), ^{
  1054. [self changeTask:fileID];
  1055. });
  1056. /*
  1057. Session
  1058. */
  1059. if (session) {
  1060. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1061. unsigned long numDownload = [downloadTasks count];
  1062. unsigned long numUpload = [uploadTasks count];
  1063. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  1064. }];
  1065. }
  1066. }
  1067. - (void)changeTask:(NSString *)fileID
  1068. {
  1069. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1070. if (!metadata) return;
  1071. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1072. if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"stopUpload"]) {
  1073. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1074. }
  1075. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadUpload"]) {
  1076. // V 1.8 if upload_session_wwan change in upload_session
  1077. if ([metadata.session isEqualToString:k_upload_session_wwan])
  1078. metadata.session = k_upload_session;
  1079. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1080. }
  1081. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadDownload"]) {
  1082. BOOL downloadData = NO, downloadPlist = NO;
  1083. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) downloadData = YES;
  1084. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) downloadPlist = YES;
  1085. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1086. [[CCNetworking sharedNetworking] downloadFile:fileID serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:nil];
  1087. });
  1088. }
  1089. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1090. // remove the file
  1091. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1092. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1093. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1094. }
  1095. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"cancelDownload"]) {
  1096. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1097. }
  1098. // remove ChangeTask (fileID) from the list
  1099. [_listChangeTask removeObjectForKey:fileID];
  1100. // delete progress
  1101. [_listProgressMetadata removeObjectForKey:fileID];
  1102. // Progress Task
  1103. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1104. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1105. // Refresh
  1106. if (_activeMain && [_listChangeTask count] == 0) {
  1107. [_activeMain reloadDatasource:serverUrl];
  1108. }
  1109. }
  1110. #pragma --------------------------------------------------------------------------------------------
  1111. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1112. #pragma --------------------------------------------------------------------------------------------
  1113. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1114. {
  1115. return YES;
  1116. }
  1117. // Method called from iOS system to send a file from other app.
  1118. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1119. {
  1120. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1121. NSLog(@"[LOG] the path is: %@", url.path);
  1122. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1123. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1124. if (self.activeAccount) {
  1125. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1126. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1127. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1128. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1129. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1130. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1131. });
  1132. }
  1133. // remove from InBox
  1134. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1135. return YES;
  1136. }
  1137. #pragma --------------------------------------------------------------------------------------------
  1138. #pragma mark ===== Crashlytics =====
  1139. #pragma --------------------------------------------------------------------------------------------
  1140. - (void) logUser
  1141. {
  1142. if (self.activeAccount.length > 0)
  1143. [CrashlyticsKit setUserName:self.activeAccount];
  1144. }
  1145. #pragma --------------------------------------------------------------------------------------------
  1146. #pragma mark ===== maintenance Mode =====
  1147. #pragma --------------------------------------------------------------------------------------------
  1148. - (void)maintenanceMode:(BOOL)mode
  1149. {
  1150. self.maintenanceMode = mode;
  1151. }
  1152. #pragma --------------------------------------------------------------------------------------------
  1153. #pragma mark ===== UPGRADE =====
  1154. #pragma --------------------------------------------------------------------------------------------
  1155. - (BOOL)upgrade
  1156. {
  1157. #ifdef DEBUG
  1158. //self.maintenanceMode = YES;
  1159. #endif
  1160. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1161. /* ---------------------- UPGRADE VERSION ----------------------- */
  1162. if (([actualVersion compare:@"2.17.3" options:NSNumericSearch] == NSOrderedAscending)) {
  1163. // Migrate Certificates Table From CoreData to Realm
  1164. NSArray *listCertificateLocation = [CCCoreData migrateCertificatesLocation];
  1165. for (NSString *certificateLocation in listCertificateLocation)
  1166. [[NCManageDatabase sharedInstance] addCertificates:certificateLocation];
  1167. }
  1168. if (([actualVersion compare:@"2.17.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1169. [self maintenanceMode:YES];
  1170. // Migrate Account Table From CoreData to Realm
  1171. NSArray *listAccount = [CCCoreData migrateAccount];
  1172. for (TableAccount *account in listAccount)
  1173. [[NCManageDatabase sharedInstance] addTableAccountFromCoredata:account];
  1174. // Most important is done
  1175. [CCUtility setVersionCryptoCloud];
  1176. // Directories + LocalFile
  1177. NSArray *listDirectories = [CCCoreData migrateDirectories];
  1178. for (TableDirectory *directory in listDirectories)
  1179. [[NCManageDatabase sharedInstance] addTableDirectoryFromCoredata:directory];
  1180. NSArray *listLocalFile = [CCCoreData migrateLocalFile];
  1181. for (TableLocalFile *localFile in listLocalFile)
  1182. [[NCManageDatabase sharedInstance] addTableLocalFileFromCoredata:localFile];
  1183. [self maintenanceMode:NO];
  1184. }
  1185. return YES;
  1186. }
  1187. @end