VLCDownloadViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*****************************************************************************
  2. * VLCDownloadViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Pierre Sagaspe <pierre.sagaspe # me.com>
  11. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCDownloadViewController.h"
  15. #import "VLCHTTPFileDownloader.h"
  16. #import "VLCActivityManager.h"
  17. #import "WhiteRaccoon.h"
  18. #import "NSString+SupportedMedia.h"
  19. #import "VLCHTTPFileDownloader.h"
  20. #import "VLC-Swift.h"
  21. typedef NS_ENUM(NSUInteger, VLCDownloadScheme) {
  22. VLCDownloadSchemeNone,
  23. VLCDownloadSchemeHTTP,
  24. VLCDownloadSchemeFTP
  25. };
  26. @interface VLCDownloadViewController () <WRRequestDelegate, UITableViewDataSource, UITableViewDelegate, VLCHTTPFileDownloader, UITextFieldDelegate>
  27. {
  28. NSMutableArray *_currentDownloads;
  29. VLCDownloadScheme _currentDownloadType;
  30. NSString *_humanReadableFilename;
  31. NSMutableArray *_currentDownloadFilename;
  32. NSTimeInterval _startDL;
  33. VLCHTTPFileDownloader *_httpDownloader;
  34. WRRequestDownload *_FTPDownloadRequest;
  35. NSTimeInterval _lastStatsUpdate;
  36. CGFloat _averageSpeed;
  37. UIBackgroundTaskIdentifier _backgroundTaskIdentifier;
  38. }
  39. @end
  40. @implementation VLCDownloadViewController
  41. + (instancetype)sharedInstance
  42. {
  43. static VLCDownloadViewController *sharedInstance = nil;
  44. static dispatch_once_t pred;
  45. dispatch_once(&pred, ^{
  46. sharedInstance = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
  47. });
  48. return sharedInstance;
  49. }
  50. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  51. {
  52. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  53. if (self){
  54. _currentDownloads = [[NSMutableArray alloc] init];
  55. _currentDownloadFilename = [[NSMutableArray alloc] init];
  56. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateForTheme) name:kVLCThemeDidChangeNotification object:nil];
  57. self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", comment:@"");
  58. }
  59. return self;
  60. }
  61. - (void)viewDidLoad
  62. {
  63. [super viewDidLoad];
  64. [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) forState:UIControlStateNormal];
  65. [self.downloadButton setAccessibilityIdentifier:@"Download"];
  66. self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", nil), [[UIDevice currentDevice] model]];
  67. self.urlField.delegate = self;
  68. self.urlField.keyboardType = UIKeyboardTypeURL;
  69. self.progressContainer.hidden = YES;
  70. self.downloadsTable.hidden = YES;
  71. self.whatToDownloadHelpLabel.backgroundColor = [UIColor clearColor];
  72. self.edgesForExtendedLayout = UIRectEdgeNone;
  73. [self updateForTheme];
  74. }
  75. - (void)viewWillAppear:(BOOL)animated
  76. {
  77. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  78. if ([pasteboard containsPasteboardTypes:@[@"public.url"]]) {
  79. id pasteboardValue = [pasteboard valueForPasteboardType:@"public.url"];
  80. if ([pasteboardValue respondsToSelector:@selector(absoluteString)]) {
  81. self.urlField.text = [pasteboardValue absoluteString];
  82. }
  83. }
  84. [self _updateUI];
  85. [super viewWillAppear:animated];
  86. }
  87. - (void)updateForTheme
  88. {
  89. NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: PresentationTheme.current.colors.lightTextColor}];
  90. self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
  91. self.urlField.backgroundColor = PresentationTheme.current.colors.cellBackgroundB;
  92. self.urlField.textColor = PresentationTheme.current.colors.cellTextColor;
  93. self.downloadsTable.backgroundColor = PresentationTheme.current.colors.background;
  94. self.view.backgroundColor = PresentationTheme.current.colors.background;
  95. self.downloadButton.backgroundColor = PresentationTheme.current.colors.orangeUI;
  96. self.whatToDownloadHelpLabel.textColor = PresentationTheme.current.colors.lightTextColor;
  97. self.progressContainer.backgroundColor = PresentationTheme.current.colors.cellBackgroundB;
  98. self.currentDownloadLabel.textColor = PresentationTheme.current.colors.cellBackgroundB;
  99. self.progressPercent.textColor = PresentationTheme.current.colors.cellBackgroundB;
  100. self.speedRate.textColor = PresentationTheme.current.colors.cellBackgroundB;
  101. self.timeDL.textColor = PresentationTheme.current.colors.cellTextColor;
  102. [self.downloadsTable reloadData];
  103. [self setNeedsStatusBarAppearanceUpdate];
  104. }
  105. - (UIStatusBarStyle)preferredStatusBarStyle
  106. {
  107. return PresentationTheme.current.colors.statusBarStyle;
  108. }
  109. - (void)viewWillDisappear:(BOOL)animated
  110. {
  111. [super viewWillDisappear:animated];
  112. [self.view endEditing:YES];
  113. }
  114. #pragma mark - UI interaction
  115. - (BOOL)shouldAutorotate
  116. {
  117. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  118. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  119. return NO;
  120. return YES;
  121. }
  122. - (IBAction)downloadAction:(id)sender
  123. {
  124. if ([self.urlField.text length] > 0) {
  125. NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
  126. if (![URLtoSave.lastPathComponent isSupportedFormat] && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  127. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  128. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), URLtoSave.lastPathComponent]
  129. viewController:self];
  130. return;
  131. }
  132. if (![URLtoSave.scheme isEqualToString:@"http"] & ![URLtoSave.scheme isEqualToString:@"https"] && ![URLtoSave.scheme isEqualToString:@"ftp"]) {
  133. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
  134. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"SCHEME_NOT_SUPPORTED_LONG", nil), URLtoSave.scheme]
  135. viewController:self];
  136. return;
  137. }
  138. [_currentDownloads addObject:URLtoSave];
  139. [_currentDownloadFilename addObject:@""];
  140. self.urlField.text = @"";
  141. [self.downloadsTable reloadData];
  142. [self _triggerNextDownload];
  143. }
  144. }
  145. - (void)_updateUI
  146. {
  147. _currentDownloadType != VLCDownloadSchemeNone ? [self downloadStarted] : [self downloadEnded];
  148. [self.downloadsTable reloadData];
  149. }
  150. - (VLCHTTPFileDownloader *)httpDownloader
  151. {
  152. if (!_httpDownloader) {
  153. _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
  154. _httpDownloader.delegate = self;
  155. }
  156. return _httpDownloader;
  157. }
  158. - (NSString *)detailText
  159. {
  160. return NSLocalizedString(@"DOWNLOADVC_DETAILTEXT", nil);
  161. }
  162. - (UIImage *)cellImage
  163. {
  164. return [UIImage imageNamed:@"Downloads"];
  165. }
  166. #pragma mark - Download management
  167. - (void)_startDownload
  168. {
  169. [_currentDownloads removeObjectAtIndex:0];
  170. [_currentDownloadFilename removeObjectAtIndex:0];
  171. [self _beginBackgroundDownload];
  172. [self _updateUI];
  173. }
  174. - (void)_downloadSchemeHttp
  175. {
  176. if (self.httpDownloader.downloadInProgress) {
  177. return;
  178. }
  179. _currentDownloadType = VLCDownloadSchemeHTTP;
  180. if (![_currentDownloadFilename.firstObject isEqualToString:@""]) {
  181. _humanReadableFilename = [[_currentDownloadFilename firstObject] stringByRemovingPercentEncoding];
  182. [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject withFileName:_humanReadableFilename];
  183. } else {
  184. [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject];
  185. _humanReadableFilename = self.httpDownloader.userReadableDownloadName;
  186. }
  187. [self _startDownload];
  188. }
  189. - (void)_downloadSchemeFtp
  190. {
  191. if (_FTPDownloadRequest) {
  192. return;
  193. }
  194. _currentDownloadType = VLCDownloadSchemeFTP;
  195. [self _downloadFTPFile:_currentDownloads.firstObject];
  196. _humanReadableFilename = [_currentDownloads.firstObject lastPathComponent];
  197. [self _startDownload];
  198. }
  199. - (void)_beginBackgroundDownload
  200. {
  201. if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  202. dispatch_block_t expirationHandler = ^{
  203. APLog(@"Downloads were interrupted after being in background too long, time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
  204. [[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTaskIdentifier];
  205. self->_backgroundTaskIdentifier = 0;
  206. };
  207. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCDownloader" expirationHandler:expirationHandler];
  208. if (_backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  209. APLog(@"Unable to download");
  210. }
  211. }
  212. }
  213. - (void)_triggerNextDownload
  214. {
  215. if ([_currentDownloads count] == 0) {
  216. _currentDownloadType = VLCDownloadSchemeNone;
  217. if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  218. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  219. _backgroundTaskIdentifier = 0;
  220. }
  221. return;
  222. }
  223. [self.activityIndicator startAnimating];
  224. NSString *downloadScheme = [_currentDownloads.firstObject scheme];
  225. if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
  226. [self _downloadSchemeHttp];
  227. } else if ([downloadScheme isEqualToString:@"ftp"]) {
  228. [self _downloadSchemeFtp];
  229. } else {
  230. APLog(@"Unknown download scheme '%@'", downloadScheme);
  231. [_currentDownloads removeObjectAtIndex:0];
  232. _currentDownloadType = VLCDownloadSchemeNone;
  233. }
  234. }
  235. - (IBAction)cancelDownload:(id)sender
  236. {
  237. if (_currentDownloadType == VLCDownloadSchemeHTTP && self.httpDownloader.downloadInProgress) {
  238. [self.httpDownloader cancelDownload];
  239. } else if (_currentDownloadType == VLCDownloadSchemeFTP && _FTPDownloadRequest) {
  240. NSURL *target = _FTPDownloadRequest.downloadLocation;
  241. [_FTPDownloadRequest destroy];
  242. [self requestCompleted:_FTPDownloadRequest];
  243. /* remove partially downloaded content */
  244. [[NSFileManager defaultManager] removeItemAtPath:target.path error:nil];
  245. }
  246. }
  247. #pragma mark - VLC HTTP Downloader delegate
  248. - (void)downloadStarted
  249. {
  250. [self.activityIndicator stopAnimating];
  251. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  252. [activityManager networkActivityStopped];
  253. [activityManager networkActivityStarted];
  254. self.currentDownloadLabel.text = _humanReadableFilename;
  255. self.progressView.progress = 0.;
  256. [self.progressPercent setText:@"0%%"];
  257. [self.speedRate setText:@"0 Kb/s"];
  258. [self.timeDL setText:@"00:00:00"];
  259. _startDL = [NSDate timeIntervalSinceReferenceDate];
  260. self.progressContainer.hidden = NO;
  261. APLog(@"download started");
  262. }
  263. - (void)downloadEnded
  264. {
  265. [[VLCActivityManager defaultManager] networkActivityStopped];
  266. _currentDownloadType = VLCDownloadSchemeNone;
  267. APLog(@"download ended");
  268. self.progressContainer.hidden = YES;
  269. [self _triggerNextDownload];
  270. }
  271. - (void)downloadFailedWithErrorDescription:(NSString *)description
  272. {
  273. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
  274. errorMessage:description
  275. viewController:self];
  276. }
  277. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  278. {
  279. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  280. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  281. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  282. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  283. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  284. }
  285. [self.progressView setProgress:percentage animated:YES];
  286. }
  287. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  288. {
  289. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  290. CGFloat smoothingFactor = 0.005;
  291. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  292. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  293. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  294. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  295. [formatter setDateFormat:@"HH:mm:ss"];
  296. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  297. NSString *remaingTime = [formatter stringFromDate:date];
  298. return remaingTime;
  299. }
  300. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  301. {
  302. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  303. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  304. string = [string stringByAppendingString:@"/s"];
  305. return string;
  306. }
  307. #pragma mark - ftp networking
  308. - (void)_downloadFTPFile:(NSURL *)URLToFile
  309. {
  310. if (_FTPDownloadRequest)
  311. return;
  312. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  313. _FTPDownloadRequest.delegate = self;
  314. _FTPDownloadRequest.passive = YES;
  315. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  316. NSString *directoryPath = searchPaths[0];
  317. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  318. _FTPDownloadRequest.downloadLocation = destinationURL;
  319. [_FTPDownloadRequest startWithFullURL:URLToFile];
  320. }
  321. - (void)requestStarted:(WRRequest *)request
  322. {
  323. [self downloadStarted];
  324. }
  325. - (void)requestCompleted:(WRRequest *)request
  326. {
  327. _FTPDownloadRequest = nil;
  328. [self downloadEnded];
  329. }
  330. - (void)requestFailed:(WRRequest *)request
  331. {
  332. _FTPDownloadRequest = nil;
  333. [self downloadEnded];
  334. [VLCAlertViewController alertViewManagerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), request.error.errorCode]
  335. errorMessage:request.error.message
  336. viewController:self];
  337. }
  338. #pragma mark - table view data source
  339. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  340. {
  341. return 1;
  342. }
  343. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  344. {
  345. NSUInteger count = _currentDownloads.count;
  346. self.downloadsTable.hidden = count > 0 ? NO : YES;
  347. return _currentDownloads.count;
  348. }
  349. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  350. {
  351. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  352. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  353. if (cell == nil) {
  354. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  355. cell.textLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  356. cell.detailTextLabel.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  357. }
  358. NSInteger row = indexPath.row;
  359. if ([_currentDownloadFilename[row] isEqualToString:@""])
  360. cell.textLabel.text = [[_currentDownloads[row] lastPathComponent] stringByRemovingPercentEncoding];
  361. else
  362. cell.textLabel.text = [[_currentDownloadFilename[row] lastPathComponent] stringByRemovingPercentEncoding];
  363. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  364. return cell;
  365. }
  366. #pragma mark - table view delegate
  367. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  368. {
  369. cell.backgroundColor = (indexPath.row % 2 == 0)? PresentationTheme.current.colors.cellBackgroundA : PresentationTheme.current.colors.cellBackgroundB;
  370. }
  371. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  372. {
  373. return YES;
  374. }
  375. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  376. {
  377. if (editingStyle == UITableViewCellEditingStyleDelete) {
  378. [_currentDownloads removeObjectAtIndex:indexPath.row];
  379. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  380. [tableView reloadData];
  381. }
  382. }
  383. #pragma mark - communication with other VLC objects
  384. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  385. {
  386. [_currentDownloads addObject:aURL];
  387. if (!fileName)
  388. fileName = @"";
  389. [_currentDownloadFilename addObject:fileName];
  390. [self.downloadsTable reloadData];
  391. [self _triggerNextDownload];
  392. }
  393. #pragma mark - text view delegate
  394. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  395. {
  396. [self.urlField resignFirstResponder];
  397. return NO;
  398. }
  399. @end