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