AppDelegate.m 56 KB

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