AppDelegate.m 58 KB

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