AppDelegate.m 56 KB

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