AppDelegate.m 63 KB

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