AppDelegate.m 66 KB

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