AppDelegate.m 65 KB

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