AppDelegate.m 56 KB

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