AppDelegate.m 57 KB

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