AppDelegate.m 56 KB

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