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 "CCOfflineFileFolder.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. // Application Initialized
  256. //
  257. - (void)applicationInitialized
  258. {
  259. // now
  260. dispatch_async(dispatch_get_main_queue(), ^{
  261. //NSLog(@"[LOG] Read Folder for change Rev");
  262. //[[NSNotificationCenter defaultCenter] postNotificationName:@"readFileSelfFolderRev" object:nil];
  263. });
  264. // 0.5 sec.
  265. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  266. //
  267. NSLog(@"[LOG] Request Server Information");
  268. //
  269. if (_activeMain)
  270. [_activeMain requestServerInformation];
  271. });
  272. // 1 sec.
  273. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  274. NSLog(@"[LOG] read file Offline");
  275. [[NSNotificationCenter defaultCenter] postNotificationName:@"readFileOffline" object:nil];
  276. NSLog(@"[LOG] read folder offline");
  277. [[CCOfflineFileFolder sharedOfflineFileFolder] readFolderOffline];
  278. });
  279. // 1.5 sec.
  280. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  281. NSLog(@"[LOG] Initialize Camera Upload");
  282. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  283. });
  284. // Initialize Camera Upload
  285. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  286. }
  287. #pragma --------------------------------------------------------------------------------------------
  288. #pragma mark ===== Verify Process 5 seconds =====
  289. #pragma --------------------------------------------------------------------------------------------
  290. - (void)verifyProcess
  291. {
  292. // BACKGROND & FOREGROUND
  293. /* Active/Disactive Graphics Animation Offline Folders */
  294. NSArray *records = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  295. NSMutableArray *directory = [[NSMutableArray alloc] init];
  296. for (TableDirectory *record in records)
  297. [directory addObject:record.serverUrl];
  298. if ([directory count] > 0)
  299. [[CCOfflineFileFolder sharedOfflineFileFolder] offlineFolderAnimationDirectory:directory callViewController:YES];
  300. // ONLY BACKGROUND
  301. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  302. } else {
  303. // ONLY FOREFROUND
  304. }
  305. }
  306. #pragma --------------------------------------------------------------------------------------------
  307. #pragma mark ===== Setting Active Account =====
  308. #pragma --------------------------------------------------------------------------------------------
  309. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword activeUID:(NSString *)activeUID activeAccessToken:(NSString *)activeAccessToken typeCloud:(NSString *)typeCloud
  310. {
  311. self.activeAccount = activeAccount;
  312. self.activeUrl = activeUrl;
  313. self.activeUser = activeUser;
  314. self.activePassword = activePassword;
  315. self.typeCloud = typeCloud;
  316. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  317. self.activeUID = activeUID;
  318. self.activeAccessToken = activeAccessToken;
  319. }
  320. #pragma --------------------------------------------------------------------------------------------
  321. #pragma mark ===== Push Notification =====
  322. #pragma --------------------------------------------------------------------------------------------
  323. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  324. {
  325. [application registerForRemoteNotifications];
  326. }
  327. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  328. {
  329. NSLog(@"DEVICE TOKEN = %@", deviceToken);
  330. }
  331. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  332. {
  333. NSLog(@"Error register remote notification %@", error);
  334. }
  335. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  336. UIApplicationState state = [application applicationState];
  337. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  338. NSLog(@"Receive Notification on Inactive or Background state");
  339. } else {
  340. NSLog(@"Receive Notification on Active state");
  341. }
  342. }
  343. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  344. {
  345. UIApplicationState state = [application applicationState];
  346. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  347. } else if (state == UIApplicationStateInactive) {
  348. // user tapped notification
  349. completionHandler(UIBackgroundFetchResultNewData);
  350. } else {
  351. // app is active
  352. completionHandler(UIBackgroundFetchResultNoData);
  353. }
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== Quick Actions - ShotcutItem =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)configDynamicShortcutItems
  359. {
  360. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  361. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  362. UIApplicationShortcutIcon *shortcutUploadClearIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadClear];
  363. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  364. UIApplicationShortcutIcon *shortcutIconTypeOffline = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadOffline];
  365. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  366. UIApplicationShortcutItem *shortcutOffline = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.offline", bundleId] localizedTitle:NSLocalizedString(@"_offline_", nil) localizedSubtitle:nil icon:shortcutIconTypeOffline userInfo:nil];
  367. UIApplicationShortcutItem *shortcutUploadClear = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadClear", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadClearIcon userInfo:nil];
  368. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  369. // add all items to an array
  370. NSArray *items = @[shortcutUploadEncrypted, shortcutUploadClear, shortcutPhotos, shortcutOffline];
  371. // add the array to our app
  372. [UIApplication sharedApplication].shortcutItems = items;
  373. }
  374. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  375. {
  376. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  377. completionHandler(handledShortCutItem);
  378. }
  379. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  380. {
  381. BOOL handled = NO;
  382. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  383. NSString *shortcutOffline = [NSString stringWithFormat:@"%@.offline", bundleId];
  384. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  385. NSString *shortcutUploadClear = [NSString stringWithFormat:@"%@.uploadClear", bundleId];
  386. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  387. if ([shortcutItem.type isEqualToString:shortcutUploadClear] && self.activeAccount) {
  388. dispatch_async(dispatch_get_main_queue(), ^{
  389. if (_activeMain) {
  390. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  391. if (splitViewController.isCollapsed) {
  392. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  393. for (UINavigationController *nvc in tbc.viewControllers) {
  394. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  395. [nvc popToRootViewControllerAnimated:NO];
  396. }
  397. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  398. } else {
  399. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  400. [nvcDetail popToRootViewControllerAnimated:NO];
  401. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  402. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  403. }
  404. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  405. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  406. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  407. });
  408. }
  409. });
  410. handled = YES;
  411. }
  412. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  413. dispatch_async(dispatch_get_main_queue(), ^{
  414. if (_activeMain) {
  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:TabBarApplicationIndexFile];
  423. } else {
  424. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  425. [nvcDetail popToRootViewControllerAnimated:NO];
  426. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  427. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  428. }
  429. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  430. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  431. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  432. });
  433. }
  434. });
  435. handled = YES;
  436. }
  437. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  438. dispatch_async(dispatch_get_main_queue(), ^{
  439. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  440. if (splitViewController.isCollapsed) {
  441. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  442. for (UINavigationController *nvc in tbc.viewControllers) {
  443. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  444. [nvc popToRootViewControllerAnimated:NO];
  445. }
  446. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  447. } else {
  448. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  449. [nvcDetail popToRootViewControllerAnimated:NO];
  450. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  451. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  452. }
  453. });
  454. handled = YES;
  455. }
  456. else if ([shortcutItem.type isEqualToString:shortcutOffline] && self.activeAccount) {
  457. dispatch_async(dispatch_get_main_queue(), ^{
  458. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  459. if (splitViewController.isCollapsed) {
  460. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  461. for (UINavigationController *nvc in tbc.viewControllers) {
  462. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  463. [nvc popToRootViewControllerAnimated:NO];
  464. if ([nvc.topViewController isKindOfClass:[CCOffline class]])
  465. [(CCOffline *)nvc.topViewController forcedSwitchOffline];
  466. }
  467. [tbc setSelectedIndex:TabBarApplicationIndexOffline];
  468. } else {
  469. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  470. [nvcDetail popToRootViewControllerAnimated:NO];
  471. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  472. UINavigationController *ncOffline = [tbc.viewControllers objectAtIndex:TabBarApplicationIndexOffline];
  473. if ([ncOffline.topViewController isKindOfClass:[CCOffline class]])
  474. [(CCOffline *)ncOffline.topViewController forcedSwitchOffline];
  475. [tbc setSelectedIndex:TabBarApplicationIndexOffline];
  476. }
  477. });
  478. handled = YES;
  479. }
  480. return handled;
  481. }
  482. #pragma --------------------------------------------------------------------------------------------
  483. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  484. #pragma --------------------------------------------------------------------------------------------
  485. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type
  486. {
  487. title = [NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]];
  488. dispatch_async(dispatch_get_main_queue(), ^{
  489. if (visible) {
  490. [TWMessageBarManager sharedInstance].styleSheet = self;
  491. [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  492. } else {
  493. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  494. }
  495. });
  496. }
  497. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  498. {
  499. UIColor *backgroundColor = nil;
  500. switch (type)
  501. {
  502. case TWMessageBarMessageTypeError:
  503. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  504. break;
  505. case TWMessageBarMessageTypeSuccess:
  506. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  507. break;
  508. case TWMessageBarMessageTypeInfo:
  509. backgroundColor = COLOR_BRAND_MESSAGE;
  510. break;
  511. default:
  512. break;
  513. }
  514. return backgroundColor;
  515. }
  516. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  517. {
  518. UIColor *strokeColor = nil;
  519. switch (type)
  520. {
  521. case TWMessageBarMessageTypeError:
  522. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  523. break;
  524. case TWMessageBarMessageTypeSuccess:
  525. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  526. break;
  527. case TWMessageBarMessageTypeInfo:
  528. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  529. break;
  530. default:
  531. break;
  532. }
  533. return strokeColor;
  534. }
  535. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  536. {
  537. UIImage *iconImage = nil;
  538. switch (type)
  539. {
  540. case TWMessageBarMessageTypeError:
  541. iconImage = [UIImage imageNamed:@"icon-error.png"];
  542. break;
  543. case TWMessageBarMessageTypeSuccess:
  544. iconImage = [UIImage imageNamed:@"icon-success.png"];
  545. break;
  546. case TWMessageBarMessageTypeInfo:
  547. iconImage = [UIImage imageNamed:@"icon-info.png"];
  548. break;
  549. default:
  550. break;
  551. }
  552. return iconImage;
  553. }
  554. #pragma --------------------------------------------------------------------------------------------
  555. #pragma mark ===== TabBarController =====
  556. #pragma --------------------------------------------------------------------------------------------
  557. - (void)createTabBarController
  558. {
  559. UITabBarItem *item;
  560. NSLayoutConstraint *constraint;
  561. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  562. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  563. [CCAspect aspectTabBar:tabBarController.tabBar hidden:NO];
  564. // File
  565. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFile];
  566. [item setTitle:NSLocalizedString(@"_home_", nil)];
  567. item.image = [UIImage imageNamed:image_tabBarFile];
  568. item.selectedImage = [UIImage imageNamed:image_tabBarFile];
  569. // Offline - Local
  570. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexOffline];
  571. if (app.isLocalStorage) {
  572. [item setTitle:NSLocalizedString(@"_local_storage_", nil)];
  573. item.image = [UIImage imageNamed:image_tabBarLocal];
  574. item.selectedImage = [UIImage imageNamed:image_tabBarLocal];
  575. } else {
  576. [item setTitle:NSLocalizedString(@"_offline_", nil)];
  577. item.image = [UIImage imageNamed:image_tabBarOffline];
  578. item.selectedImage = [UIImage imageNamed:image_tabBarOffline];
  579. }
  580. // Hide (PLUS)
  581. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexHide];
  582. item.title = nil;
  583. item.image = nil;
  584. item.enabled = false;
  585. // Photos
  586. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexPhotos];
  587. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  588. item.image = [UIImage imageNamed:image_tabBarPhotos];
  589. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  590. // Settings
  591. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexSettings];
  592. [item setTitle:NSLocalizedString(@"_settings_", nil)];
  593. item.image = [UIImage imageNamed:image_tabBarSettings];
  594. item.selectedImage = [UIImage imageNamed:image_tabBarSettings];
  595. // Plus Button
  596. UIImage *buttonImage = [UIImage imageNamed:@"Plus"];
  597. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  598. button.tag = 99;
  599. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  600. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  601. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  602. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  603. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  604. [tabBarController.view addSubview:button];
  605. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  606. [tabBarController.view addConstraint:constraint];
  607. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  608. [tabBarController.view addConstraint:constraint];
  609. }
  610. - (void)plusButtonVisibile:(BOOL)visible
  611. {
  612. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  613. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  614. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  615. if (buttonPlus) {
  616. if (visible) {
  617. buttonPlus.hidden = false;
  618. } else {
  619. buttonPlus.hidden = true;
  620. }
  621. }
  622. }
  623. - (void)handleTouchTabbarCenter:(id)sender
  624. {
  625. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] init];
  626. if ([CCUtility getCreateMenuEncrypted])
  627. [menuAdd createMenuEncryptedWithView:self.window.rootViewController.view];
  628. else
  629. [menuAdd createMenuPlainWithView:self.window.rootViewController.view];
  630. }
  631. - (void)updateApplicationIconBadgeNumber
  632. {
  633. // Core Data
  634. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  635. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  636. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  637. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  638. // netQueueDownload
  639. for (NSOperation *operation in [app.netQueueDownload operations]) {
  640. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  641. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  642. }
  643. // netQueueDownloadWWan
  644. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  645. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  646. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  647. }
  648. // netQueueUpload
  649. for (NSOperation *operation in [app.netQueueUpload operations]) {
  650. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  651. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  652. }
  653. // netQueueUploadWWan
  654. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  655. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  656. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  657. }
  658. // Total
  659. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  660. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  661. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  662. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  663. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  664. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  665. if (total > 0)
  666. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  667. else
  668. [tbItem setBadgeValue:nil];
  669. }
  670. }
  671. #pragma --------------------------------------------------------------------------------------------
  672. #pragma mark ===== Media Player Control =====
  673. #pragma --------------------------------------------------------------------------------------------
  674. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  675. {
  676. switch (event.subtype) {
  677. case UIEventSubtypeRemoteControlPlay:
  678. if (self.player.mediaPlayer) {
  679. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  680. if (self.player.mediaPlayer.nowPlayingItem.title)
  681. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  682. if (self.player.mediaPlayer.nowPlayingItem.artist)
  683. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  684. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  685. [self.player.mediaPlayer play];
  686. }
  687. break;
  688. case UIEventSubtypeRemoteControlPause:
  689. if (self.player.mediaPlayer) {
  690. [self.player.mediaPlayer pause];
  691. }
  692. break;
  693. case UIEventSubtypeRemoteControlNextTrack:
  694. // handle it break;
  695. case UIEventSubtypeRemoteControlPreviousTrack:
  696. // handle it break;
  697. default:
  698. break;
  699. }
  700. }
  701. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  702. {
  703. return YES;
  704. }
  705. #pragma --------------------------------------------------------------------------------------------
  706. #pragma mark ===== Manager Passcode =====
  707. #pragma --------------------------------------------------------------------------------------------
  708. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  709. {
  710. // fermiamo la data della sessione
  711. self.sessionePasscodeLock = nil;
  712. // se il block code è a zero esci con NON attivare la richiesta password
  713. if ([[CCUtility getBlockCode] length] == 0) return NO;
  714. // se non c'è attivo un account esci con NON attivare la richiesta password
  715. if ([self.activeAccount length] == 0) return NO;
  716. // se non c'è il passcode esci con NON attivare la richiesta password
  717. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  718. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  719. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  720. return YES;
  721. }
  722. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  723. {
  724. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  725. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  726. viewController.delegate = self;
  727. viewController.title = _brand_;
  728. viewController.fromType = CCBKPasscodeFromLockScreen;
  729. viewController.inputViewTitlePassword = YES;
  730. if ([CCUtility getSimplyBlockCode]) {
  731. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  732. viewController.passcodeInputView.maximumLength = 6;
  733. } else {
  734. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  735. viewController.passcodeInputView.maximumLength = 64;
  736. }
  737. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  738. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  739. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  740. return navigationController;
  741. }
  742. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  743. {
  744. [aViewController dismissViewControllerAnimated:YES completion:nil];
  745. // is a lock screen
  746. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  747. [aViewController dismissViewControllerAnimated:YES completion:nil];
  748. // start session Passcode Lock
  749. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  750. self.sessionePasscodeLock = [NSDate date];
  751. }
  752. }
  753. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  754. {
  755. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  756. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  757. //self.lockUntilDate = nil;
  758. //self.failedAttempts = 0;
  759. aResultHandler(YES);
  760. } else aResultHandler(NO);
  761. } else aResultHandler(YES);
  762. }
  763. #pragma --------------------------------------------------------------------------------------------
  764. #pragma mark ===== reachabilityChanged =====
  765. #pragma --------------------------------------------------------------------------------------------
  766. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  767. {
  768. if ([self.reachability isReachable]) {
  769. if (self.lastReachability == NO) {
  770. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  771. if (_activeMain)
  772. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  773. }
  774. NSLog(@"[LOG] Reachability Changed: Reachable");
  775. self.lastReachability = YES;
  776. } else {
  777. if (self.lastReachability == YES) {
  778. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  779. }
  780. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  781. self.lastReachability = NO;
  782. }
  783. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  784. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  785. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  786. }
  787. #pragma --------------------------------------------------------------------------------------------
  788. #pragma mark ===== Fetch =====
  789. #pragma --------------------------------------------------------------------------------------------
  790. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  791. {
  792. NSLog(@"[LOG] Start Fetch");
  793. // Verify new photo
  794. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  795. // after 20 sec verify Re
  796. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  797. [[CCNetworking sharedNetworking] automaticDownloadInError];
  798. [[CCNetworking sharedNetworking] automaticUploadInError];
  799. NSLog(@"[LOG] End Fetch 20 sec.");
  800. });
  801. // after 25 sec
  802. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  803. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  804. if ([records count] > 0) {
  805. completionHandler(UIBackgroundFetchResultNewData);
  806. } else {
  807. completionHandler(UIBackgroundFetchResultNoData);
  808. }
  809. NSLog(@"[LOG] End Fetch 25 sec.");
  810. });
  811. }
  812. #pragma --------------------------------------------------------------------------------------------
  813. #pragma mark ===== Operation Networking & Session =====
  814. #pragma --------------------------------------------------------------------------------------------
  815. //
  816. // Method called by the system when all the background task has end
  817. //
  818. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  819. {
  820. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  821. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  822. [[CCNetworking sharedNetworking] automaticDownloadInError];
  823. [[CCNetworking sharedNetworking] automaticUploadInError];
  824. self.backgroundSessionCompletionHandler = completionHandler;
  825. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  826. self.backgroundSessionCompletionHandler = nil;
  827. completionHandler();
  828. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  829. });
  830. }
  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