VLCDownloadViewController.m 16 KB

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