AppDelegate.m 64 KB

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