AppDelegate.m 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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. /*
  547. item.enabled = false;
  548. item.image = nil;
  549. item.title = nil;
  550. */
  551. // Favorite - Local
  552. item = [tabBarController.tabBar.items objectAtIndex:TabBarApplicationIndexFavorite];
  553. if (app.isLocalStorage) {
  554. [item setTitle:NSLocalizedString(@"_local_storage_", nil)];
  555. item.image = [UIImage imageNamed:image_tabBarLocal];
  556. item.selectedImage = [UIImage imageNamed:image_tabBarLocal];
  557. } else {
  558. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  559. item.image = [UIImage imageNamed:image_tabBarFavorite];
  560. item.selectedImage = [UIImage imageNamed:image_tabBarFavorite];
  561. }
  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. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.window.rootViewController.view title:@""];
  605. [actionSheet addButtonWithTitle:NSLocalizedString(@"Info", nil)
  606. image:[UIImage imageNamed:@"passcode"]
  607. type:AHKActionSheetButtonTypeDefault
  608. handler:^(AHKActionSheet *as) {
  609. if (_activeMain)
  610. [_activeMain returnCreate:returnCreateFolderPlain];
  611. }];
  612. [actionSheet addButtonWithTitle:NSLocalizedString(@"Add to Favorites", nil)
  613. image:[UIImage imageNamed:@"password"]
  614. type:AHKActionSheetButtonTypeDefault
  615. handler:^(AHKActionSheet *as) {
  616. if (_activeMain)
  617. [_activeMain returnCreate:returnCreateFotoVideoPlain];
  618. }];
  619. [actionSheet show];
  620. }
  621. - (void)updateApplicationIconBadgeNumber
  622. {
  623. // Core Data
  624. _queueNunDownload = [[CCCoreData getTableMetadataDownloadAccount:self.activeAccount] count];
  625. _queueNumDownloadWWan = [[CCCoreData getTableMetadataDownloadWWanAccount:self.activeAccount] count];
  626. _queueNumUpload = [[CCCoreData getTableMetadataUploadAccount:self.activeAccount] count];
  627. _queueNumUploadWWan = [[CCCoreData getTableMetadataUploadWWanAccount:self.activeAccount] count];
  628. // netQueueDownload
  629. for (NSOperation *operation in [app.netQueueDownload operations]) {
  630. /*** NEXTCLOUD OWNCLOUD ***/
  631. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  632. if (((OCnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  633. #ifdef CC
  634. /*** DROPBOX ***/
  635. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  636. if (((DBnetworking *)operation).isExecuting == NO) _queueNunDownload++;
  637. #endif
  638. }
  639. // netQueueDownloadWWan
  640. for (NSOperation *operation in [app.netQueueDownloadWWan operations]) {
  641. /*** NEXTCLOUD OWNCLOUD ***/
  642. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  643. if (((OCnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  644. #ifdef CC
  645. /*** DROPBOX ***/
  646. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  647. if (((DBnetworking *)operation).isExecuting == NO) _queueNumDownloadWWan++;
  648. #endif
  649. }
  650. // netQueueUpload
  651. for (NSOperation *operation in [app.netQueueUpload operations]) {
  652. /*** NEXTCLOUD OWNCLOUD ***/
  653. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  654. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  655. #ifdef CC
  656. /*** DROPBOX ***/
  657. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  658. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUpload++;
  659. #endif
  660. }
  661. // netQueueUploadWWan
  662. for (NSOperation *operation in [app.netQueueUploadWWan operations]) {
  663. /*** NEXTCLOUD OWNCLOUD ***/
  664. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])
  665. if (((OCnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  666. #ifdef CC
  667. /*** DROPBOX ***/
  668. if ([app.typeCloud isEqualToString:typeCloudDropbox])
  669. if (((DBnetworking *)operation).isExecuting == NO) _queueNumUploadWWan++;
  670. #endif
  671. }
  672. // Total
  673. NSUInteger total = _queueNunDownload + _queueNumDownloadWWan + _queueNumUpload + _queueNumUploadWWan + [CCCoreData countTableAutomaticUploadForAccount:self.activeAccount selector:nil];
  674. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  675. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  676. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  677. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  678. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  679. if (total > 0)
  680. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  681. else
  682. [tbItem setBadgeValue:nil];
  683. }
  684. }
  685. #pragma --------------------------------------------------------------------------------------------
  686. #pragma mark ===== Media Player Control =====
  687. #pragma --------------------------------------------------------------------------------------------
  688. - (void)remoteControlReceivedWithEvent:(UIEvent *)event
  689. {
  690. switch (event.subtype) {
  691. case UIEventSubtypeRemoteControlPlay:
  692. if (self.player.mediaPlayer) {
  693. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  694. if (self.player.mediaPlayer.nowPlayingItem.title)
  695. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  696. if (self.player.mediaPlayer.nowPlayingItem.artist)
  697. [songInfo setObject:self.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  698. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  699. [self.player.mediaPlayer play];
  700. }
  701. break;
  702. case UIEventSubtypeRemoteControlPause:
  703. if (self.player.mediaPlayer) {
  704. [self.player.mediaPlayer pause];
  705. }
  706. break;
  707. case UIEventSubtypeRemoteControlNextTrack:
  708. // handle it break;
  709. case UIEventSubtypeRemoteControlPreviousTrack:
  710. // handle it break;
  711. default:
  712. break;
  713. }
  714. }
  715. - (BOOL)mediaPlayerViewWillStartPlaying:(LMMediaPlayerView *)playerView media:(LMMediaItem *)media
  716. {
  717. return YES;
  718. }
  719. #pragma --------------------------------------------------------------------------------------------
  720. #pragma mark ===== Manager Passcode =====
  721. #pragma --------------------------------------------------------------------------------------------
  722. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  723. {
  724. // fermiamo la data della sessione
  725. self.sessionePasscodeLock = nil;
  726. // se il block code è a zero esci con NON attivare la richiesta password
  727. if ([[CCUtility getBlockCode] length] == 0) return NO;
  728. // se non c'è attivo un account esci con NON attivare la richiesta password
  729. if ([self.activeAccount length] == 0) return NO;
  730. // se non c'è il passcode esci con NON attivare la richiesta password
  731. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) return NO;
  732. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  733. if ([CCUtility getOnlyLockDir] && ![CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount]) return NO;
  734. return YES;
  735. }
  736. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  737. {
  738. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  739. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  740. viewController.delegate = self;
  741. viewController.title = _brand_;
  742. viewController.fromType = CCBKPasscodeFromLockScreen;
  743. viewController.inputViewTitlePassword = YES;
  744. if ([CCUtility getSimplyBlockCode]) {
  745. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  746. viewController.passcodeInputView.maximumLength = 6;
  747. } else {
  748. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  749. viewController.passcodeInputView.maximumLength = 64;
  750. }
  751. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  752. viewController.touchIDManager.promptText = [CCUtility localizableBrand:@"_scan_fingerprint_" table:nil];
  753. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  754. return navigationController;
  755. }
  756. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  757. {
  758. [aViewController dismissViewControllerAnimated:YES completion:nil];
  759. // is a lock screen
  760. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  761. [aViewController dismissViewControllerAnimated:YES completion:nil];
  762. // start session Passcode Lock
  763. if ([CCCoreData isBlockZone:self.serverUrl activeAccount:self.activeAccount])
  764. self.sessionePasscodeLock = [NSDate date];
  765. }
  766. }
  767. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  768. {
  769. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  770. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  771. //self.lockUntilDate = nil;
  772. //self.failedAttempts = 0;
  773. aResultHandler(YES);
  774. } else aResultHandler(NO);
  775. } else aResultHandler(YES);
  776. }
  777. #pragma --------------------------------------------------------------------------------------------
  778. #pragma mark ===== reachabilityChanged =====
  779. #pragma --------------------------------------------------------------------------------------------
  780. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  781. {
  782. if ([self.reachability isReachable]) {
  783. if (self.lastReachability == NO) {
  784. [self messageNotification:@"_network_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  785. if (_activeMain)
  786. [_activeMain performSelector:@selector(requestServerInformation) withObject:nil afterDelay:3];
  787. }
  788. NSLog(@"[LOG] Reachability Changed: Reachable");
  789. self.lastReachability = YES;
  790. } else {
  791. if (self.lastReachability == YES) {
  792. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  793. }
  794. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  795. self.lastReachability = NO;
  796. }
  797. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  798. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  799. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  800. }
  801. #pragma --------------------------------------------------------------------------------------------
  802. #pragma mark ===== Fetch =====
  803. #pragma --------------------------------------------------------------------------------------------
  804. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  805. {
  806. NSLog(@"[LOG] Start Fetch");
  807. // Verify new photo
  808. [[NSNotificationCenter defaultCenter] postNotificationName:@"initStateCameraUpload" object:nil];
  809. // after 20 sec verify Re
  810. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  811. [[CCNetworking sharedNetworking] automaticDownloadInError];
  812. [[CCNetworking sharedNetworking] automaticUploadInError];
  813. NSLog(@"[LOG] End Fetch 20 sec.");
  814. });
  815. // after 25 sec
  816. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  817. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", self.activeAccount] context:nil];
  818. if ([records count] > 0) {
  819. completionHandler(UIBackgroundFetchResultNewData);
  820. } else {
  821. completionHandler(UIBackgroundFetchResultNoData);
  822. }
  823. NSLog(@"[LOG] End Fetch 25 sec.");
  824. });
  825. }
  826. #pragma --------------------------------------------------------------------------------------------
  827. #pragma mark ===== Operation Networking & Session =====
  828. #pragma --------------------------------------------------------------------------------------------
  829. - (void)cancelAllOperations
  830. {
  831. [_netQueue cancelAllOperations];
  832. [_netQueueDownload cancelAllOperations];
  833. [_netQueueDownloadWWan cancelAllOperations];
  834. [_netQueueUpload cancelAllOperations];
  835. [_netQueueUploadWWan cancelAllOperations];
  836. [self performSelector:@selector(updateApplicationIconBadgeNumber) withObject:nil afterDelay:0.5];
  837. }
  838. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  839. {
  840. id operation;
  841. BOOL activityIndicator = NO;
  842. // Activity Indicator
  843. if (netQueue == _netQueue)
  844. activityIndicator = YES;
  845. /*** NEXTCLOUD OWNCLOUD ***/
  846. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud])
  847. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withTypeCloud:_typeCloud activityIndicator:activityIndicator];
  848. #ifdef CC
  849. /*** DROPBOX ***/
  850. if ([_typeCloud isEqualToString:typeCloudDropbox])
  851. operation = [[DBnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl withActiveUID:_activeUID withActiveAccessToken:_activeAccessToken activityIndicator:activityIndicator];
  852. #endif
  853. [operation setQueuePriority:metadataNet.priority];
  854. [netQueue addOperation:operation];
  855. }
  856. - (NSMutableArray *)verifyExistsInQueuesDownloadSelector:(NSString *)selector
  857. {
  858. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  859. /*** NEXTCLOUD OWNCLOUD ***/
  860. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  861. for (OCnetworking *operation in [self.netQueueDownload operations])
  862. if ([operation.metadataNet.selector isEqualToString:selector])
  863. [metadatasNet addObject:[operation.metadataNet copy]];
  864. for (OCnetworking *operation in [self.netQueueDownloadWWan operations])
  865. if ([operation.metadataNet.selector isEqualToString:selector])
  866. [metadatasNet addObject:[operation.metadataNet copy]];
  867. }
  868. #ifdef CC
  869. /*** DROPBOX ***/
  870. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  871. for (DBnetworking *operation in [self.netQueueDownload operations])
  872. if ([operation.metadataNet.selector isEqualToString:selector])
  873. [metadatasNet addObject:operation.metadataNet];
  874. for (DBnetworking *operation in [self.netQueueDownloadWWan operations])
  875. if ([operation.metadataNet.selector isEqualToString:selector])
  876. [metadatasNet addObject:operation.metadataNet];
  877. }
  878. #endif
  879. return metadatasNet;
  880. }
  881. - (NSMutableArray *)verifyExistsInQueuesUploadSelector:(NSString *)selector
  882. {
  883. NSMutableArray *metadatasNet = [[NSMutableArray alloc] init];
  884. /*** NEXTCLOUD OWNCLOUD ***/
  885. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  886. for (OCnetworking *operation in [self.netQueueUpload operations])
  887. if ([operation.metadataNet.selector isEqualToString:selector])
  888. [metadatasNet addObject:[operation.metadataNet copy]];
  889. for (OCnetworking *operation in [self.netQueueUploadWWan operations])
  890. if ([operation.metadataNet.selector isEqualToString:selector])
  891. [metadatasNet addObject:[operation.metadataNet copy]];
  892. }
  893. #ifdef CC
  894. /*** DROPBOX ***/
  895. if ([app.typeCloud isEqualToString:typeCloudDropbox]) {
  896. for (DBnetworking *operation in [self.netQueueUpload operations])
  897. if ([operation.metadataNet.selector isEqualToString:selector])
  898. [metadatasNet addObject:operation.metadataNet];
  899. for (DBnetworking *operation in [self.netQueueUploadWWan operations])
  900. if ([operation.metadataNet.selector isEqualToString:selector])
  901. [metadatasNet addObject:operation.metadataNet];
  902. }
  903. #endif
  904. return metadatasNet;
  905. }
  906. - (void)loadTableAutomaticUploadForSelector:(NSString *)selector
  907. {
  908. // Only one
  909. if ([[self verifyExistsInQueuesUploadSelector:selector] count] > 1)
  910. return;
  911. // Verify num error if selectorUploadAutomaticAll
  912. if ([selector isEqualToString:selectorUploadAutomaticAll]) {
  913. NSUInteger count = [TableMetadata MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  914. #ifdef DEBUG
  915. NSArray *records = [[NSArray alloc] init];
  916. records = [TableMetadata MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (sessionSelector == %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", app.activeAccount, selectorUploadAutomaticAll,taskIdentifierError, taskIdentifierError]];
  917. #endif
  918. if (count >= 10) {
  919. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  920. return;
  921. }
  922. }
  923. // Add Network queue
  924. CCMetadataNet *metadataNet = [CCCoreData getTableAutomaticUploadForAccount:self.activeAccount selector:selector context:nil];
  925. if (metadataNet) {
  926. NSOperationQueue *queue;
  927. if ([metadataNet.session containsString:@"wwan"])
  928. queue = app.netQueueUploadWWan;
  929. else
  930. queue = app.netQueueUpload;
  931. [self addNetworkingOperationQueue:queue delegate:app.activeMain metadataNet:metadataNet];
  932. }
  933. }
  934. - (void)verifyDownloadUploadInProgress
  935. {
  936. BOOL callVerifyDownload = NO;
  937. BOOL callVerifyUpload = NO;
  938. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  939. NSLog(@"[LOG] Verify Download/Upload in progress now : %@ - Download %@ - Upload %@", [NSDate date], [self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession], [self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]);
  940. if ([[NSDate date] compare:[self.sessionDateLastDownloadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  941. callVerifyDownload = YES;
  942. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  943. }
  944. if ([[NSDate date] compare:[self.sessionDateLastUploadTasks dateByAddingTimeInterval:timerVerifySession]] == NSOrderedDescending) {
  945. callVerifyUpload = YES;
  946. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  947. }
  948. if (callVerifyDownload && callVerifyUpload) {
  949. NSLog(@"[LOG] Stop timer verify session");
  950. [self.timerVerifySessionInProgress invalidate];
  951. }
  952. }
  953. }
  954. // Notification change session
  955. - (void)sessionChanged:(NSNotification *)notification
  956. {
  957. NSURLSession *session;
  958. CCMetadata *metadata;
  959. NSURLSessionTask *task;
  960. for (id object in notification.object) {
  961. if ([object isKindOfClass:[NSURLSession class]])
  962. session = object;
  963. if ([object isKindOfClass:[CCMetadata class]])
  964. metadata = object;
  965. if ([object isKindOfClass:[NSURLSessionTask class]])
  966. task = object;
  967. }
  968. /*
  969. Task
  970. */
  971. if ([task isKindOfClass:[NSURLSessionDownloadTask class]])
  972. app.sessionDateLastDownloadTasks = [NSDate date];
  973. if ([task isKindOfClass:[NSURLSessionUploadTask class]])
  974. app.sessionDateLastUploadTasks = [NSDate date];
  975. if (metadata && [_listChangeTask objectForKey:metadata.fileID])
  976. dispatch_async(dispatch_get_main_queue(), ^{
  977. [self changeTask:metadata];
  978. });
  979. /*
  980. Session
  981. */
  982. if (session) {
  983. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  984. unsigned long numDownload = [downloadTasks count];
  985. unsigned long numUpload = [uploadTasks count];
  986. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  987. }];
  988. }
  989. }
  990. - (void)changeTask:(CCMetadata *)metadata
  991. {
  992. if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"stopUpload"]) {
  993. // sessionTaskIdentifier on Stop
  994. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:taskIdentifierStop sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  995. }
  996. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadUpload"]) {
  997. // V 1.8 if upload_session_wwan change in upload_session
  998. if ([metadata.session isEqualToString:upload_session_wwan])
  999. metadata.session = upload_session;
  1000. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  1001. }
  1002. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"reloadDownload"]) {
  1003. BOOL downloadData = NO, downloadPlist = NO;
  1004. if (metadata.sessionTaskIdentifier != taskIdentifierDone) downloadData = YES;
  1005. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) downloadPlist = YES;
  1006. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1007. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1008. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:downloadData downloadPlist:downloadPlist selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:download_session taskStatus:taskStatusResume delegate:nil];
  1009. });
  1010. }
  1011. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1012. // remove the file
  1013. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, app.activeAccount]];
  1014. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  1015. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] error:nil];
  1016. }
  1017. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelDownload"]) {
  1018. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:taskIdentifierDone sessionTaskIdentifierPlist:taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, self.activeAccount] context:nil];
  1019. }
  1020. // remove ChangeTask (fileID) from the list
  1021. [_listChangeTask removeObjectForKey:metadata.fileID];
  1022. // delete progress
  1023. [_listProgressMetadata removeObjectForKey:metadata.fileID];
  1024. // Detail
  1025. if (_activeDetail)
  1026. [_activeDetail progressTask:nil serverUrl:nil cryptated:NO progress:0];
  1027. // Refresh
  1028. if (_activeMain && [_listChangeTask count] == 0)
  1029. [_activeMain getDataSourceWithReloadTableView:metadata.directoryID fileID:nil selector:nil];
  1030. }
  1031. - (void)dropAutomaticUploadWithSelector:(NSString *)selector
  1032. {
  1033. [CCCoreData flushTableAutomaticUploadAccount:self.activeAccount selector:selector];
  1034. // Update icon badge number
  1035. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1036. [self updateApplicationIconBadgeNumber];
  1037. });
  1038. }
  1039. #pragma --------------------------------------------------------------------------------------------
  1040. #pragma mark ===== Dropbox =====
  1041. #pragma --------------------------------------------------------------------------------------------
  1042. #ifdef CC
  1043. - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
  1044. {
  1045. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1046. }
  1047. - (void)restClient:(DBRestClient *)client loadedAccountInfo:(DBAccountInfo *)info
  1048. {
  1049. NSString *account = [NSString stringWithFormat:@"%@ %@", [info email], typeCloudDropbox];
  1050. [CCCoreData deleteAccount:account];
  1051. // new account
  1052. [CCCoreData addAccount:account url:@"https://www.dropbox.com" user:[info email] password:nil uid:info.userId typeCloud:typeCloudDropbox];
  1053. TableAccount *tableAccount = [CCCoreData setActiveAccount:account];
  1054. if (tableAccount)
  1055. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  1056. NSString *uuid = [CCUtility getUUID];
  1057. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:uuid];
  1058. // update ManageAccount
  1059. [[NSNotificationCenter defaultCenter] postNotificationName:@"updateFormManageAccount" object:nil];
  1060. // Login correct
  1061. if ([passcode length] > 0 && [self.activeAccount length] > 0)
  1062. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginCorrect" object:nil];
  1063. }
  1064. #endif
  1065. #pragma --------------------------------------------------------------------------------------------
  1066. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1069. {
  1070. return YES;
  1071. }
  1072. // Method called from iOS system to send a file from other app.
  1073. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1074. {
  1075. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1076. NSLog(@"[LOG] the path is: %@", url.path);
  1077. #ifdef CC
  1078. /*************************************** DROPBOX *********************************/
  1079. if ([[DBSession sharedSession] handleOpenURL:url]) {
  1080. NSString *query = url.query;
  1081. if ([[url absoluteString] rangeOfString:@"cancel"].location == NSNotFound) {
  1082. NSDictionary *urlData = [DBSession parseURLParams:query];
  1083. NSString *uid = [urlData objectForKey:@"uid"];
  1084. if ([[[DBSession sharedSession] userIds] containsObject:uid]) {
  1085. self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession] userId:uid];
  1086. self.restClient.delegate = self;
  1087. [self.restClient loadAccountInfo];
  1088. }
  1089. } else {
  1090. // user cancelled the login
  1091. [[NSNotificationCenter defaultCenter] postNotificationName:@"messageLoginIncorrect" object:nil];
  1092. }
  1093. return YES;
  1094. }
  1095. /*********************************************************************************/
  1096. #endif
  1097. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1098. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1099. NSString *passcode = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  1100. if (self.activeAccount && [passcode length]) {
  1101. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1102. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1103. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1104. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1105. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1106. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1107. });
  1108. }
  1109. // remove from InBox
  1110. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1111. return YES;
  1112. }
  1113. #pragma --------------------------------------------------------------------------------------------
  1114. #pragma mark ===== UPGRADE =====
  1115. #pragma --------------------------------------------------------------------------------------------
  1116. - (void)upgrade
  1117. {
  1118. #ifdef DEBUG
  1119. // [CCCoreData flushTableGPS];
  1120. // [CCCoreData setGeoInformationLocalNull];
  1121. #endif
  1122. NSString *actualVersion = [CCUtility getVersionCryptoCloud];
  1123. /* ---------------------- UPGRADE VERSION ----------------------- */
  1124. if (([actualVersion compare:@"2.13" options:NSNumericSearch] == NSOrderedAscending)) {
  1125. [CCCoreData flushTableDirectoryAccount:nil];
  1126. [CCCoreData flushTableLocalFileAccount:nil];
  1127. [CCCoreData flushTableMetadataAccount:nil];
  1128. }
  1129. if (([actualVersion compare:@"2.15" options:NSNumericSearch] == NSOrderedAscending)) {
  1130. [CCCoreData flushTableGPS];
  1131. [CCCoreData setGeoInformationLocalNull];
  1132. }
  1133. }
  1134. @end