AppDelegate.m 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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)startUpload
  796. {
  797. NSArray *metadatasNet = [CCCoreData getTableUploadFromAccount:self.activeAccount queueName:@"it.twsweb.cryptocloud.queueUploadCameraAllPhoto" numRecords:(maxConcurrentOperationUploadCameraAllPhoto - [_netQueueUploadCameraAllPhoto operationCount]) context:nil];
  798. }
  799. - (void)verifyDownloadUploadInProgress
  800. {
  801. BOOL callVerifyDownload = NO;
  802. BOOL callVerifyUpload = NO;
  803. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  804. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  805. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  806. callVerifyDownload = YES;
  807. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  808. }
  809. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  810. callVerifyUpload = YES;
  811. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  812. }
  813. if (callVerifyDownload && callVerifyUpload) {
  814. NSLog(@"[LOG] Stop timer verify session");
  815. [self.timerVerifySessionInProgress invalidate];
  816. }
  817. }
  818. }
  819. // Notification change session
  820. - (void)sessionChanged:(NSNotification *)notification
  821. {
  822. NSURLSession *session;
  823. CCMetadata *metadata;
  824. NSURLSessionTask *task;
  825. for (id object in notification.object) {
  826. if ([object isKindOfClass:[NSURLSession class]])
  827. session = object;
  828. if ([object isKindOfClass:[CCMetadata class]])
  829. metadata = object;
  830. if ([object isKindOfClass:[NSURLSessionTask class]])
  831. task = object;
  832. }
  833. /*
  834. Task
  835. */
  836. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  837. app.sessionDateLastDownloadTasks = [NSDate date];
  838. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  839. app.sessionDateLastUploadTasks = [NSDate date];
  840. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  841. dispatch_async(dispatch_get_main_queue(), ^{
  842. [self changeTask:metadata];
  843. });
  844. /*
  845. Session
  846. */
  847. if (session) {
  848. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  849. unsigned long numDownload = [downloadTasks count];
  850. unsigned long numUpload = [uploadTasks count];
  851. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  852. }];
  853. }
  854. }
  855. - (void)changeTask:(CCMetadata *)metadata
  856. {
  857. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  858. // sessionTaskIdentifier on Stop
  859. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  860. }
  861. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  862. // V 1.8 if upload_session_wwan change in upload_session
  863. if ([metadata.session isEqualToString:upload_session_wwan])
  864. metadata.session = upload_session;
  865. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  866. }
  867. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  868. BOOL downloadData = NO, downloadPlist = NO;
  869. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  870. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  871. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  872. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  873. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  874. });
  875. }
  876. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  877. // remove the file
  878. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  879. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  880. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  881. }
  882. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  883. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  884. }
  885. // remove ChangeTask (fileID) from the list
  886. [_listChangeTask removeObjectForKey:metadata.fileID];
  887. // delete progress
  888. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  889. // Detail
  890. if (_activeDetail)
  891. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  892. // Refresh
  893. if (_activeMain && [_listChangeTask count] == 0)
  894. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  895. }
  896. - (void)dropCameraUploadAllPhoto
  897. {
  898. [_netQueueUploadCameraAllPhoto cancelAllOperations];
  899. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '') AND ((sessionSelector == %@))", self.activeAccount, selectorUploadCameraAllPhoto]];
  900. [CCCoreData setCameraUploadFullPhotosActiveAccount:NO activeAccount:app.activeAccount];
  901. // Update icon badge number
  902. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  903. [self updateApplicationIconBadgeNumber];
  904. });
  905. }
  906. #pragma --------------------------------------------------------------------------------------------
  907. #pragma mark ===== Dropbox =====
  908. #pragma --------------------------------------------------------------------------------------------
  909. #ifdef CC
  910. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  911. {
  912. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  913. }
  914. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  915. {
  916. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  917. [CCCoreData deleteAccount:account];
  918. // new account
  919. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  920. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  921. if (tableAccount)
  922. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  923. NSString *uuid = [CCUtility getUUID];
  924. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  925. // update ManageAccount
  926. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  927. // Login correct
  928. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  929. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  930. }
  931. #endif
  932. #pragma --------------------------------------------------------------------------------------------
  933. #pragma mark ===== Open CCUploadFromOtherUpp =====
  934. #pragma --------------------------------------------------------------------------------------------
  935. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  936. {
  937. return YES;
  938. }
  939. // Method called from iOS system to send a file from other app.
  940. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  941. {
  942. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  943. NSLog(@"[LOG] the path is: %@", url.path);
  944. #ifdef CC
  945. /*************************************** DROPBOX *********************************/
  946. if ([[DBSession sharedSession] handleOpenURL:url]) {
  947. NSString *query = url.query;
  948. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  949. NSDictionary *urlData = [DBSession parseURLParams:query];
  950. NSString *uid = [urlData objectForKey:@"uid"];
  951. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  952. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  953. self.restClient.delegate = self;
  954. [self.restClient loadAccountInfo];
  955. }
  956. } else {
  957. // user cancelled the login
  958. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  959. }
  960. return YES;
  961. }
  962. /*********************************************************************************/
  963. #endif
  964. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  965. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  966. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  967. if (self.activeAccount && [passcode length]) {
  968. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  969. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  970. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  971. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  972. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  973. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  974. });
  975. }
  976. // remove from InBox
  977. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  978. return YES;
  979. }
  980. #pragma --------------------------------------------------------------------------------------------
  981. #pragma mark ===== UPGRADE =====
  982. #pragma --------------------------------------------------------------------------------------------
  983. - (void)upgrade
  984. {
  985. #ifdef DEBUG
  986. // [CCCoreData flushTableGPS];
  987. // [CCCoreData setGeoInformationLocalNull];
  988. #endif
  989. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  990. /* ---------------------- UPGRADE VERSION ----------------------- */
  991. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  992. [CCCoreData flushTableDirectoryAccount:nil];
  993. [CCCoreData flushTableLocalFileAccount:nil];
  994. [CCCoreData flushTableMetadataAccount:nil];
  995. }
  996. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  997. [CCCoreData flushTableGPS];
  998. [CCCoreData setGeoInformationLocalNull];
  999. }
  1000. }
  1001. @end