AppDelegate.m 66 KB

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