AppDelegate.m 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. //
  2. // AppDelegate.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import "iRate.h"
  25. #import "OCFrameworkConstants.h"
  26. #import "AFURLSessionManager.h"
  27. #import "JBroken.h"
  28. #import "CCNetworking.h"
  29. #import "CCCoreData.h"
  30. #import "CCCrypto.h"
  31. #import "CCFavorite.h"
  32. #import "CCManageAsset.h"
  33. #import "CCGraphics.h"
  34. #import "CCPhotosCameraUpload.h"
  35. #import "CCSynchronization.h"
  36. #import "CCMain.h"
  37. #import "CCDetail.h"
  38. @interface AppDelegate ()
  39. {
  40. }
  41. @end
  42. @implementation AppDelegate
  43. + (void)initialize
  44. {
  45. [iRate sharedInstance].daysUntilPrompt = 10;
  46. [iRate sharedInstance].usesUntilPrompt = 10;
  47. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  48. //enable preview mode
  49. //[iRate sharedInstance].previewMode = YES;
  50. }
  51. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  52. {
  53. NSString *dir;
  54. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  55. NSLog(@"[LOG] Start program group %@", dirGroup);
  56. // create Directory local => Documents
  57. dir = [CCUtility getDirectoryLocal];
  58. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  59. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  60. // create Directory audio => Library, Application Support, audio
  61. dir = [CCUtility getDirectoryAudio];
  62. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  63. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  64. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  65. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  66. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  67. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  68. //[CCCoreData verifyVersionCoreData];
  69. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  70. #ifdef DEBUG
  71. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  72. #else
  73. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  74. #endif
  75. // Verify upgrade
  76. [self upgrade];
  77. // Set account, if no exists clear all
  78. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  79. if (recordAccount == nil) {
  80. // remove all the keys Chain
  81. [CCUtility deleteAllChainStore];
  82. // remove all the App group key
  83. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  84. } else {
  85. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password activeUID:recordAccount.uid activeAccessToken:recordAccount.token typeCloud:recordAccount.typeCloud];
  86. }
  87. // Operation Queue OC-DB Networking
  88. _netQueue = [[NSOperationQueue alloc] init];
  89. _netQueue.name = netQueueName;
  90. _netQueue.maxConcurrentOperationCount = maxConcurrentOperation;
  91. _netQueueDownload = [[NSOperationQueue alloc] init];
  92. _netQueueDownload.name = netQueueDownloadName;
  93. _netQueueDownload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  94. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  95. _netQueueDownloadWWan.name = netQueueDownloadWWanName;
  96. _netQueueDownloadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  97. _netQueueUpload = [[NSOperationQueue alloc] init];
  98. _netQueueUpload.name = netQueueUploadName;
  99. _netQueueUpload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  100. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  101. _netQueueUploadWWan.name = netQueueUploadWWanName;
  102. _netQueueUploadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  103. #ifdef CC
  104. // Inizialize DBSession for Dropbox
  105. NSString *appKey = appKeyCryptoCloud;
  106. NSString *appSecret = appSecretCryptoCloud;
  107. DBSession *dbSession = [[DBSession alloc] initWithAppKey:appKey appSecret:appSecret root:kDBRootDropbox];
  108. [DBSession setSharedSession:dbSession];
  109. #endif
  110. // Add notification change session
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:networkingSessionNotification object:nil];
  112. // Inizializzazioni Share
  113. self.sharesID = [[NSMutableDictionary alloc] init];
  114. self.sharesLink = [[NSMutableDictionary alloc] init];
  115. self.sharesUserAndGroup = [[NSMutableDictionary alloc] init];
  116. // Verify Session in progress and Init date task
  117. self.sessionDateLastDownloadTasks = [NSDate date];
  118. self.sessionDateLastUploadTasks = [NSDate date];
  119. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  120. // Background Fetch
  121. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  122. // Init List
  123. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  124. self.listChangeTask = [[NSMutableDictionary alloc] init];
  125. self.listMainVC = [[NSMutableDictionary alloc] init];
  126. // Player audio
  127. self.player = [LMMediaPlayerView sharedPlayerView];
  128. self.player.delegate = self;
  129. // ico Image Cache
  130. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  131. // remove tmp & cache
  132. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  133. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  134. for (NSString *file in tmpDirectory) {
  135. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  136. }
  137. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  138. });
  139. // setting Reachable in back
  140. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  141. self.reachability = [Reachability reachabilityForInternetConnection];
  142. self.lastReachability = [self.reachability isReachable];
  143. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  144. [self.reachability startNotifier];
  145. });
  146. //AV Session
  147. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  148. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  149. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  150. // permission request camera roll
  151. ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  152. [lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  153. //NSLog(@"[LOG] %li",(long)[group numberOfAssets]);
  154. } failureBlock:^(NSError *error) {
  155. if (error.code == ALAssetsLibraryAccessUserDeniedError) {
  156. NSLog(@"[LOG] user denied access, code: %li",(long)error.code);
  157. }else{
  158. NSLog(@"[LOG] Other error code: %li",(long)error.code);
  159. }
  160. }];
  161. // permission request notification
  162. if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  163. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
  164. [application registerUserNotificationSettings:settings];
  165. }
  166. // it is a device Jailbroken
  167. self.isDeviceJailbroken = isDeviceJailbroken();
  168. [self.window setTintColor:COLOR_BRAND];
  169. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  170. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  171. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  172. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  173. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  174. // Settings TabBar
  175. [self createTabBarController];
  176. // passcode
  177. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  178. dispatch_async(dispatch_get_main_queue(), ^{
  179. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  180. });
  181. // Quick Actions
  182. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  183. [self configDynamicShortcutItems];
  184. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  185. if (shortcutItem)
  186. [self handleShortCutItem:shortcutItem];
  187. }
  188. // Start timer Verify Process
  189. self.timerVerifyProcess = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(verifyProcess) userInfo:nil repeats:YES];
  190. return YES;
  191. }
  192. //
  193. // L' applicazione è diventata attiva
  194. //
  195. - (void)applicationDidBecomeActive:(UIApplication *)application
  196. {
  197. // After 5 sec. for wait load app.activeMain start if exists in Table Automatic Upload + All
  198. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  199. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic] > 0)
  200. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  201. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomaticAll] > 0)
  202. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  203. });
  204. }
  205. //
  206. // L' applicazione si dimetterà dallo stato di attivo
  207. //
  208. - (void)applicationWillResignActive:(UIApplication *)application
  209. {
  210. [self updateApplicationIconBadgeNumber];
  211. }
  212. //
  213. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  214. //
  215. - (void)applicationWillEnterForeground:(UIApplication *)application
  216. {
  217. // facciamo partire il timer per il controllo delle sessioni
  218. [self.timerVerifySessionInProgress invalidate];
  219. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  220. // refresh active Main
  221. if (_activeMain)
  222. [_activeMain getDataSourceWithReloadTableView];
  223. // Initializations
  224. [self applicationInitialized];
  225. }
  226. //
  227. // L' applicazione è entrata nello sfondo
  228. //
  229. - (void)applicationDidEnterBackground:(UIApplication *)application
  230. {
  231. NSLog(@"[LOG] Enter in Background");
  232. [[CCQuickActions quickActionsManager] closeAll];
  233. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  234. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  235. __block UIBackgroundTaskIdentifier background_task;
  236. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  237. //Clean up code. Tell the system that we are done.
  238. [application endBackgroundTask: background_task];
  239. background_task = UIBackgroundTaskInvalid;
  240. }];
  241. }
  242. }
  243. //
  244. // L'applicazione terminerà
  245. //
  246. - (void)applicationWillTerminate:(UIApplication *)application
  247. {
  248. [MagicalRecord cleanUp];
  249. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  250. }
  251. //
  252. // Method called by the system when all the background task has end
  253. //
  254. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  255. {
  256. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  257. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  258. [[CCNetworking sharedNetworking] automaticDownloadInError];
  259. [[CCNetworking sharedNetworking] automaticUploadInError];
  260. self.backgroundSessionCompletionHandler = completionHandler;
  261. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  262. self.backgroundSessionCompletionHandler = nil;
  263. completionHandler();
  264. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  265. });
  266. }
  267. //
  268. // Application Initialized
  269. //
  270. - (void)applicationInitialized
  271. {
  272. // now
  273. dispatch_async(dispatch_get_main_queue(), ^{
  274. //NSLog(@"[LOG] Read Folder for change Rev");
  275. //[[NSNotificationCenter defaultCenter] postNotificationName:@"readFileSelfFolderRev" object:nil];
  276. });
  277. // 0.5 sec.
  278. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  279. //
  280. NSLog(@"[LOG] Request Server Information");
  281. //
  282. if (_activeMain)
  283. [_activeMain requestServerInformation];
  284. });
  285. // 1 sec.
  286. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  287. NSLog(@"[LOG] Synchronize Favorites");
  288. [[NSNotificationCenter defaultCenter] postNotificationName:@"synchronizedFavorites" object:nil];
  289. NSLog(@"[LOG] Synchronize Folders");
  290. [[CCSynchronization sharedSynchronization] synchronizationFolders];
  291. });
  292. // 1.5 sec.
  293. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  294. NSLog(@"[LOG] Initialize Camera Upload");
  295. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  296. });
  297. // Initialize Camera Upload
  298. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  299. }
  300. #pragma --------------------------------------------------------------------------------------------
  301. #pragma mark ===== Verify Process 5 seconds =====
  302. #pragma --------------------------------------------------------------------------------------------
  303. - (void)verifyProcess
  304. {
  305. // BACKGROND & FOREGROUND
  306. /* Active/Disactive Graphics Animation Synchronization Folders */
  307. NSArray *records = [CCCoreData getSynchronizedDirectoryActiveAccount:app.activeAccount];
  308. NSMutableArray *directory = [[NSMutableArray alloc] init];
  309. for (TableDirectory *record in records)
  310. [directory addObject:record.serverUrl];
  311. if ([directory count] > 0)
  312. [[CCSynchronization sharedSynchronization] synchronizationAnimationDirectory:directory callViewController:YES];
  313. // ONLY BACKGROUND
  314. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  315. } else {
  316. // ONLY FOREFROUND
  317. }
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ===== Setting Active Account =====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword activeUID:(NSString *)activeUID activeAccessToken:(NSString *)activeAccessToken typeCloud:(NSString *)typeCloud
  323. {
  324. self.activeAccount = activeAccount;
  325. self.activeUrl = activeUrl;
  326. self.activeUser = activeUser;
  327. self.activePassword = activePassword;
  328. self.typeCloud = typeCloud;
  329. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  330. self.activeUID = activeUID;
  331. self.activeAccessToken = activeAccessToken;
  332. }
  333. #pragma --------------------------------------------------------------------------------------------
  334. #pragma mark ===== Quick Actions - ShotcutItem =====
  335. #pragma --------------------------------------------------------------------------------------------
  336. - (void)configDynamicShortcutItems
  337. {
  338. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  339. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  340. UIApplicationShortcutIcon *shortcutUploadClearIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadClear];
  341. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  342. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  343. UIApplicationShortcutItem *shortcutFavorite = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.favorite", bundleId] localizedTitle:NSLocalizedString(@"_favorites_", nil) localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeFavorite] userInfo:nil];
  344. UIApplicationShortcutItem *shortcutUploadClear = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadClear", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadClearIcon userInfo:nil];
  345. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  346. // add all items to an array
  347. NSArray *items = @[shortcutUploadEncrypted, shortcutUploadClear, shortcutPhotos, shortcutFavorite];
  348. // add the array to our app
  349. [UIApplication sharedApplication].shortcutItems = items;
  350. }
  351. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  352. {
  353. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  354. completionHandler(handledShortCutItem);
  355. }
  356. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  357. {
  358. BOOL handled = NO;
  359. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  360. NSString *shortcutFavorite = [NSString stringWithFormat:@"%@.favorite", bundleId];
  361. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  362. NSString *shortcutUploadClear = [NSString stringWithFormat:@"%@.uploadClear", bundleId];
  363. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  364. if ([shortcutItem.type isEqualToString:shortcutUploadClear] && self.activeAccount) {
  365. dispatch_async(dispatch_get_main_queue(), ^{
  366. if (_activeMain) {
  367. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  368. if (splitViewController.isCollapsed) {
  369. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  370. for (UINavigationController *nvc in tbc.viewControllers) {
  371. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  372. [nvc popToRootViewControllerAnimated:NO];
  373. }
  374. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  375. } else {
  376. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  377. [nvcDetail popToRootViewControllerAnimated:NO];
  378. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  379. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  380. }
  381. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  382. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  383. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  384. });
  385. }
  386. });
  387. handled = YES;
  388. }
  389. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. if (_activeMain) {
  392. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  393. if (splitViewController.isCollapsed) {
  394. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  395. for (UINavigationController *nvc in tbc.viewControllers) {
  396. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  397. [nvc popToRootViewControllerAnimated:NO];
  398. }
  399. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  400. } else {
  401. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  402. [nvcDetail popToRootViewControllerAnimated:NO];
  403. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  404. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  405. }
  406. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  407. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  408. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  409. });
  410. }
  411. });
  412. handled = YES;
  413. }
  414. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  415. dispatch_async(dispatch_get_main_queue(), ^{
  416. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  417. if (splitViewController.isCollapsed) {
  418. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  419. for (UINavigationController *nvc in tbc.viewControllers) {
  420. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  421. [nvc popToRootViewControllerAnimated:NO];
  422. }
  423. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  424. } else {
  425. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  426. [nvcDetail popToRootViewControllerAnimated:NO];
  427. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  428. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  429. }
  430. });
  431. handled = YES;
  432. }
  433. else if ([shortcutItem.type isEqualToString:shortcutFavorite] && self.activeAccount) {
  434. dispatch_async(dispatch_get_main_queue(), ^{
  435. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  436. if (splitViewController.isCollapsed) {
  437. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  438. for (UINavigationController *nvc in tbc.viewControllers) {
  439. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  440. [nvc popToRootViewControllerAnimated:NO];
  441. if ([nvc.topViewController isKindOfClass:[CCFavorite class]])
  442. [(CCFavorite *)nvc.topViewController forcedSwitchFavorite];
  443. }
  444. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  445. } else {
  446. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  447. [nvcDetail popToRootViewControllerAnimated:NO];
  448. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  449. UINavigationController *ncFavorite = [tbc.viewControllers objectAtIndex:TabBarApplicationIndexFavorite];
  450. if ([ncFavorite.topViewController isKindOfClass:[CCFavorite class]])
  451. [(CCFavorite *)ncFavorite.topViewController forcedSwitchFavorite];
  452. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  453. }
  454. });
  455. handled = YES;
  456. }
  457. return handled;
  458. }
  459. #pragma --------------------------------------------------------------------------------------------
  460. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  461. #pragma --------------------------------------------------------------------------------------------
  462. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type
  463. {
  464. title = [NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]];
  465. dispatch_async(dispatch_get_main_queue(), ^{
  466. if (visible) {
  467. [TWMessageBarManager sharedInstance].styleSheet = self;
  468. [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  469. } else {
  470. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  471. }
  472. });
  473. }
  474. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  475. {
  476. UIColor *backgroundColor = nil;
  477. switch (type)
  478. {
  479. case TWMessageBarMessageTypeError:
  480. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  481. break;
  482. case TWMessageBarMessageTypeSuccess:
  483. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  484. break;
  485. case TWMessageBarMessageTypeInfo:
  486. backgroundColor = COLOR_BRAND_MESSAGE;
  487. break;
  488. default:
  489. break;
  490. }
  491. return backgroundColor;
  492. }
  493. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  494. {
  495. UIColor *strokeColor = nil;
  496. switch (type)
  497. {
  498. case TWMessageBarMessageTypeError:
  499. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  500. break;
  501. case TWMessageBarMessageTypeSuccess:
  502. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  503. break;
  504. case TWMessageBarMessageTypeInfo:
  505. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  506. break;
  507. default:
  508. break;
  509. }
  510. return strokeColor;
  511. }
  512. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  513. {
  514. UIImage *iconImage = nil;
  515. switch (type)
  516. {
  517. case TWMessageBarMessageTypeError:
  518. iconImage = [UIImage imageNamed:@"icon-error.png"];
  519. break;
  520. case TWMessageBarMessageTypeSuccess:
  521. iconImage = [UIImage imageNamed:@"icon-success.png"];
  522. break;
  523. case TWMessageBarMessageTypeInfo:
  524. iconImage = [UIImage imageNamed:@"icon-info.png"];
  525. break;
  526. default:
  527. break;
  528. }
  529. return iconImage;
  530. }
  531. #pragma --------------------------------------------------------------------------------------------
  532. #pragma mark ===== TabBarController =====
  533. #pragma --------------------------------------------------------------------------------------------
  534. - (void)createTabBarController
  535. {
  536. UITabBarItem *item;
  537. NSLayoutConstraint *constraint;
  538. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  539. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  540. [CCAspect aspectTabBar:tabBarController.tabBar hidden:NO];
  541. // File
  542. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFile];
  543. [item setTitle:NSLocalizedString(@"_home_", nil)];
  544. item.image = [UIImage imageNamed:image_tabBarFile];
  545. item.selectedImage = [UIImage imageNamed:image_tabBarFile];
  546. // Favorite - Local
  547. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFavorite];
  548. if (app.isLocalStorage) {
  549. [item setTitle:NSLocalizedString(@"_local_storage_", nil)];
  550. item.image = [UIImage imageNamed:image_tabBarLocal];
  551. item.selectedImage = [UIImage imageNamed:image_tabBarLocal];
  552. } else {
  553. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  554. item.image = [UIImage imageNamed:image_tabBarFavorite];
  555. item.selectedImage = [UIImage imageNamed:image_tabBarFavorite];
  556. }
  557. // Hide (PLUS)
  558. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexHide];
  559. item.title = nil;
  560. item.image = nil;
  561. item.enabled = false;
  562. // Photos
  563. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexPhotos];
  564. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  565. item.image = [UIImage imageNamed:image_tabBarPhotos];
  566. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  567. // Settings
  568. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexSettings];
  569. [item setTitle:NSLocalizedString(@"_settings_", nil)];
  570. item.image = [UIImage imageNamed:image_tabBarSettings];
  571. item.selectedImage = [UIImage imageNamed:image_tabBarSettings];
  572. // Plus Button
  573. UIImage *buttonImage = [UIImage imageNamed:@"Plus"];
  574. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  575. button.tag = 99;
  576. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  577. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  578. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  579. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  580. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  581. [tabBarController.view addSubview:button];
  582. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  583. [tabBarController.view addConstraint:constraint];
  584. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  585. [tabBarController.view addConstraint:constraint];
  586. }
  587. - (void)plusButtonVisibile:(BOOL)visible
  588. {
  589. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  590. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  591. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  592. if (buttonPlus) {
  593. if (visible) {
  594. buttonPlus.hidden = false;
  595. } else {
  596. buttonPlus.hidden = true;
  597. }
  598. }
  599. }
  600. - (void)handleTouchTabbarCenter:(id)sender
  601. {
  602. if (_activeMain)
  603. [_activeMain addActionTable];
  604. /*
  605. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.window.rootViewController.view title:nil];
  606. [actionSheet addButtonWithTitle:NSLocalizedString(@"Info", nil)
  607. image:[UIImage imageNamed:@"passcode"]
  608. type:AHKActionSheetButtonTypeDefault
  609. handler:^(AHKActionSheet *as) {
  610. if (_activeMain)
  611. [_activeMain returnCreate:returnCreateFolderPlain];
  612. }];
  613. [actionSheet addButtonWithTitle:NSLocalizedString(@"Add to Favorites", nil)
  614. image:[UIImage imageNamed:@"password"]
  615. type:AHKActionSheetButtonTypeDefault
  616. handler:^(AHKActionSheet *as) {
  617. if (_activeMain)
  618. [_activeMain returnCreate:returnCreateFotoVideoPlain];
  619. }];
  620. [actionSheet show];
  621. */
  622. }
  623. - (void)updateApplicationIconBadgeNumber
  624. {
  625. // Core Data
  626. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  627. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  628. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  629. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  630. // netQueueDownload
  631. for (NSOperation *operation in [app.netQueueDownload operations]) {
  632. /*** NEXTCLOUD OWNCLOUD ***/
  633. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  634. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  635. #ifdef CC
  636. /*** DROPBOX ***/
  637. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  638. if (((DBnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  639. #endif
  640. }
  641. // netQueueDownloadWWan
  642. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  643. /*** NEXTCLOUD OWNCLOUD ***/
  644. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  645. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  646. #ifdef CC
  647. /*** DROPBOX ***/
  648. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  649. if (((DBnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  650. #endif
  651. }
  652. // netQueueUpload
  653. for (NSOperation *operation in [app.netQueueUpload operations]) {
  654. /*** NEXTCLOUD OWNCLOUD ***/
  655. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  656. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  657. #ifdef CC
  658. /*** DROPBOX ***/
  659. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  660. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  661. #endif
  662. }
  663. // netQueueUploadWWan
  664. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  665. /*** NEXTCLOUD OWNCLOUD ***/
  666. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  667. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  668. #ifdef CC
  669. /*** DROPBOX ***/
  670. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  671. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  672. #endif
  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. /*** NEXTCLOUD OWNCLOUD ***/
  848. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  849. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud activityIndicator:activityIndicator];
  850. #ifdef CC
  851. /*** DROPBOX ***/
  852. if ([_typeCloud isEqualToString:typeCloudDropbox])
  853. operation = [[DBnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withActiveUID:_activeUID withActiveAccessToken:_activeAccessToken activityIndicator:activityIndicator];
  854. #endif
  855. [operation setQueuePriority:metadataNet.priority];
  856. [netQueue addOperation:operation];
  857. }
  858. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  859. {
  860. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  861. /*** NEXTCLOUD OWNCLOUD ***/
  862. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  863. for (OCnetworking *operation in [self.netQueueDownload operations])
  864. if ([operation.metadataNet.selector isEqualToString:selector])
  865. [metadatasNet addObject:[operation.metadataNet copy]];
  866. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  867. if ([operation.metadataNet.selector isEqualToString:selector])
  868. [metadatasNet addObject:[operation.metadataNet copy]];
  869. }
  870. #ifdef CC
  871. /*** DROPBOX ***/
  872. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  873. for (DBnetworking *operation in [self.netQueueDownload operations])
  874. if ([operation.metadataNet.selector isEqualToString:selector])
  875. [metadatasNet addObject:operation.metadataNet];
  876. for (DBnetworking *operation in [self.netQueueDownloadWWan operations])
  877. if ([operation.metadataNet.selector isEqualToString:selector])
  878. [metadatasNet addObject:operation.metadataNet];
  879. }
  880. #endif
  881. return metadatasNet;
  882. }
  883. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  884. {
  885. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  886. /*** NEXTCLOUD OWNCLOUD ***/
  887. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  888. for (OCnetworking *operation in [self.netQueueUpload operations])
  889. if ([operation.metadataNet.selector isEqualToString:selector])
  890. [metadatasNet addObject:[operation.metadataNet copy]];
  891. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  892. if ([operation.metadataNet.selector isEqualToString:selector])
  893. [metadatasNet addObject:[operation.metadataNet copy]];
  894. }
  895. #ifdef CC
  896. /*** DROPBOX ***/
  897. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  898. for (DBnetworking *operation in [self.netQueueUpload operations])
  899. if ([operation.metadataNet.selector isEqualToString:selector])
  900. [metadatasNet addObject:operation.metadataNet];
  901. for (DBnetworking *operation in [self.netQueueUploadWWan operations])
  902. if ([operation.metadataNet.selector isEqualToString:selector])
  903. [metadatasNet addObject:operation.metadataNet];
  904. }
  905. #endif
  906. return metadatasNet;
  907. }
  908. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  909. {
  910. // Only one
  911. if ([[self verifyExistsInQueuesUploadSelector:selector] count] > 1)
  912. return;
  913. // Verify num error if selectorUploadAutomaticAll
  914. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  915. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  916. #ifdef DEBUG
  917. NSArray *records = [[NSArray alloc] init];
  918. records = [TableMetadata MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  919. #endif
  920. if (count >= 10) {
  921. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  922. return;
  923. }
  924. }
  925. // Add Network queue
  926. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector context:nil];
  927. if (metadataNet) {
  928. NSOperationQueue *queue;
  929. if ([metadataNet.session containsString:@"wwan"])
  930. queue = app.netQueueUploadWWan;
  931. else
  932. queue = app.netQueueUpload;
  933. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet];
  934. }
  935. }
  936. - (void)verifyDownloadUploadInProgress
  937. {
  938. BOOL callVerifyDownload = NO;
  939. BOOL callVerifyUpload = NO;
  940. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  941. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  942. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  943. callVerifyDownload = YES;
  944. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  945. }
  946. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  947. callVerifyUpload = YES;
  948. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  949. }
  950. if (callVerifyDownload && callVerifyUpload) {
  951. NSLog(@"[LOG] Stop timer verify session");
  952. [self.timerVerifySessionInProgress invalidate];
  953. }
  954. }
  955. }
  956. // Notification change session
  957. - (void)sessionChanged:(NSNotification *)notification
  958. {
  959. NSURLSession *session;
  960. CCMetadata *metadata;
  961. NSURLSessionTask *task;
  962. for (id object in notification.object) {
  963. if ([object isKindOfClass:[NSURLSession class]])
  964. session = object;
  965. if ([object isKindOfClass:[CCMetadata class]])
  966. metadata = object;
  967. if ([object isKindOfClass:[NSURLSessionTask class]])
  968. task = object;
  969. }
  970. /*
  971. Task
  972. */
  973. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  974. app.sessionDateLastDownloadTasks = [NSDate date];
  975. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  976. app.sessionDateLastUploadTasks = [NSDate date];
  977. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  978. dispatch_async(dispatch_get_main_queue(), ^{
  979. [self changeTask:metadata];
  980. });
  981. /*
  982. Session
  983. */
  984. if (session) {
  985. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  986. unsigned long numDownload = [downloadTasks count];
  987. unsigned long numUpload = [uploadTasks count];
  988. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  989. }];
  990. }
  991. }
  992. - (void)changeTask:(CCMetadata *)metadata
  993. {
  994. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  995. // sessionTaskIdentifier on Stop
  996. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  997. }
  998. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  999. // V 1.8 if upload_session_wwan change in upload_session
  1000. if ([metadata.session isEqualToString:upload_session_wwan])
  1001. metadata.session = upload_session;
  1002. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  1003. }
  1004. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  1005. BOOL downloadData = NO, downloadPlist = NO;
  1006. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  1007. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  1008. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1009. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1010. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  1011. });
  1012. }
  1013. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1014. // remove the file
  1015. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  1016. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  1017. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  1018. }
  1019. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  1020. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1021. }
  1022. // remove ChangeTask (fileID) from the list
  1023. [_listChangeTask removeObjectForKey:metadata.fileID];
  1024. // delete progress
  1025. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  1026. // Detail
  1027. if (_activeDetail)
  1028. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  1029. // Refresh
  1030. if (_activeMain && [_listChangeTask count] == 0)
  1031. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  1032. }
  1033. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  1034. {
  1035. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  1036. // Update icon badge number
  1037. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1038. [self updateApplicationIconBadgeNumber];
  1039. });
  1040. }
  1041. #pragma --------------------------------------------------------------------------------------------
  1042. #pragma mark ===== Dropbox =====
  1043. #pragma --------------------------------------------------------------------------------------------
  1044. #ifdef CC
  1045. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  1046. {
  1047. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1048. }
  1049. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  1050. {
  1051. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  1052. [CCCoreData deleteAccount:account];
  1053. // new account
  1054. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  1055. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  1056. if (tableAccount)
  1057. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  1058. NSString *uuid = [CCUtility getUUID];
  1059. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  1060. // update ManageAccount
  1061. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  1062. // Login correct
  1063. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  1064. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  1065. }
  1066. #endif
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1071. {
  1072. return YES;
  1073. }
  1074. // Method called from iOS system to send a file from other app.
  1075. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1076. {
  1077. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1078. NSLog(@"[LOG] the path is: %@", url.path);
  1079. #ifdef CC
  1080. /*************************************** DROPBOX *********************************/
  1081. if ([[DBSession sharedSession] handleOpenURL:url]) {
  1082. NSString *query = url.query;
  1083. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  1084. NSDictionary *urlData = [DBSession parseURLParams:query];
  1085. NSString *uid = [urlData objectForKey:@"uid"];
  1086. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  1087. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  1088. self.restClient.delegate = self;
  1089. [self.restClient loadAccountInfo];
  1090. }
  1091. } else {
  1092. // user cancelled the login
  1093. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1094. }
  1095. return YES;
  1096. }
  1097. /*********************************************************************************/
  1098. #endif
  1099. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1100. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1101. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  1102. if (self.activeAccount && [passcode length]) {
  1103. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1104. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1105. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1106. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1107. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1108. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1109. });
  1110. }
  1111. // remove from InBox
  1112. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1113. return YES;
  1114. }
  1115. #pragma --------------------------------------------------------------------------------------------
  1116. #pragma mark ===== UPGRADE =====
  1117. #pragma --------------------------------------------------------------------------------------------
  1118. - (void)upgrade
  1119. {
  1120. #ifdef DEBUG
  1121. // [CCCoreData flushTableGPS];
  1122. // [CCCoreData setGeoInformationLocalNull];
  1123. #endif
  1124. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1125. /* ---------------------- UPGRADE VERSION ----------------------- */
  1126. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1127. [CCCoreData flushTableDirectoryAccount:nil];
  1128. [CCCoreData flushTableLocalFileAccount:nil];
  1129. [CCCoreData flushTableMetadataAccount:nil];
  1130. }
  1131. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1132. [CCCoreData flushTableGPS];
  1133. [CCCoreData setGeoInformationLocalNull];
  1134. }
  1135. }
  1136. @end