AppDelegate.m 57 KB

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