AppDelegate.m 58 KB

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