AppDelegate.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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 "OCFrameworkConstants.h"
  26. #import "AFURLSessionManager.h"
  27. #import "JBroken.h"
  28. #import "CCNetworking.h"
  29. #import "CCCoreData.h"
  30. #import "CCCrypto.h"
  31. #import "CCFavorite.h"
  32. #import "CCManageAsset.h"
  33. #import "CCGraphics.h"
  34. #import "CCPhotosCameraUpload.h"
  35. #import "CCSynchronization.h"
  36. #import "CCMain.h"
  37. #import "CCDetail.h"
  38. @interface AppDelegate ()
  39. {
  40. }
  41. @end
  42. @implementation AppDelegate
  43. + (void)initialize
  44. {
  45. [iRate sharedInstance].daysUntilPrompt = 10;
  46. [iRate sharedInstance].usesUntilPrompt = 10;
  47. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  48. //enable preview mode
  49. //[iRate sharedInstance].previewMode = YES;
  50. }
  51. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  52. {
  53. NSString *dir;
  54. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  55. NSLog(@"[LOG] Start program group %@", dirGroup);
  56. // create Directory local => Documents
  57. dir = [CCUtility getDirectoryLocal];
  58. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  59. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  60. // create Directory audio => Library, Application Support, audio
  61. dir = [CCUtility getDirectoryAudio];
  62. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  63. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  64. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  65. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  66. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  67. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  68. //[CCCoreData verifyVersionCoreData];
  69. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  70. #ifdef DEBUG
  71. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  72. #else
  73. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  74. #endif
  75. // Test Flight
  76. NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
  77. NSString *receiptURLString = [receiptURL path];
  78. _isRunningTestFlight = ([receiptURLString rangeOfString:@"sandboxReceipt"].location != NSNotFound);
  79. // Verify upgrade
  80. [self upgrade];
  81. // Set account, if no exists clear all
  82. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  83. if (recordAccount == nil) {
  84. // remove all the keys Chain
  85. [CCUtility deleteAllChainStore];
  86. // remove all the App group key
  87. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  88. } else {
  89. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password activeUID:recordAccount.uid activeAccessToken:recordAccount.token typeCloud:recordAccount.typeCloud];
  90. }
  91. // Operation Queue OC-DB Networking
  92. _netQueue = [[NSOperationQueue alloc] init];
  93. _netQueue.name = netQueueName;
  94. _netQueue.maxConcurrentOperationCount = maxConcurrentOperation;
  95. _netQueueDownload = [[NSOperationQueue alloc] init];
  96. _netQueueDownload.name = netQueueDownloadName;
  97. _netQueueDownload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  98. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  99. _netQueueDownloadWWan.name = netQueueDownloadWWanName;
  100. _netQueueDownloadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  101. _netQueueUpload = [[NSOperationQueue alloc] init];
  102. _netQueueUpload.name = netQueueUploadName;
  103. _netQueueUpload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  104. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  105. _netQueueUploadWWan.name = netQueueUploadWWanName;
  106. _netQueueUploadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  107. #ifdef CC
  108. // Inizialize DBSession for Dropbox
  109. NSString *appKey = appKeyCryptoCloud;
  110. NSString *appSecret = appSecretCryptoCloud;
  111. DBSession *dbSession = [[DBSession alloc] initWithAppKey:appKey appSecret:appSecret root:kDBRootDropbox];
  112. [DBSession setSharedSession:dbSession];
  113. #endif
  114. // Add notification change session
  115. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:networkingSessionNotification object:nil];
  116. // Inizializzazioni Share
  117. self.sharesID = [[NSMutableDictionary alloc] init];
  118. self.sharesLink = [[NSMutableDictionary alloc] init];
  119. self.sharesUserAndGroup = [[NSMutableDictionary alloc] init];
  120. // Verify Session in progress and Init date task
  121. self.sessionDateLastDownloadTasks = [NSDate date];
  122. self.sessionDateLastUploadTasks = [NSDate date];
  123. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  124. // Background Fetch
  125. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  126. // Init List
  127. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  128. self.listChangeTask = [[NSMutableDictionary alloc] init];
  129. self.listMainVC = [[NSMutableDictionary alloc] init];
  130. self.listFolderSynchronization = [[NSMutableArray alloc] init];
  131. // Player audio
  132. self.player = [LMMediaPlayerView sharedPlayerView];
  133. self.player.delegate = self;
  134. // ico Image Cache
  135. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  136. // remove tmp & cache
  137. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  138. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  139. for (NSString *file in tmpDirectory) {
  140. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  141. }
  142. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  143. });
  144. // setting Reachable in back
  145. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  146. self.reachability = [Reachability reachabilityForInternetConnection];
  147. self.lastReachability = [self.reachability isReachable];
  148. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  149. [self.reachability startNotifier];
  150. });
  151. //AV Session
  152. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  153. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  154. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  155. // permission request camera roll
  156. ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  157. [lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  158. //NSLog(@"[LOG] %li",(long)[group numberOfAssets]);
  159. } failureBlock:^(NSError *error) {
  160. if (error.code == ALAssetsLibraryAccessUserDeniedError) {
  161. NSLog(@"[LOG] user denied access, code: %li",(long)error.code);
  162. }else{
  163. NSLog(@"[LOG] Other error code: %li",(long)error.code);
  164. }
  165. }];
  166. // permission request notification
  167. if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  168. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
  169. [application registerUserNotificationSettings:settings];
  170. }
  171. // it is a device Jailbroken
  172. self.isDeviceJailbroken = isDeviceJailbroken();
  173. [self.window setTintColor:COLOR_BRAND];
  174. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  175. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  176. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  177. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  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. return YES;
  193. }
  194. //
  195. // L' applicazione è diventata attiva
  196. //
  197. - (void)applicationDidBecomeActive:(UIApplication *)application
  198. {
  199. }
  200. //
  201. // L' applicazione si dimetterà dallo stato di attivo
  202. //
  203. - (void)applicationWillResignActive:(UIApplication *)application
  204. {
  205. [self updateApplicationIconBadgeNumber];
  206. }
  207. //
  208. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  209. //
  210. - (void)applicationWillEnterForeground:(UIApplication *)application
  211. {
  212. // facciamo partire il timer per il controllo delle sessioni
  213. [self.timerVerifySessionInProgress invalidate];
  214. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  215. // refresh active Main
  216. if (_activeMain)
  217. [_activeMain getDataSourceWithReloadTableView];
  218. // Initializations
  219. [self applicationInitialized];
  220. }
  221. //
  222. // L' applicazione è entrata nello sfondo
  223. //
  224. - (void)applicationDidEnterBackground:(UIApplication *)application
  225. {
  226. NSLog(@"[LOG] Enter in Background");
  227. [[CCQuickActions quickActionsManager] closeAll];
  228. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  229. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  230. __block UIBackgroundTaskIdentifier background_task;
  231. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  232. //Clean up code. Tell the system that we are done.
  233. [application endBackgroundTask: background_task];
  234. background_task = UIBackgroundTaskInvalid;
  235. }];
  236. }
  237. }
  238. //
  239. // L'applicazione terminerà
  240. //
  241. - (void)applicationWillTerminate:(UIApplication *)application
  242. {
  243. [MagicalRecord cleanUp];
  244. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  245. }
  246. //
  247. // Method called by the system when all the background task has end
  248. //
  249. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  250. {
  251. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  252. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  253. [[CCNetworking sharedNetworking] automaticDownloadInError];
  254. [[CCNetworking sharedNetworking] automaticUploadInError];
  255. self.backgroundSessionCompletionHandler = completionHandler;
  256. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  257. self.backgroundSessionCompletionHandler = nil;
  258. completionHandler();
  259. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  260. });
  261. }
  262. //
  263. // Application Initialized
  264. //
  265. - (void)applicationInitialized
  266. {
  267. // now
  268. dispatch_async(dispatch_get_main_queue(), ^{
  269. //NSLog(@"[LOG] Read Folder for change Rev");
  270. //[[NSNotificationCenter defaultCenter] postNotificationName:@"readFileSelfFolderRev" object:nil];
  271. });
  272. // 0.5 sec.
  273. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  274. //
  275. NSLog(@"[LOG] Request Server Information");
  276. //
  277. if (_activeMain)
  278. [_activeMain requestServerInformation];
  279. });
  280. // 1 sec.
  281. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  282. NSLog(@"[LOG] Synchronize Favorites");
  283. [[NSNotificationCenter defaultCenter] postNotificationName:@"synchronizedFavorites" object:nil];
  284. NSLog(@"[LOG] Synchronize Folders");
  285. [[CCSynchronization sharedSynchronization] synchronizationFolders];
  286. });
  287. // 1.5 sec.
  288. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  289. NSLog(@"[LOG] Initialize Camera Upload");
  290. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  291. });
  292. // Initialize Camera Upload
  293. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  294. }
  295. #pragma --------------------------------------------------------------------------------------------
  296. #pragma mark ===== Verify Process =====
  297. #pragma --------------------------------------------------------------------------------------------
  298. - (void)verifyProcess
  299. {
  300. NSMutableArray *metadatasNet = [self verifyExistsInQueuesUploadSelector:selectorUploadAutomaticAll];
  301. NSLog(@"5 sec. %lu", [metadatasNet count]);
  302. }
  303. #pragma --------------------------------------------------------------------------------------------
  304. #pragma mark ===== Setting Active Account =====
  305. #pragma --------------------------------------------------------------------------------------------
  306. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword activeUID:(NSString *)activeUID activeAccessToken:(NSString *)activeAccessToken typeCloud:(NSString *)typeCloud
  307. {
  308. self.activeAccount = activeAccount;
  309. self.activeUrl = activeUrl;
  310. self.activeUser = activeUser;
  311. self.activePassword = activePassword;
  312. self.typeCloud = typeCloud;
  313. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  314. self.activeUID = activeUID;
  315. self.activeAccessToken = activeAccessToken;
  316. }
  317. #pragma --------------------------------------------------------------------------------------------
  318. #pragma mark ===== Quick Actions - ShotcutItem =====
  319. #pragma --------------------------------------------------------------------------------------------
  320. - (void)configDynamicShortcutItems
  321. {
  322. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  323. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  324. UIApplicationShortcutIcon *shortcutUploadClearIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadClear];
  325. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  326. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  327. UIApplicationShortcutItem *shortcutFavorite = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.favorite", bundleId] localizedTitle:NSLocalizedString(@"_favorites_", nil) localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeFavorite] userInfo:nil];
  328. UIApplicationShortcutItem *shortcutUploadClear = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadClear", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadClearIcon userInfo:nil];
  329. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  330. // add all items to an array
  331. NSArray *items = @[shortcutUploadEncrypted, shortcutUploadClear, shortcutPhotos, shortcutFavorite];
  332. // add the array to our app
  333. [UIApplication sharedApplication].shortcutItems = items;
  334. }
  335. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  336. {
  337. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  338. completionHandler(handledShortCutItem);
  339. }
  340. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  341. {
  342. BOOL handled = NO;
  343. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  344. NSString *shortcutFavorite = [NSString stringWithFormat:@"%@.favorite", bundleId];
  345. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  346. NSString *shortcutUploadClear = [NSString stringWithFormat:@"%@.uploadClear", bundleId];
  347. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  348. if ([shortcutItem.type isEqualToString:shortcutUploadClear] && self.activeAccount) {
  349. dispatch_async(dispatch_get_main_queue(), ^{
  350. if (_activeMain) {
  351. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  352. if (splitViewController.isCollapsed) {
  353. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  354. for (UINavigationController *nvc in tbc.viewControllers) {
  355. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  356. [nvc popToRootViewControllerAnimated:NO];
  357. }
  358. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  359. } else {
  360. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  361. [nvcDetail popToRootViewControllerAnimated:NO];
  362. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  363. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  364. }
  365. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  366. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  367. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  368. });
  369. }
  370. });
  371. handled = YES;
  372. }
  373. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  374. dispatch_async(dispatch_get_main_queue(), ^{
  375. if (_activeMain) {
  376. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  377. if (splitViewController.isCollapsed) {
  378. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  379. for (UINavigationController *nvc in tbc.viewControllers) {
  380. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  381. [nvc popToRootViewControllerAnimated:NO];
  382. }
  383. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  384. } else {
  385. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  386. [nvcDetail popToRootViewControllerAnimated:NO];
  387. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  388. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  389. }
  390. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  391. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  392. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  393. });
  394. }
  395. });
  396. handled = YES;
  397. }
  398. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  399. dispatch_async(dispatch_get_main_queue(), ^{
  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:TabBarApplicationIndexPhotos];
  408. } else {
  409. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  410. [nvcDetail popToRootViewControllerAnimated:NO];
  411. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  412. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  413. }
  414. });
  415. handled = YES;
  416. }
  417. else if ([shortcutItem.type isEqualToString:shortcutFavorite] && self.activeAccount) {
  418. dispatch_async(dispatch_get_main_queue(), ^{
  419. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  420. if (splitViewController.isCollapsed) {
  421. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  422. for (UINavigationController *nvc in tbc.viewControllers) {
  423. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  424. [nvc popToRootViewControllerAnimated:NO];
  425. if ([nvc.topViewController isKindOfClass:[CCFavorite class]])
  426. [(CCFavorite *)nvc.topViewController forcedSwitchFavorite];
  427. }
  428. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  429. } else {
  430. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  431. [nvcDetail popToRootViewControllerAnimated:NO];
  432. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  433. UINavigationController *ncFavorite = [tbc.viewControllers objectAtIndex:TabBarApplicationIndexFavorite];
  434. if ([ncFavorite.topViewController isKindOfClass:[CCFavorite class]])
  435. [(CCFavorite *)ncFavorite.topViewController forcedSwitchFavorite];
  436. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  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_BRAND_MESSAGE;
  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. - (void)updateApplicationIconBadgeNumber
  516. {
  517. // Core Data
  518. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  519. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  520. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  521. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  522. // Clear list folder in Synchronization
  523. [self.listFolderSynchronization removeAllObjects];
  524. // netQueueDownload
  525. for (NSOperation *operation in [app.netQueueDownload operations]) {
  526. /*** NEXTCLOUD OWNCLOUD ***/
  527. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  528. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  529. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorDownloadSynchronized])
  530. [_listFolderSynchronization addObject:((OCnetworking *)operation).metadataNet.serverUrl];
  531. }
  532. #ifdef CC
  533. /*** DROPBOX ***/
  534. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  535. if (((DBnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  536. if ([((DBnetworking *)operation).metadataNet.selector isEqualToString:selectorDownloadSynchronized])
  537. [_listFolderSynchronization addObject:((DBnetworking *)operation).metadataNet.serverUrl];
  538. }
  539. #endif
  540. }
  541. // netQueueDownloadWWan
  542. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  543. /*** NEXTCLOUD OWNCLOUD ***/
  544. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  545. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  546. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorDownloadSynchronized])
  547. [_listFolderSynchronization addObject:((OCnetworking *)operation).metadataNet.serverUrl];
  548. }
  549. #ifdef CC
  550. /*** DROPBOX ***/
  551. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  552. if (((DBnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  553. if ([((DBnetworking *)operation).metadataNet.selector isEqualToString:selectorDownloadSynchronized])
  554. [_listFolderSynchronization addObject:((DBnetworking *)operation).metadataNet.serverUrl];
  555. }
  556. #endif
  557. }
  558. // netQueueUpload
  559. for (NSOperation *operation in [app.netQueueUpload operations]) {
  560. /*** NEXTCLOUD OWNCLOUD ***/
  561. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  562. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  563. #ifdef CC
  564. /*** DROPBOX ***/
  565. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  566. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  567. #endif
  568. }
  569. // netQueueUploadWWan
  570. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  571. /*** NEXTCLOUD OWNCLOUD ***/
  572. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  573. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  574. #ifdef CC
  575. /*** DROPBOX ***/
  576. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  577. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  578. #endif
  579. }
  580. // Total
  581. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  582. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  583. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  584. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  585. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  586. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  587. if (total > 0)
  588. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  589. else
  590. [tbItem setBadgeValue:nil];
  591. }
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== Media Player Control =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  597. {
  598. switch (event.subtype) {
  599. case UIEventSubtypeRemoteControlPlay:
  600. if (self.player.mediaPlayer) {
  601. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  602. if (self.player.mediaPlayer.nowPlayingItem.title)
  603. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  604. if (self.player.mediaPlayer.nowPlayingItem.artist)
  605. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  606. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  607. [self.player.mediaPlayer play];
  608. }
  609. break;
  610. case UIEventSubtypeRemoteControlPause:
  611. if (self.player.mediaPlayer) {
  612. [self.player.mediaPlayer pause];
  613. }
  614. break;
  615. case UIEventSubtypeRemoteControlNextTrack:
  616. // handle it break;
  617. case UIEventSubtypeRemoteControlPreviousTrack:
  618. // handle it break;
  619. default:
  620. break;
  621. }
  622. }
  623. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  624. {
  625. return YES;
  626. }
  627. #pragma --------------------------------------------------------------------------------------------
  628. #pragma mark ===== Manager Passcode =====
  629. #pragma --------------------------------------------------------------------------------------------
  630. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  631. {
  632. // fermiamo la data della sessione
  633. self.sessionePasscodeLock = nil;
  634. // se il block code è a zero esci con NON attivare la richiesta password
  635. if ([[CCUtility getBlockCode] length] == 0) return NO;
  636. // se non c'è attivo un account esci con NON attivare la richiesta password
  637. if ([self.activeAccount length] == 0) return NO;
  638. // se non c'è il passcode esci con NON attivare la richiesta password
  639. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  640. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  641. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  642. return YES;
  643. }
  644. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  645. {
  646. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  647. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  648. viewController.delegate = self;
  649. viewController.title = _brand_;
  650. viewController.fromType = CCBKPasscodeFromLockScreen;
  651. viewController.inputViewTitlePassword = YES;
  652. if ([CCUtility getSimplyBlockCode]) {
  653. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  654. viewController.passcodeInputView.maximumLength = 6;
  655. } else {
  656. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  657. viewController.passcodeInputView.maximumLength = 64;
  658. }
  659. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  660. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  661. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  662. return navigationController;
  663. }
  664. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  665. {
  666. [aViewController dismissViewControllerAnimated:YES completion:nil];
  667. // is a lock screen
  668. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  669. [aViewController dismissViewControllerAnimated:YES completion:nil];
  670. // start session Passcode Lock
  671. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  672. self.sessionePasscodeLock = [NSDate date];
  673. }
  674. }
  675. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  676. {
  677. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  678. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  679. //self.lockUntilDate = nil;
  680. //self.failedAttempts = 0;
  681. aResultHandler(YES);
  682. } else aResultHandler(NO);
  683. } else aResultHandler(YES);
  684. }
  685. #pragma --------------------------------------------------------------------------------------------
  686. #pragma mark ===== reachabilityChanged =====
  687. #pragma --------------------------------------------------------------------------------------------
  688. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  689. {
  690. if ([self.reachability isReachable]) {
  691. if (self.lastReachability == NO) {
  692. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  693. if (_activeMain)
  694. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  695. }
  696. NSLog(@"[LOG] Reachability Changed: Reachable");
  697. self.lastReachability = YES;
  698. } else {
  699. if (self.lastReachability == YES) {
  700. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  701. }
  702. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  703. self.lastReachability = NO;
  704. }
  705. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  706. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  707. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  708. }
  709. #pragma --------------------------------------------------------------------------------------------
  710. #pragma mark ===== Fetch =====
  711. #pragma --------------------------------------------------------------------------------------------
  712. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  713. {
  714. NSLog(@"[LOG] Start Fetch");
  715. // Verify new photo
  716. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  717. // after 20 sec verify Re
  718. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  719. [[CCNetworking sharedNetworking] automaticDownloadInError];
  720. [[CCNetworking sharedNetworking] automaticUploadInError];
  721. NSLog(@"[LOG] End Fetch 20 sec.");
  722. });
  723. // after 25 sec
  724. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  725. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  726. if ([records count] > 0) {
  727. completionHandler(UIBackgroundFetchResultNewData);
  728. } else {
  729. completionHandler(UIBackgroundFetchResultNoData);
  730. }
  731. NSLog(@"[LOG] End Fetch 25 sec.");
  732. });
  733. }
  734. #pragma --------------------------------------------------------------------------------------------
  735. #pragma mark ===== Operation Networking & Session =====
  736. #pragma --------------------------------------------------------------------------------------------
  737. - (void)cancelAllOperations
  738. {
  739. [_netQueue cancelAllOperations];
  740. [_netQueueDownload cancelAllOperations];
  741. [_netQueueDownloadWWan cancelAllOperations];
  742. [_netQueueUpload cancelAllOperations];
  743. [_netQueueUploadWWan cancelAllOperations];
  744. [self performSelector:@selector(updateApplicationIconBadgeNumber) withObject:nil afterDelay:0.5];
  745. }
  746. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet oneByOne:(BOOL)oneByOne
  747. {
  748. id operation;
  749. BOOL activityIndicator = NO;
  750. // Activity Indicator
  751. if (netQueue == _netQueue)
  752. activityIndicator = YES;
  753. /*** NEXTCLOUD OWNCLOUD ***/
  754. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  755. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud oneByOne:oneByOne activityIndicator:activityIndicator];
  756. #ifdef CC
  757. /*** DROPBOX ***/
  758. if ([_typeCloud isEqualToString:typeCloudDropbox])
  759. operation = [[DBnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withActiveUID:_activeUID withActiveAccessToken:_activeAccessToken oneByOne:oneByOne activityIndicator:activityIndicator];
  760. #endif
  761. [operation setQueuePriority:metadataNet.priority];
  762. [netQueue addOperation:operation];
  763. }
  764. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  765. {
  766. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  767. /*** NEXTCLOUD OWNCLOUD ***/
  768. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  769. for (OCnetworking *operation in [self.netQueueUpload operations])
  770. if ([operation.metadataNet.selector isEqualToString:selector])
  771. [metadatasNet addObject:operation.metadataNet];
  772. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  773. if ([operation.metadataNet.selector isEqualToString:selector])
  774. [metadatasNet addObject:operation.metadataNet];
  775. }
  776. #ifdef CC
  777. /*** DROPBOX ***/
  778. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  779. for (DBnetworking *operation in [self.netQueueUpload operations])
  780. if ([operation.metadataNet.selector isEqualToString:selector])
  781. [metadatasNet addObject:operation.metadataNet];
  782. for (DBnetworking *operation in [self.netQueueUploadWWan operations])
  783. if ([operation.metadataNet.selector isEqualToString:selector])
  784. [metadatasNet addObject:operation.metadataNet];
  785. }
  786. #endif
  787. return metadatasNet;
  788. }
  789. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  790. {
  791. // Verify num error if selectorUploadAutomaticAll
  792. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  793. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  794. if (count >= 10) {
  795. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  796. return;
  797. }
  798. }
  799. // Add Network queue
  800. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector delete:YES context:nil];
  801. if (metadataNet) {
  802. NSOperationQueue *queue;
  803. if ([metadataNet.session containsString:@"wwan"])
  804. queue = app.netQueueUploadWWan;
  805. else
  806. queue = app.netQueueUpload;
  807. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet oneByOne:YES];
  808. }
  809. }
  810. - (void)verifyDownloadUploadInProgress
  811. {
  812. BOOL callVerifyDownload = NO;
  813. BOOL callVerifyUpload = NO;
  814. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  815. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  816. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  817. callVerifyDownload = YES;
  818. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  819. }
  820. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  821. callVerifyUpload = YES;
  822. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  823. }
  824. if (callVerifyDownload && callVerifyUpload) {
  825. NSLog(@"[LOG] Stop timer verify session");
  826. [self.timerVerifySessionInProgress invalidate];
  827. }
  828. }
  829. }
  830. // Notification change session
  831. - (void)sessionChanged:(NSNotification *)notification
  832. {
  833. NSURLSession *session;
  834. CCMetadata *metadata;
  835. NSURLSessionTask *task;
  836. for (id object in notification.object) {
  837. if ([object isKindOfClass:[NSURLSession class]])
  838. session = object;
  839. if ([object isKindOfClass:[CCMetadata class]])
  840. metadata = object;
  841. if ([object isKindOfClass:[NSURLSessionTask class]])
  842. task = object;
  843. }
  844. /*
  845. Task
  846. */
  847. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  848. app.sessionDateLastDownloadTasks = [NSDate date];
  849. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  850. app.sessionDateLastUploadTasks = [NSDate date];
  851. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  852. dispatch_async(dispatch_get_main_queue(), ^{
  853. [self changeTask:metadata];
  854. });
  855. /*
  856. Session
  857. */
  858. if (session) {
  859. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  860. unsigned long numDownload = [downloadTasks count];
  861. unsigned long numUpload = [uploadTasks count];
  862. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  863. }];
  864. }
  865. }
  866. - (void)changeTask:(CCMetadata *)metadata
  867. {
  868. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  869. // sessionTaskIdentifier on Stop
  870. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  871. }
  872. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  873. // V 1.8 if upload_session_wwan change in upload_session
  874. if ([metadata.session isEqualToString:upload_session_wwan])
  875. metadata.session = upload_session;
  876. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  877. }
  878. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  879. BOOL downloadData = NO, downloadPlist = NO;
  880. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  881. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  882. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  883. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  884. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  885. });
  886. }
  887. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  888. // remove the file
  889. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  890. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  891. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  892. }
  893. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  894. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  895. }
  896. // remove ChangeTask (fileID) from the list
  897. [_listChangeTask removeObjectForKey:metadata.fileID];
  898. // delete progress
  899. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  900. // Detail
  901. if (_activeDetail)
  902. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  903. // Refresh
  904. if (_activeMain && [_listChangeTask count] == 0)
  905. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  906. }
  907. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  908. {
  909. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  910. // Update icon badge number
  911. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  912. [self updateApplicationIconBadgeNumber];
  913. });
  914. }
  915. #pragma --------------------------------------------------------------------------------------------
  916. #pragma mark ===== Dropbox =====
  917. #pragma --------------------------------------------------------------------------------------------
  918. #ifdef CC
  919. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  920. {
  921. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  922. }
  923. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  924. {
  925. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  926. [CCCoreData deleteAccount:account];
  927. // new account
  928. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  929. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  930. if (tableAccount)
  931. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  932. NSString *uuid = [CCUtility getUUID];
  933. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  934. // update ManageAccount
  935. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  936. // Login correct
  937. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  938. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  939. }
  940. #endif
  941. #pragma --------------------------------------------------------------------------------------------
  942. #pragma mark ===== Open CCUploadFromOtherUpp =====
  943. #pragma --------------------------------------------------------------------------------------------
  944. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  945. {
  946. return YES;
  947. }
  948. // Method called from iOS system to send a file from other app.
  949. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  950. {
  951. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  952. NSLog(@"[LOG] the path is: %@", url.path);
  953. #ifdef CC
  954. /*************************************** DROPBOX *********************************/
  955. if ([[DBSession sharedSession] handleOpenURL:url]) {
  956. NSString *query = url.query;
  957. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  958. NSDictionary *urlData = [DBSession parseURLParams:query];
  959. NSString *uid = [urlData objectForKey:@"uid"];
  960. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  961. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  962. self.restClient.delegate = self;
  963. [self.restClient loadAccountInfo];
  964. }
  965. } else {
  966. // user cancelled the login
  967. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  968. }
  969. return YES;
  970. }
  971. /*********************************************************************************/
  972. #endif
  973. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  974. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  975. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  976. if (self.activeAccount && [passcode length]) {
  977. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  978. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  979. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  980. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  981. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  982. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  983. });
  984. }
  985. // remove from InBox
  986. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  987. return YES;
  988. }
  989. #pragma --------------------------------------------------------------------------------------------
  990. #pragma mark ===== UPGRADE =====
  991. #pragma --------------------------------------------------------------------------------------------
  992. - (void)upgrade
  993. {
  994. #ifdef DEBUG
  995. // [CCCoreData flushTableGPS];
  996. // [CCCoreData setGeoInformationLocalNull];
  997. #endif
  998. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  999. /* ---------------------- UPGRADE VERSION ----------------------- */
  1000. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1001. [CCCoreData flushTableDirectoryAccount:nil];
  1002. [CCCoreData flushTableLocalFileAccount:nil];
  1003. [CCCoreData flushTableMetadataAccount:nil];
  1004. }
  1005. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1006. [CCCoreData flushTableGPS];
  1007. [CCCoreData setGeoInformationLocalNull];
  1008. }
  1009. }
  1010. @end