AppDelegate.m 61 KB

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