AppDelegate.m 65 KB

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