AppDelegate.m 56 KB

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