AppDelegate.m 60 KB

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