AppDelegate.m 65 KB

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