AppDelegate.m 56 KB

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