AppDelegate.m 64 KB

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