AppDelegate.m 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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. #import "Nextcloud-Swift.h"
  39. @interface AppDelegate ()
  40. {
  41. }
  42. @end
  43. @implementation AppDelegate
  44. + (void)initialize
  45. {
  46. [iRate sharedInstance].daysUntilPrompt = 10;
  47. [iRate sharedInstance].usesUntilPrompt = 10;
  48. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  49. //enable preview mode
  50. //[iRate sharedInstance].previewMode = YES;
  51. }
  52. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  53. {
  54. NSString *dir;
  55. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  56. NSLog(@"[LOG] Start program group %@", dirGroup);
  57. // create Directory local => Documents
  58. dir = [CCUtility getDirectoryLocal];
  59. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  60. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  61. // create Directory audio => Library, Application Support, audio
  62. dir = [CCUtility getDirectoryAudio];
  63. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  64. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  65. // create Crypto Cloud in Group => Library, Application Support, Crypto Cloud
  66. dir = [[dirGroup URLByAppendingPathComponent:appDatabase] path];
  67. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  68. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  69. //[CCCoreData verifyVersionCoreData];
  70. [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:(id)[dirGroup URLByAppendingPathComponent:[appDatabase stringByAppendingPathComponent:@"cryptocloud"]]];
  71. #ifdef DEBUG
  72. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
  73. #else
  74. [MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelOff];
  75. #endif
  76. // Verify upgrade
  77. [self upgrade];
  78. // Set account, if no exists clear all
  79. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  80. if (recordAccount == nil) {
  81. // remove all the keys Chain
  82. [CCUtility deleteAllChainStore];
  83. // remove all the App group key
  84. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  85. } else {
  86. [self settingActiveAccount:recordAccount.account activeUrl:recordAccount.url activeUser:recordAccount.user activePassword:recordAccount.password activeUID:recordAccount.uid activeAccessToken:recordAccount.token typeCloud:recordAccount.typeCloud];
  87. }
  88. // Operation Queue OC-DB Networking
  89. _netQueue = [[NSOperationQueue alloc] init];
  90. _netQueue.name = netQueueName;
  91. _netQueue.maxConcurrentOperationCount = maxConcurrentOperation;
  92. _netQueueDownload = [[NSOperationQueue alloc] init];
  93. _netQueueDownload.name = netQueueDownloadName;
  94. _netQueueDownload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  95. _netQueueDownloadWWan = [[NSOperationQueue alloc] init];
  96. _netQueueDownloadWWan.name = netQueueDownloadWWanName;
  97. _netQueueDownloadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  98. _netQueueUpload = [[NSOperationQueue alloc] init];
  99. _netQueueUpload.name = netQueueUploadName;
  100. _netQueueUpload.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  101. _netQueueUploadWWan = [[NSOperationQueue alloc] init];
  102. _netQueueUploadWWan.name = netQueueUploadWWanName;
  103. _netQueueUploadWWan.maxConcurrentOperationCount = maxConcurrentOperationDownloadUpload;
  104. #ifdef CC
  105. // Inizialize DBSession for Dropbox
  106. NSString *appKey = appKeyCryptoCloud;
  107. NSString *appSecret = appSecretCryptoCloud;
  108. DBSession *dbSession = [[DBSession alloc] initWithAppKey:appKey appSecret:appSecret root:kDBRootDropbox];
  109. [DBSession setSharedSession:dbSession];
  110. #endif
  111. // Add notification change session
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:networkingSessionNotification object:nil];
  113. // Inizializzazioni Share
  114. self.sharesID = [[NSMutableDictionary alloc] init];
  115. self.sharesLink = [[NSMutableDictionary alloc] init];
  116. self.sharesUserAndGroup = [[NSMutableDictionary alloc] init];
  117. // Verify Session in progress and Init date task
  118. self.sessionDateLastDownloadTasks = [NSDate date];
  119. self.sessionDateLastUploadTasks = [NSDate date];
  120. self.timerVerifySessionInProgress = [NSTimer scheduledTimerWithTimeInterval:timerVerifySession target:self selector:@selector(verifyDownloadUploadInProgress) userInfo:nil repeats:YES];
  121. // Background Fetch
  122. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  123. // Init List
  124. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  125. self.listChangeTask = [[NSMutableDictionary alloc] init];
  126. self.listMainVC = [[NSMutableDictionary alloc] init];
  127. // Player audio
  128. self.player = [LMMediaPlayerView sharedPlayerView];
  129. self.player.delegate = self;
  130. // ico Image Cache
  131. self.icoImagesCache = [[NSMutableDictionary alloc] init];
  132. // remove tmp & cache
  133. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  134. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  135. for (NSString *file in tmpDirectory) {
  136. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  137. }
  138. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  139. });
  140. // setting Reachable in back
  141. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  142. self.reachability = [Reachability reachabilityForInternetConnection];
  143. self.lastReachability = [self.reachability isReachable];
  144. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  145. [self.reachability startNotifier];
  146. });
  147. //AV Session
  148. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  149. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  150. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  151. // permission request camera roll
  152. ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  153. [lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  154. //NSLog(@"[LOG] %li",(long)[group numberOfAssets]);
  155. } failureBlock:^(NSError *error) {
  156. if (error.code == ALAssetsLibraryAccessUserDeniedError) {
  157. NSLog(@"[LOG] user denied access, code: %li",(long)error.code);
  158. }else{
  159. NSLog(@"[LOG] Other error code: %li",(long)error.code);
  160. }
  161. }];
  162. // permission request notification
  163. if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  164. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
  165. [application registerUserNotificationSettings:settings];
  166. }
  167. // it is a device Jailbroken
  168. self.isDeviceJailbroken = isDeviceJailbroken();
  169. [self.window setTintColor:COLOR_BRAND];
  170. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  171. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  172. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  173. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  174. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  175. // Settings TabBar
  176. [self createTabBarController];
  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. NSLayoutConstraint *constraint;
  539. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  540. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  541. [CCAspect aspectTabBar:tabBarController.tabBar hidden:NO];
  542. // File
  543. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFile];
  544. [item setTitle:NSLocalizedString(@"_home_", nil)];
  545. item.image = [UIImage imageNamed:image_tabBarFile];
  546. item.selectedImage = [UIImage imageNamed:image_tabBarFile];
  547. // Favorite - Local
  548. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFavorite];
  549. if (app.isLocalStorage) {
  550. [item setTitle:NSLocalizedString(@"_local_storage_", nil)];
  551. item.image = [UIImage imageNamed:image_tabBarLocal];
  552. item.selectedImage = [UIImage imageNamed:image_tabBarLocal];
  553. } else {
  554. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  555. item.image = [UIImage imageNamed:image_tabBarFavorite];
  556. item.selectedImage = [UIImage imageNamed:image_tabBarFavorite];
  557. }
  558. // Hide (PLUS)
  559. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexHide];
  560. item.title = nil;
  561. item.image = nil;
  562. item.enabled = false;
  563. // Photos
  564. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexPhotos];
  565. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  566. item.image = [UIImage imageNamed:image_tabBarPhotos];
  567. item.selectedImage = [UIImage imageNamed:image_tabBarPhotos];
  568. // Settings
  569. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexSettings];
  570. [item setTitle:NSLocalizedString(@"_settings_", nil)];
  571. item.image = [UIImage imageNamed:image_tabBarSettings];
  572. item.selectedImage = [UIImage imageNamed:image_tabBarSettings];
  573. // Plus Button
  574. UIImage *buttonImage = [UIImage imageNamed:@"Plus"];
  575. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  576. button.tag = 99;
  577. button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  578. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  579. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  580. [button addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  581. [button setTranslatesAutoresizingMaskIntoConstraints:NO];
  582. [tabBarController.view addSubview:button];
  583. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  584. [tabBarController.view addConstraint:constraint];
  585. constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5];
  586. [tabBarController.view addConstraint:constraint];
  587. }
  588. - (void)plusButtonVisibile:(BOOL)visible
  589. {
  590. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  591. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  592. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  593. if (buttonPlus) {
  594. if (visible) {
  595. buttonPlus.hidden = false;
  596. } else {
  597. buttonPlus.hidden = true;
  598. }
  599. }
  600. }
  601. - (void)handleTouchTabbarCenter:(id)sender
  602. {
  603. CreateMenu *menu = [[CreateMenu alloc] init];
  604. [menu createMenuPlainWithView:self.window.rootViewController.view];
  605. }
  606. - (void)updateApplicationIconBadgeNumber
  607. {
  608. // Core Data
  609. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  610. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  611. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  612. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  613. // netQueueDownload
  614. for (NSOperation *operation in [app.netQueueDownload operations]) {
  615. /*** NEXTCLOUD OWNCLOUD ***/
  616. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  617. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  618. #ifdef CC
  619. /*** DROPBOX ***/
  620. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  621. if (((DBnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  622. #endif
  623. }
  624. // netQueueDownloadWWan
  625. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  626. /*** NEXTCLOUD OWNCLOUD ***/
  627. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  628. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  629. #ifdef CC
  630. /*** DROPBOX ***/
  631. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  632. if (((DBnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  633. #endif
  634. }
  635. // netQueueUpload
  636. for (NSOperation *operation in [app.netQueueUpload operations]) {
  637. /*** NEXTCLOUD OWNCLOUD ***/
  638. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  639. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  640. #ifdef CC
  641. /*** DROPBOX ***/
  642. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  643. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  644. #endif
  645. }
  646. // netQueueUploadWWan
  647. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  648. /*** NEXTCLOUD OWNCLOUD ***/
  649. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  650. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  651. #ifdef CC
  652. /*** DROPBOX ***/
  653. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  654. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  655. #endif
  656. }
  657. // Total
  658. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  659. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  660. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  661. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  662. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  663. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  664. if (total > 0)
  665. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  666. else
  667. [tbItem setBadgeValue:nil];
  668. }
  669. }
  670. #pragma --------------------------------------------------------------------------------------------
  671. #pragma mark ===== Media Player Control =====
  672. #pragma --------------------------------------------------------------------------------------------
  673. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  674. {
  675. switch (event.subtype) {
  676. case UIEventSubtypeRemoteControlPlay:
  677. if (self.player.mediaPlayer) {
  678. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  679. if (self.player.mediaPlayer.nowPlayingItem.title)
  680. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  681. if (self.player.mediaPlayer.nowPlayingItem.artist)
  682. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  683. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  684. [self.player.mediaPlayer play];
  685. }
  686. break;
  687. case UIEventSubtypeRemoteControlPause:
  688. if (self.player.mediaPlayer) {
  689. [self.player.mediaPlayer pause];
  690. }
  691. break;
  692. case UIEventSubtypeRemoteControlNextTrack:
  693. // handle it break;
  694. case UIEventSubtypeRemoteControlPreviousTrack:
  695. // handle it break;
  696. default:
  697. break;
  698. }
  699. }
  700. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  701. {
  702. return YES;
  703. }
  704. #pragma --------------------------------------------------------------------------------------------
  705. #pragma mark ===== Manager Passcode =====
  706. #pragma --------------------------------------------------------------------------------------------
  707. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  708. {
  709. // fermiamo la data della sessione
  710. self.sessionePasscodeLock = nil;
  711. // se il block code è a zero esci con NON attivare la richiesta password
  712. if ([[CCUtility getBlockCode] length] == 0) return NO;
  713. // se non c'è attivo un account esci con NON attivare la richiesta password
  714. if ([self.activeAccount length] == 0) return NO;
  715. // se non c'è il passcode esci con NON attivare la richiesta password
  716. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  717. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  718. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  719. return YES;
  720. }
  721. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  722. {
  723. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  724. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  725. viewController.delegate = self;
  726. viewController.title = _brand_;
  727. viewController.fromType = CCBKPasscodeFromLockScreen;
  728. viewController.inputViewTitlePassword = YES;
  729. if ([CCUtility getSimplyBlockCode]) {
  730. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  731. viewController.passcodeInputView.maximumLength = 6;
  732. } else {
  733. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  734. viewController.passcodeInputView.maximumLength = 64;
  735. }
  736. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  737. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  738. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  739. return navigationController;
  740. }
  741. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  742. {
  743. [aViewController dismissViewControllerAnimated:YES completion:nil];
  744. // is a lock screen
  745. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  746. [aViewController dismissViewControllerAnimated:YES completion:nil];
  747. // start session Passcode Lock
  748. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  749. self.sessionePasscodeLock = [NSDate date];
  750. }
  751. }
  752. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  753. {
  754. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  755. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  756. //self.lockUntilDate = nil;
  757. //self.failedAttempts = 0;
  758. aResultHandler(YES);
  759. } else aResultHandler(NO);
  760. } else aResultHandler(YES);
  761. }
  762. #pragma --------------------------------------------------------------------------------------------
  763. #pragma mark ===== reachabilityChanged =====
  764. #pragma --------------------------------------------------------------------------------------------
  765. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  766. {
  767. if ([self.reachability isReachable]) {
  768. if (self.lastReachability == NO) {
  769. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  770. if (_activeMain)
  771. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  772. }
  773. NSLog(@"[LOG] Reachability Changed: Reachable");
  774. self.lastReachability = YES;
  775. } else {
  776. if (self.lastReachability == YES) {
  777. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  778. }
  779. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  780. self.lastReachability = NO;
  781. }
  782. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  783. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  784. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  785. }
  786. #pragma --------------------------------------------------------------------------------------------
  787. #pragma mark ===== Fetch =====
  788. #pragma --------------------------------------------------------------------------------------------
  789. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  790. {
  791. NSLog(@"[LOG] Start Fetch");
  792. // Verify new photo
  793. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  794. // after 20 sec verify Re
  795. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  796. [[CCNetworking sharedNetworking] automaticDownloadInError];
  797. [[CCNetworking sharedNetworking] automaticUploadInError];
  798. NSLog(@"[LOG] End Fetch 20 sec.");
  799. });
  800. // after 25 sec
  801. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  802. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  803. if ([records count] > 0) {
  804. completionHandler(UIBackgroundFetchResultNewData);
  805. } else {
  806. completionHandler(UIBackgroundFetchResultNoData);
  807. }
  808. NSLog(@"[LOG] End Fetch 25 sec.");
  809. });
  810. }
  811. #pragma --------------------------------------------------------------------------------------------
  812. #pragma mark ===== Operation Networking & Session =====
  813. #pragma --------------------------------------------------------------------------------------------
  814. - (void)cancelAllOperations
  815. {
  816. [_netQueue cancelAllOperations];
  817. [_netQueueDownload cancelAllOperations];
  818. [_netQueueDownloadWWan cancelAllOperations];
  819. [_netQueueUpload cancelAllOperations];
  820. [_netQueueUploadWWan cancelAllOperations];
  821. [self performSelector:@selector(updateApplicationIconBadgeNumber) withObject:nil afterDelay:0.5];
  822. }
  823. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  824. {
  825. id operation;
  826. BOOL activityIndicator = NO;
  827. // Activity Indicator
  828. if (netQueue == _netQueue)
  829. activityIndicator = YES;
  830. /*** NEXTCLOUD OWNCLOUD ***/
  831. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  832. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud activityIndicator:activityIndicator];
  833. #ifdef CC
  834. /*** DROPBOX ***/
  835. if ([_typeCloud isEqualToString:typeCloudDropbox])
  836. operation = [[DBnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withActiveUID:_activeUID withActiveAccessToken:_activeAccessToken activityIndicator:activityIndicator];
  837. #endif
  838. [operation setQueuePriority:metadataNet.priority];
  839. [netQueue addOperation:operation];
  840. }
  841. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  842. {
  843. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  844. /*** NEXTCLOUD OWNCLOUD ***/
  845. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  846. for (OCnetworking *operation in [self.netQueueDownload operations])
  847. if ([operation.metadataNet.selector isEqualToString:selector])
  848. [metadatasNet addObject:[operation.metadataNet copy]];
  849. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  850. if ([operation.metadataNet.selector isEqualToString:selector])
  851. [metadatasNet addObject:[operation.metadataNet copy]];
  852. }
  853. #ifdef CC
  854. /*** DROPBOX ***/
  855. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  856. for (DBnetworking *operation in [self.netQueueDownload operations])
  857. if ([operation.metadataNet.selector isEqualToString:selector])
  858. [metadatasNet addObject:operation.metadataNet];
  859. for (DBnetworking *operation in [self.netQueueDownloadWWan operations])
  860. if ([operation.metadataNet.selector isEqualToString:selector])
  861. [metadatasNet addObject:operation.metadataNet];
  862. }
  863. #endif
  864. return metadatasNet;
  865. }
  866. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  867. {
  868. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  869. /*** NEXTCLOUD OWNCLOUD ***/
  870. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  871. for (OCnetworking *operation in [self.netQueueUpload operations])
  872. if ([operation.metadataNet.selector isEqualToString:selector])
  873. [metadatasNet addObject:[operation.metadataNet copy]];
  874. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  875. if ([operation.metadataNet.selector isEqualToString:selector])
  876. [metadatasNet addObject:[operation.metadataNet copy]];
  877. }
  878. #ifdef CC
  879. /*** DROPBOX ***/
  880. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  881. for (DBnetworking *operation in [self.netQueueUpload operations])
  882. if ([operation.metadataNet.selector isEqualToString:selector])
  883. [metadatasNet addObject:operation.metadataNet];
  884. for (DBnetworking *operation in [self.netQueueUploadWWan operations])
  885. if ([operation.metadataNet.selector isEqualToString:selector])
  886. [metadatasNet addObject:operation.metadataNet];
  887. }
  888. #endif
  889. return metadatasNet;
  890. }
  891. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  892. {
  893. // Only one
  894. if ([[self verifyExistsInQueuesUploadSelector:selector] count] > 1)
  895. return;
  896. // Verify num error if selectorUploadAutomaticAll
  897. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  898. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  899. #ifdef DEBUG
  900. NSArray *records = [[NSArray alloc] init];
  901. records = [TableMetadata MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  902. #endif
  903. if (count >= 10) {
  904. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  905. return;
  906. }
  907. }
  908. // Add Network queue
  909. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector context:nil];
  910. if (metadataNet) {
  911. NSOperationQueue *queue;
  912. if ([metadataNet.session containsString:@"wwan"])
  913. queue = app.netQueueUploadWWan;
  914. else
  915. queue = app.netQueueUpload;
  916. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet];
  917. }
  918. }
  919. - (void)verifyDownloadUploadInProgress
  920. {
  921. BOOL callVerifyDownload = NO;
  922. BOOL callVerifyUpload = NO;
  923. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  924. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  925. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  926. callVerifyDownload = YES;
  927. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  928. }
  929. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  930. callVerifyUpload = YES;
  931. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  932. }
  933. if (callVerifyDownload && callVerifyUpload) {
  934. NSLog(@"[LOG] Stop timer verify session");
  935. [self.timerVerifySessionInProgress invalidate];
  936. }
  937. }
  938. }
  939. // Notification change session
  940. - (void)sessionChanged:(NSNotification *)notification
  941. {
  942. NSURLSession *session;
  943. CCMetadata *metadata;
  944. NSURLSessionTask *task;
  945. for (id object in notification.object) {
  946. if ([object isKindOfClass:[NSURLSession class]])
  947. session = object;
  948. if ([object isKindOfClass:[CCMetadata class]])
  949. metadata = object;
  950. if ([object isKindOfClass:[NSURLSessionTask class]])
  951. task = object;
  952. }
  953. /*
  954. Task
  955. */
  956. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  957. app.sessionDateLastDownloadTasks = [NSDate date];
  958. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  959. app.sessionDateLastUploadTasks = [NSDate date];
  960. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  961. dispatch_async(dispatch_get_main_queue(), ^{
  962. [self changeTask:metadata];
  963. });
  964. /*
  965. Session
  966. */
  967. if (session) {
  968. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  969. unsigned long numDownload = [downloadTasks count];
  970. unsigned long numUpload = [uploadTasks count];
  971. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  972. }];
  973. }
  974. }
  975. - (void)changeTask:(CCMetadata *)metadata
  976. {
  977. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  978. // sessionTaskIdentifier on Stop
  979. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  980. }
  981. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  982. // V 1.8 if upload_session_wwan change in upload_session
  983. if ([metadata.session isEqualToString:upload_session_wwan])
  984. metadata.session = upload_session;
  985. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  986. }
  987. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  988. BOOL downloadData = NO, downloadPlist = NO;
  989. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  990. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  991. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  992. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  993. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  994. });
  995. }
  996. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  997. // remove the file
  998. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  999. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  1000. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  1001. }
  1002. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  1003. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1004. }
  1005. // remove ChangeTask (fileID) from the list
  1006. [_listChangeTask removeObjectForKey:metadata.fileID];
  1007. // delete progress
  1008. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  1009. // Detail
  1010. if (_activeDetail)
  1011. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  1012. // Refresh
  1013. if (_activeMain && [_listChangeTask count] == 0)
  1014. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  1015. }
  1016. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  1017. {
  1018. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  1019. // Update icon badge number
  1020. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1021. [self updateApplicationIconBadgeNumber];
  1022. });
  1023. }
  1024. #pragma --------------------------------------------------------------------------------------------
  1025. #pragma mark ===== Dropbox =====
  1026. #pragma --------------------------------------------------------------------------------------------
  1027. #ifdef CC
  1028. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  1029. {
  1030. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1031. }
  1032. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  1033. {
  1034. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  1035. [CCCoreData deleteAccount:account];
  1036. // new account
  1037. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  1038. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  1039. if (tableAccount)
  1040. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  1041. NSString *uuid = [CCUtility getUUID];
  1042. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  1043. // update ManageAccount
  1044. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  1045. // Login correct
  1046. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  1047. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  1048. }
  1049. #endif
  1050. #pragma --------------------------------------------------------------------------------------------
  1051. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1052. #pragma --------------------------------------------------------------------------------------------
  1053. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1054. {
  1055. return YES;
  1056. }
  1057. // Method called from iOS system to send a file from other app.
  1058. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1059. {
  1060. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1061. NSLog(@"[LOG] the path is: %@", url.path);
  1062. #ifdef CC
  1063. /*************************************** DROPBOX *********************************/
  1064. if ([[DBSession sharedSession] handleOpenURL:url]) {
  1065. NSString *query = url.query;
  1066. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  1067. NSDictionary *urlData = [DBSession parseURLParams:query];
  1068. NSString *uid = [urlData objectForKey:@"uid"];
  1069. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  1070. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  1071. self.restClient.delegate = self;
  1072. [self.restClient loadAccountInfo];
  1073. }
  1074. } else {
  1075. // user cancelled the login
  1076. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1077. }
  1078. return YES;
  1079. }
  1080. /*********************************************************************************/
  1081. #endif
  1082. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1083. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1084. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  1085. if (self.activeAccount && [passcode length]) {
  1086. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1087. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1088. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1089. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1090. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1091. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1092. });
  1093. }
  1094. // remove from InBox
  1095. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1096. return YES;
  1097. }
  1098. #pragma --------------------------------------------------------------------------------------------
  1099. #pragma mark ===== UPGRADE =====
  1100. #pragma --------------------------------------------------------------------------------------------
  1101. - (void)upgrade
  1102. {
  1103. #ifdef DEBUG
  1104. // [CCCoreData flushTableGPS];
  1105. // [CCCoreData setGeoInformationLocalNull];
  1106. #endif
  1107. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1108. /* ---------------------- UPGRADE VERSION ----------------------- */
  1109. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1110. [CCCoreData flushTableDirectoryAccount:nil];
  1111. [CCCoreData flushTableLocalFileAccount:nil];
  1112. [CCCoreData flushTableMetadataAccount:nil];
  1113. }
  1114. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1115. [CCCoreData flushTableGPS];
  1116. [CCCoreData setGeoInformationLocalNull];
  1117. }
  1118. }
  1119. @end