AppDelegate.m 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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. [self plusButton:true];
  177. // passcode
  178. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  179. dispatch_async(dispatch_get_main_queue(), ^{
  180. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  181. });
  182. // Quick Actions
  183. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  184. [self configDynamicShortcutItems];
  185. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  186. if (shortcutItem)
  187. [self handleShortCutItem:shortcutItem];
  188. }
  189. // Start timer Verify Process
  190. self.timerVerifyProcess = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(verifyProcess) userInfo:nil repeats:YES];
  191. return YES;
  192. }
  193. //
  194. // L' applicazione è diventata attiva
  195. //
  196. - (void)applicationDidBecomeActive:(UIApplication *)application
  197. {
  198. // After 5 sec. for wait load app.activeMain start if exists in Table Automatic Upload + All
  199. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  200. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomatic] > 0)
  201. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  202. if ([CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:selectorUploadAutomaticAll] > 0)
  203. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  204. });
  205. }
  206. //
  207. // L' applicazione si dimetterà dallo stato di attivo
  208. //
  209. - (void)applicationWillResignActive:(UIApplication *)application
  210. {
  211. [self updateApplicationIconBadgeNumber];
  212. }
  213. //
  214. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  215. //
  216. - (void)applicationWillEnterForeground:(UIApplication *)application
  217. {
  218. // facciamo partire il timer per il controllo delle sessioni
  219. [self.timerVerifySessionInProgress invalidate];
  220. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  221. // refresh active Main
  222. if (_activeMain)
  223. [_activeMain getDataSourceWithReloadTableView];
  224. // Initializations
  225. [self applicationInitialized];
  226. }
  227. //
  228. // L' applicazione è entrata nello sfondo
  229. //
  230. - (void)applicationDidEnterBackground:(UIApplication *)application
  231. {
  232. NSLog(@"[LOG] Enter in Background");
  233. [[CCQuickActions quickActionsManager] closeAll];
  234. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  235. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  236. __block UIBackgroundTaskIdentifier background_task;
  237. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  238. //Clean up code. Tell the system that we are done.
  239. [application endBackgroundTask: background_task];
  240. background_task = UIBackgroundTaskInvalid;
  241. }];
  242. }
  243. }
  244. //
  245. // L'applicazione terminerà
  246. //
  247. - (void)applicationWillTerminate:(UIApplication *)application
  248. {
  249. [MagicalRecord cleanUp];
  250. NSLog(@"[LOG] bye bye, Crypto Cloud !");
  251. }
  252. //
  253. // Method called by the system when all the background task has end
  254. //
  255. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
  256. {
  257. NSLog(@"[LOG] Start completition handler from background - identifier : %@", identifier);
  258. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  259. [[CCNetworking sharedNetworking] automaticDownloadInError];
  260. [[CCNetworking sharedNetworking] automaticUploadInError];
  261. self.backgroundSessionCompletionHandler = completionHandler;
  262. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  263. self.backgroundSessionCompletionHandler = nil;
  264. completionHandler();
  265. NSLog(@"[LOG] End 25 sec. completition handler - identifier : %@", identifier);
  266. });
  267. }
  268. //
  269. // Application Initialized
  270. //
  271. - (void)applicationInitialized
  272. {
  273. // now
  274. dispatch_async(dispatch_get_main_queue(), ^{
  275. //NSLog(@"[LOG] Read Folder for change Rev");
  276. //[[NSNotificationCenter defaultCenter] postNotificationName:@"readFileSelfFolderRev" object:nil];
  277. });
  278. // 0.5 sec.
  279. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  280. //
  281. NSLog(@"[LOG] Request Server Information");
  282. //
  283. if (_activeMain)
  284. [_activeMain requestServerInformation];
  285. });
  286. // 1 sec.
  287. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  288. NSLog(@"[LOG] Synchronize Favorites");
  289. [[NSNotificationCenter defaultCenter] postNotificationName:@"synchronizedFavorites" object:nil];
  290. NSLog(@"[LOG] Synchronize Folders");
  291. [[CCSynchronization sharedSynchronization] synchronizationFolders];
  292. });
  293. // 1.5 sec.
  294. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  295. NSLog(@"[LOG] Initialize Camera Upload");
  296. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  297. });
  298. // Initialize Camera Upload
  299. //[[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:@{@"afterDelay": @(2)}];
  300. }
  301. #pragma --------------------------------------------------------------------------------------------
  302. #pragma mark ===== Verify Process 5 seconds =====
  303. #pragma --------------------------------------------------------------------------------------------
  304. - (void)verifyProcess
  305. {
  306. // BACKGROND & FOREGROUND
  307. /* Active/Disactive Graphics Animation Synchronization Folders */
  308. NSArray *records = [CCCoreData getSynchronizedDirectoryActiveAccount:app.activeAccount];
  309. NSMutableArray *directory = [[NSMutableArray alloc] init];
  310. for (TableDirectory *record in records)
  311. [directory addObject:record.serverUrl];
  312. if ([directory count] > 0)
  313. [[CCSynchronization sharedSynchronization] synchronizationAnimationDirectory:directory callViewController:YES];
  314. // ONLY BACKGROUND
  315. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  316. } else {
  317. // ONLY FOREFROUND
  318. }
  319. }
  320. #pragma --------------------------------------------------------------------------------------------
  321. #pragma mark ===== Setting Active Account =====
  322. #pragma --------------------------------------------------------------------------------------------
  323. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword activeUID:(NSString *)activeUID activeAccessToken:(NSString *)activeAccessToken typeCloud:(NSString *)typeCloud
  324. {
  325. self.activeAccount = activeAccount;
  326. self.activeUrl = activeUrl;
  327. self.activeUser = activeUser;
  328. self.activePassword = activePassword;
  329. self.typeCloud = typeCloud;
  330. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  331. self.activeUID = activeUID;
  332. self.activeAccessToken = activeAccessToken;
  333. }
  334. #pragma --------------------------------------------------------------------------------------------
  335. #pragma mark ===== Quick Actions - ShotcutItem =====
  336. #pragma --------------------------------------------------------------------------------------------
  337. - (void)configDynamicShortcutItems
  338. {
  339. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  340. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionPhotos];
  341. UIApplicationShortcutIcon *shortcutUploadClearIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadClear];
  342. UIApplicationShortcutIcon *shortcutUploadEncryptedIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:image_quickActionUploadEncrypted];
  343. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  344. UIApplicationShortcutItem *shortcutFavorite = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.favorite", bundleId] localizedTitle:NSLocalizedString(@"_favorites_", nil) localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeFavorite] userInfo:nil];
  345. UIApplicationShortcutItem *shortcutUploadClear = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadClear", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadClearIcon userInfo:nil];
  346. UIApplicationShortcutItem *shortcutUploadEncrypted = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.uploadEncrypted", bundleId] localizedTitle:NSLocalizedString(@"_upload_encrypted_file_", nil) localizedSubtitle:nil icon:shortcutUploadEncryptedIcon userInfo:nil];
  347. // add all items to an array
  348. NSArray *items = @[shortcutUploadEncrypted, shortcutUploadClear, shortcutPhotos, shortcutFavorite];
  349. // add the array to our app
  350. [UIApplication sharedApplication].shortcutItems = items;
  351. }
  352. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  353. {
  354. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  355. completionHandler(handledShortCutItem);
  356. }
  357. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  358. {
  359. BOOL handled = NO;
  360. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  361. NSString *shortcutFavorite = [NSString stringWithFormat:@"%@.favorite", bundleId];
  362. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  363. NSString *shortcutUploadClear = [NSString stringWithFormat:@"%@.uploadClear", bundleId];
  364. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  365. if ([shortcutItem.type isEqualToString:shortcutUploadClear] && self.activeAccount) {
  366. dispatch_async(dispatch_get_main_queue(), ^{
  367. if (_activeMain) {
  368. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  369. if (splitViewController.isCollapsed) {
  370. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  371. for (UINavigationController *nvc in tbc.viewControllers) {
  372. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  373. [nvc popToRootViewControllerAnimated:NO];
  374. }
  375. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  376. } else {
  377. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  378. [nvcDetail popToRootViewControllerAnimated:NO];
  379. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  380. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  381. }
  382. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  383. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  384. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:NO viewController:_activeMain];
  385. });
  386. }
  387. });
  388. handled = YES;
  389. }
  390. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  391. dispatch_async(dispatch_get_main_queue(), ^{
  392. if (_activeMain) {
  393. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  394. if (splitViewController.isCollapsed) {
  395. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  396. for (UINavigationController *nvc in tbc.viewControllers) {
  397. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  398. [nvc popToRootViewControllerAnimated:NO];
  399. }
  400. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  401. } else {
  402. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  403. [nvcDetail popToRootViewControllerAnimated:NO];
  404. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  405. [tbc setSelectedIndex:TabBarApplicationIndexFile];
  406. }
  407. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  408. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  409. [[CCQuickActions quickActionsManager] startQuickActionsEncrypted:YES viewController:_activeMain];
  410. });
  411. }
  412. });
  413. handled = YES;
  414. }
  415. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  416. dispatch_async(dispatch_get_main_queue(), ^{
  417. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  418. if (splitViewController.isCollapsed) {
  419. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  420. for (UINavigationController *nvc in tbc.viewControllers) {
  421. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  422. [nvc popToRootViewControllerAnimated:NO];
  423. }
  424. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  425. } else {
  426. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  427. [nvcDetail popToRootViewControllerAnimated:NO];
  428. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  429. [tbc setSelectedIndex:TabBarApplicationIndexPhotos];
  430. }
  431. });
  432. handled = YES;
  433. }
  434. else if ([shortcutItem.type isEqualToString:shortcutFavorite] && self.activeAccount) {
  435. dispatch_async(dispatch_get_main_queue(), ^{
  436. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  437. if (splitViewController.isCollapsed) {
  438. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  439. for (UINavigationController *nvc in tbc.viewControllers) {
  440. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  441. [nvc popToRootViewControllerAnimated:NO];
  442. if ([nvc.topViewController isKindOfClass:[CCFavorite class]])
  443. [(CCFavorite *)nvc.topViewController forcedSwitchFavorite];
  444. }
  445. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  446. } else {
  447. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  448. [nvcDetail popToRootViewControllerAnimated:NO];
  449. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  450. UINavigationController *ncFavorite = [tbc.viewControllers objectAtIndex:TabBarApplicationIndexFavorite];
  451. if ([ncFavorite.topViewController isKindOfClass:[CCFavorite class]])
  452. [(CCFavorite *)ncFavorite.topViewController forcedSwitchFavorite];
  453. [tbc setSelectedIndex:TabBarApplicationIndexFavorite];
  454. }
  455. });
  456. handled = YES;
  457. }
  458. return handled;
  459. }
  460. #pragma --------------------------------------------------------------------------------------------
  461. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  462. #pragma --------------------------------------------------------------------------------------------
  463. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type
  464. {
  465. title = [NSString stringWithFormat:@"%@\n",[CCUtility localizableBrand:title table:nil]];
  466. dispatch_async(dispatch_get_main_queue(), ^{
  467. if (visible) {
  468. [TWMessageBarManager sharedInstance].styleSheet = self;
  469. [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:[CCUtility localizableBrand:description table:nil] type:type duration:delay];
  470. } else {
  471. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  472. }
  473. });
  474. }
  475. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  476. {
  477. UIColor *backgroundColor = nil;
  478. switch (type)
  479. {
  480. case TWMessageBarMessageTypeError:
  481. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  482. break;
  483. case TWMessageBarMessageTypeSuccess:
  484. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  485. break;
  486. case TWMessageBarMessageTypeInfo:
  487. backgroundColor = COLOR_BRAND_MESSAGE;
  488. break;
  489. default:
  490. break;
  491. }
  492. return backgroundColor;
  493. }
  494. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  495. {
  496. UIColor *strokeColor = nil;
  497. switch (type)
  498. {
  499. case TWMessageBarMessageTypeError:
  500. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  501. break;
  502. case TWMessageBarMessageTypeSuccess:
  503. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  504. break;
  505. case TWMessageBarMessageTypeInfo:
  506. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  507. break;
  508. default:
  509. break;
  510. }
  511. return strokeColor;
  512. }
  513. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  514. {
  515. UIImage *iconImage = nil;
  516. switch (type)
  517. {
  518. case TWMessageBarMessageTypeError:
  519. iconImage = [UIImage imageNamed:@"icon-error.png"];
  520. break;
  521. case TWMessageBarMessageTypeSuccess:
  522. iconImage = [UIImage imageNamed:@"icon-success.png"];
  523. break;
  524. case TWMessageBarMessageTypeInfo:
  525. iconImage = [UIImage imageNamed:@"icon-info.png"];
  526. break;
  527. default:
  528. break;
  529. }
  530. return iconImage;
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== TabBarController =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)createTabBarController
  536. {
  537. UITabBarItem *item;
  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. }
  573. - (BOOL)plusButton:(BOOL)visible
  574. {
  575. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  576. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  577. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  578. if (buttonPlus)
  579. [buttonPlus removeFromSuperview];
  580. if (visible) {
  581. UIImage *buttonImage = [UIImage imageNamed:@"Plus"];
  582. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  583. button.tag = 99;
  584. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  585. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  586. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  587. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  588. button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
  589. CGFloat heightDifference = buttonImage.size.height - tabBarController.tabBar.frame.size.height;
  590. if (heightDifference < 0) {
  591. button.center = tabBarController.tabBar.center;
  592. } else {
  593. CGPoint center = tabBarController.tabBar.center;
  594. center.y = center.y - 15;
  595. button.center = center;
  596. }
  597. [tabBarController.view addSubview:button];
  598. }
  599. if (buttonPlus) return true;
  600. else return false;
  601. }
  602. - (void)handleTouchTabbarCenter:(id)sender
  603. {
  604. if (_activeMain)
  605. [_activeMain addActionTable];
  606. /*
  607. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.window.rootViewController.view title:nil];
  608. [actionSheet addButtonWithTitle:NSLocalizedString(@"Info", nil)
  609. image:[UIImage imageNamed:@"passcode"]
  610. type:AHKActionSheetButtonTypeDefault
  611. handler:^(AHKActionSheet *as) {
  612. if (_activeMain)
  613. [_activeMain returnCreate:returnCreateFolderPlain];
  614. }];
  615. [actionSheet addButtonWithTitle:NSLocalizedString(@"Add to Favorites", nil)
  616. image:[UIImage imageNamed:@"password"]
  617. type:AHKActionSheetButtonTypeDefault
  618. handler:^(AHKActionSheet *as) {
  619. if (_activeMain)
  620. [_activeMain returnCreate:returnCreateFotoVideoPlain];
  621. }];
  622. [actionSheet show];
  623. */
  624. }
  625. - (void)updateApplicationIconBadgeNumber
  626. {
  627. // Core Data
  628. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  629. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  630. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  631. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  632. // netQueueDownload
  633. for (NSOperation *operation in [app.netQueueDownload operations]) {
  634. /*** NEXTCLOUD OWNCLOUD ***/
  635. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  636. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  637. #ifdef CC
  638. /*** DROPBOX ***/
  639. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  640. if (((DBnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  641. #endif
  642. }
  643. // netQueueDownloadWWan
  644. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  645. /*** NEXTCLOUD OWNCLOUD ***/
  646. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  647. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  648. #ifdef CC
  649. /*** DROPBOX ***/
  650. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  651. if (((DBnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  652. #endif
  653. }
  654. // netQueueUpload
  655. for (NSOperation *operation in [app.netQueueUpload operations]) {
  656. /*** NEXTCLOUD OWNCLOUD ***/
  657. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  658. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  659. #ifdef CC
  660. /*** DROPBOX ***/
  661. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  662. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  663. #endif
  664. }
  665. // netQueueUploadWWan
  666. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  667. /*** NEXTCLOUD OWNCLOUD ***/
  668. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  669. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  670. #ifdef CC
  671. /*** DROPBOX ***/
  672. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  673. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  674. #endif
  675. }
  676. // Total
  677. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  678. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  679. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  680. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  681. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  682. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  683. if (total > 0)
  684. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  685. else
  686. [tbItem setBadgeValue:nil];
  687. }
  688. }
  689. #pragma --------------------------------------------------------------------------------------------
  690. #pragma mark ===== Media Player Control =====
  691. #pragma --------------------------------------------------------------------------------------------
  692. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  693. {
  694. switch (event.subtype) {
  695. case UIEventSubtypeRemoteControlPlay:
  696. if (self.player.mediaPlayer) {
  697. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  698. if (self.player.mediaPlayer.nowPlayingItem.title)
  699. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  700. if (self.player.mediaPlayer.nowPlayingItem.artist)
  701. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  702. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  703. [self.player.mediaPlayer play];
  704. }
  705. break;
  706. case UIEventSubtypeRemoteControlPause:
  707. if (self.player.mediaPlayer) {
  708. [self.player.mediaPlayer pause];
  709. }
  710. break;
  711. case UIEventSubtypeRemoteControlNextTrack:
  712. // handle it break;
  713. case UIEventSubtypeRemoteControlPreviousTrack:
  714. // handle it break;
  715. default:
  716. break;
  717. }
  718. }
  719. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  720. {
  721. return YES;
  722. }
  723. #pragma --------------------------------------------------------------------------------------------
  724. #pragma mark ===== Manager Passcode =====
  725. #pragma --------------------------------------------------------------------------------------------
  726. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  727. {
  728. // fermiamo la data della sessione
  729. self.sessionePasscodeLock = nil;
  730. // se il block code è a zero esci con NON attivare la richiesta password
  731. if ([[CCUtility getBlockCode] length] == 0) return NO;
  732. // se non c'è attivo un account esci con NON attivare la richiesta password
  733. if ([self.activeAccount length] == 0) return NO;
  734. // se non c'è il passcode esci con NON attivare la richiesta password
  735. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  736. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  737. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  738. return YES;
  739. }
  740. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  741. {
  742. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  743. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  744. viewController.delegate = self;
  745. viewController.title = _brand_;
  746. viewController.fromType = CCBKPasscodeFromLockScreen;
  747. viewController.inputViewTitlePassword = YES;
  748. if ([CCUtility getSimplyBlockCode]) {
  749. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  750. viewController.passcodeInputView.maximumLength = 6;
  751. } else {
  752. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  753. viewController.passcodeInputView.maximumLength = 64;
  754. }
  755. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  756. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  757. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  758. return navigationController;
  759. }
  760. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  761. {
  762. [aViewController dismissViewControllerAnimated:YES completion:nil];
  763. // is a lock screen
  764. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  765. [aViewController dismissViewControllerAnimated:YES completion:nil];
  766. // start session Passcode Lock
  767. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  768. self.sessionePasscodeLock = [NSDate date];
  769. }
  770. }
  771. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  772. {
  773. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  774. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  775. //self.lockUntilDate = nil;
  776. //self.failedAttempts = 0;
  777. aResultHandler(YES);
  778. } else aResultHandler(NO);
  779. } else aResultHandler(YES);
  780. }
  781. #pragma --------------------------------------------------------------------------------------------
  782. #pragma mark ===== reachabilityChanged =====
  783. #pragma --------------------------------------------------------------------------------------------
  784. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  785. {
  786. if ([self.reachability isReachable]) {
  787. if (self.lastReachability == NO) {
  788. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  789. if (_activeMain)
  790. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  791. }
  792. NSLog(@"[LOG] Reachability Changed: Reachable");
  793. self.lastReachability = YES;
  794. } else {
  795. if (self.lastReachability == YES) {
  796. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  797. }
  798. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  799. self.lastReachability = NO;
  800. }
  801. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  802. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  803. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  804. }
  805. #pragma --------------------------------------------------------------------------------------------
  806. #pragma mark ===== Fetch =====
  807. #pragma --------------------------------------------------------------------------------------------
  808. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  809. {
  810. NSLog(@"[LOG] Start Fetch");
  811. // Verify new photo
  812. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  813. // after 20 sec verify Re
  814. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  815. [[CCNetworking sharedNetworking] automaticDownloadInError];
  816. [[CCNetworking sharedNetworking] automaticUploadInError];
  817. NSLog(@"[LOG] End Fetch 20 sec.");
  818. });
  819. // after 25 sec
  820. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  821. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  822. if ([records count] > 0) {
  823. completionHandler(UIBackgroundFetchResultNewData);
  824. } else {
  825. completionHandler(UIBackgroundFetchResultNoData);
  826. }
  827. NSLog(@"[LOG] End Fetch 25 sec.");
  828. });
  829. }
  830. #pragma --------------------------------------------------------------------------------------------
  831. #pragma mark ===== Operation Networking & Session =====
  832. #pragma --------------------------------------------------------------------------------------------
  833. - (void)cancelAllOperations
  834. {
  835. [_netQueue cancelAllOperations];
  836. [_netQueueDownload cancelAllOperations];
  837. [_netQueueDownloadWWan cancelAllOperations];
  838. [_netQueueUpload cancelAllOperations];
  839. [_netQueueUploadWWan cancelAllOperations];
  840. [self performSelector:@selector(updateApplicationIconBadgeNumber) withObject:nil afterDelay:0.5];
  841. }
  842. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  843. {
  844. id operation;
  845. BOOL activityIndicator = NO;
  846. // Activity Indicator
  847. if (netQueue == _netQueue)
  848. activityIndicator = YES;
  849. /*** NEXTCLOUD OWNCLOUD ***/
  850. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  851. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud activityIndicator:activityIndicator];
  852. #ifdef CC
  853. /*** DROPBOX ***/
  854. if ([_typeCloud isEqualToString:typeCloudDropbox])
  855. operation = [[DBnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withActiveUID:_activeUID withActiveAccessToken:_activeAccessToken activityIndicator:activityIndicator];
  856. #endif
  857. [operation setQueuePriority:metadataNet.priority];
  858. [netQueue addOperation:operation];
  859. }
  860. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  861. {
  862. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  863. /*** NEXTCLOUD OWNCLOUD ***/
  864. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  865. for (OCnetworking *operation in [self.netQueueDownload operations])
  866. if ([operation.metadataNet.selector isEqualToString:selector])
  867. [metadatasNet addObject:[operation.metadataNet copy]];
  868. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  869. if ([operation.metadataNet.selector isEqualToString:selector])
  870. [metadatasNet addObject:[operation.metadataNet copy]];
  871. }
  872. #ifdef CC
  873. /*** DROPBOX ***/
  874. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  875. for (DBnetworking *operation in [self.netQueueDownload operations])
  876. if ([operation.metadataNet.selector isEqualToString:selector])
  877. [metadatasNet addObject:operation.metadataNet];
  878. for (DBnetworking *operation in [self.netQueueDownloadWWan operations])
  879. if ([operation.metadataNet.selector isEqualToString:selector])
  880. [metadatasNet addObject:operation.metadataNet];
  881. }
  882. #endif
  883. return metadatasNet;
  884. }
  885. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  886. {
  887. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  888. /*** NEXTCLOUD OWNCLOUD ***/
  889. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  890. for (OCnetworking *operation in [self.netQueueUpload operations])
  891. if ([operation.metadataNet.selector isEqualToString:selector])
  892. [metadatasNet addObject:[operation.metadataNet copy]];
  893. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  894. if ([operation.metadataNet.selector isEqualToString:selector])
  895. [metadatasNet addObject:[operation.metadataNet copy]];
  896. }
  897. #ifdef CC
  898. /*** DROPBOX ***/
  899. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  900. for (DBnetworking *operation in [self.netQueueUpload operations])
  901. if ([operation.metadataNet.selector isEqualToString:selector])
  902. [metadatasNet addObject:operation.metadataNet];
  903. for (DBnetworking *operation in [self.netQueueUploadWWan operations])
  904. if ([operation.metadataNet.selector isEqualToString:selector])
  905. [metadatasNet addObject:operation.metadataNet];
  906. }
  907. #endif
  908. return metadatasNet;
  909. }
  910. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  911. {
  912. // Only one
  913. if ([[self verifyExistsInQueuesUploadSelector:selector] count] > 1)
  914. return;
  915. // Verify num error if selectorUploadAutomaticAll
  916. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  917. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  918. #ifdef DEBUG
  919. NSArray *records = [[NSArray alloc] init];
  920. records = [TableMetadata MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  921. #endif
  922. if (count >= 10) {
  923. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  924. return;
  925. }
  926. }
  927. // Add Network queue
  928. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector context:nil];
  929. if (metadataNet) {
  930. NSOperationQueue *queue;
  931. if ([metadataNet.session containsString:@"wwan"])
  932. queue = app.netQueueUploadWWan;
  933. else
  934. queue = app.netQueueUpload;
  935. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet];
  936. }
  937. }
  938. - (void)verifyDownloadUploadInProgress
  939. {
  940. BOOL callVerifyDownload = NO;
  941. BOOL callVerifyUpload = NO;
  942. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  943. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  944. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  945. callVerifyDownload = YES;
  946. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  947. }
  948. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  949. callVerifyUpload = YES;
  950. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  951. }
  952. if (callVerifyDownload && callVerifyUpload) {
  953. NSLog(@"[LOG] Stop timer verify session");
  954. [self.timerVerifySessionInProgress invalidate];
  955. }
  956. }
  957. }
  958. // Notification change session
  959. - (void)sessionChanged:(NSNotification *)notification
  960. {
  961. NSURLSession *session;
  962. CCMetadata *metadata;
  963. NSURLSessionTask *task;
  964. for (id object in notification.object) {
  965. if ([object isKindOfClass:[NSURLSession class]])
  966. session = object;
  967. if ([object isKindOfClass:[CCMetadata class]])
  968. metadata = object;
  969. if ([object isKindOfClass:[NSURLSessionTask class]])
  970. task = object;
  971. }
  972. /*
  973. Task
  974. */
  975. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  976. app.sessionDateLastDownloadTasks = [NSDate date];
  977. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  978. app.sessionDateLastUploadTasks = [NSDate date];
  979. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  980. dispatch_async(dispatch_get_main_queue(), ^{
  981. [self changeTask:metadata];
  982. });
  983. /*
  984. Session
  985. */
  986. if (session) {
  987. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  988. unsigned long numDownload = [downloadTasks count];
  989. unsigned long numUpload = [uploadTasks count];
  990. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  991. }];
  992. }
  993. }
  994. - (void)changeTask:(CCMetadata *)metadata
  995. {
  996. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  997. // sessionTaskIdentifier on Stop
  998. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  999. }
  1000. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  1001. // V 1.8 if upload_session_wwan change in upload_session
  1002. if ([metadata.session isEqualToString:upload_session_wwan])
  1003. metadata.session = upload_session;
  1004. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  1005. }
  1006. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  1007. BOOL downloadData = NO, downloadPlist = NO;
  1008. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  1009. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  1010. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1011. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1012. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  1013. });
  1014. }
  1015. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1016. // remove the file
  1017. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  1018. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  1019. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  1020. }
  1021. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  1022. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1023. }
  1024. // remove ChangeTask (fileID) from the list
  1025. [_listChangeTask removeObjectForKey:metadata.fileID];
  1026. // delete progress
  1027. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  1028. // Detail
  1029. if (_activeDetail)
  1030. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  1031. // Refresh
  1032. if (_activeMain && [_listChangeTask count] == 0)
  1033. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  1034. }
  1035. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  1036. {
  1037. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  1038. // Update icon badge number
  1039. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1040. [self updateApplicationIconBadgeNumber];
  1041. });
  1042. }
  1043. #pragma --------------------------------------------------------------------------------------------
  1044. #pragma mark ===== Dropbox =====
  1045. #pragma --------------------------------------------------------------------------------------------
  1046. #ifdef CC
  1047. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  1048. {
  1049. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1050. }
  1051. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  1052. {
  1053. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  1054. [CCCoreData deleteAccount:account];
  1055. // new account
  1056. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  1057. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  1058. if (tableAccount)
  1059. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  1060. NSString *uuid = [CCUtility getUUID];
  1061. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  1062. // update ManageAccount
  1063. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  1064. // Login correct
  1065. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  1066. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  1067. }
  1068. #endif
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1071. #pragma --------------------------------------------------------------------------------------------
  1072. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1073. {
  1074. return YES;
  1075. }
  1076. // Method called from iOS system to send a file from other app.
  1077. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1078. {
  1079. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1080. NSLog(@"[LOG] the path is: %@", url.path);
  1081. #ifdef CC
  1082. /*************************************** DROPBOX *********************************/
  1083. if ([[DBSession sharedSession] handleOpenURL:url]) {
  1084. NSString *query = url.query;
  1085. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  1086. NSDictionary *urlData = [DBSession parseURLParams:query];
  1087. NSString *uid = [urlData objectForKey:@"uid"];
  1088. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  1089. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  1090. self.restClient.delegate = self;
  1091. [self.restClient loadAccountInfo];
  1092. }
  1093. } else {
  1094. // user cancelled the login
  1095. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1096. }
  1097. return YES;
  1098. }
  1099. /*********************************************************************************/
  1100. #endif
  1101. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1102. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1103. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  1104. if (self.activeAccount && [passcode length]) {
  1105. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1106. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1107. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1108. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1109. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1110. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1111. });
  1112. }
  1113. // remove from InBox
  1114. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1115. return YES;
  1116. }
  1117. #pragma --------------------------------------------------------------------------------------------
  1118. #pragma mark ===== UPGRADE =====
  1119. #pragma --------------------------------------------------------------------------------------------
  1120. - (void)upgrade
  1121. {
  1122. #ifdef DEBUG
  1123. // [CCCoreData flushTableGPS];
  1124. // [CCCoreData setGeoInformationLocalNull];
  1125. #endif
  1126. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1127. /* ---------------------- UPGRADE VERSION ----------------------- */
  1128. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1129. [CCCoreData flushTableDirectoryAccount:nil];
  1130. [CCCoreData flushTableLocalFileAccount:nil];
  1131. [CCCoreData flushTableMetadataAccount:nil];
  1132. }
  1133. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1134. [CCCoreData flushTableGPS];
  1135. [CCCoreData setGeoInformationLocalNull];
  1136. }
  1137. }
  1138. @end