VLCDownloadViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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_iOS-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. }
  104. - (void)viewWillDisappear:(BOOL)animated
  105. {
  106. [super viewWillDisappear:animated];
  107. [self.view endEditing:YES];
  108. }
  109. #pragma mark - UI interaction
  110. - (BOOL)shouldAutorotate
  111. {
  112. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  113. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  114. return NO;
  115. return YES;
  116. }
  117. - (IBAction)downloadAction:(id)sender
  118. {
  119. if ([self.urlField.text length] > 0) {
  120. NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
  121. if (![URLtoSave.lastPathComponent isSupportedFormat] && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  122. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  123. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), URLtoSave.lastPathComponent]
  124. delegate:self
  125. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  126. otherButtonTitles:nil];
  127. [alert show];
  128. return;
  129. }
  130. if (![URLtoSave.scheme isEqualToString:@"http"] & ![URLtoSave.scheme isEqualToString:@"https"] && ![URLtoSave.scheme isEqualToString:@"ftp"]) {
  131. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
  132. message:[NSString stringWithFormat:NSLocalizedString(@"SCHEME_NOT_SUPPORTED_LONG", nil), URLtoSave.scheme]
  133. delegate:self
  134. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  135. otherButtonTitles:nil];
  136. [alert show];
  137. return;
  138. }
  139. [_currentDownloads addObject:URLtoSave];
  140. [_currentDownloadFilename addObject:@""];
  141. self.urlField.text = @"";
  142. [self.downloadsTable reloadData];
  143. [self _triggerNextDownload];
  144. }
  145. }
  146. - (void)_updateUI
  147. {
  148. _currentDownloadType != VLCDownloadSchemeNone ? [self downloadStarted] : [self downloadEnded];
  149. [self.downloadsTable reloadData];
  150. }
  151. - (VLCHTTPFileDownloader *)httpDownloader
  152. {
  153. if (!_httpDownloader) {
  154. _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
  155. _httpDownloader.delegate = self;
  156. }
  157. return _httpDownloader;
  158. }
  159. - (NSString *)detailText
  160. {
  161. return NSLocalizedString(@"DOWNLOADVC_DETAILTEXT", nil);
  162. }
  163. - (UIImage *)cellImage
  164. {
  165. return [UIImage imageNamed:@"Downloads"];
  166. }
  167. #pragma mark - Download management
  168. - (void)_startDownload
  169. {
  170. [_currentDownloads removeObjectAtIndex:0];
  171. [_currentDownloadFilename removeObjectAtIndex:0];
  172. [self _beginBackgroundDownload];
  173. [self _updateUI];
  174. }
  175. - (void)_downloadSchemeHttp
  176. {
  177. if (self.httpDownloader.downloadInProgress) {
  178. return;
  179. }
  180. _currentDownloadType = VLCDownloadSchemeHTTP;
  181. if (![_currentDownloadFilename.firstObject isEqualToString:@""]) {
  182. _humanReadableFilename = [[_currentDownloadFilename firstObject] stringByRemovingPercentEncoding];
  183. [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject withFileName:_humanReadableFilename];
  184. } else {
  185. [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject];
  186. _humanReadableFilename = self.httpDownloader.userReadableDownloadName;
  187. }
  188. [self _startDownload];
  189. }
  190. - (void)_downloadSchemeFtp
  191. {
  192. if (_FTPDownloadRequest) {
  193. return;
  194. }
  195. _currentDownloadType = VLCDownloadSchemeFTP;
  196. [self _downloadFTPFile:_currentDownloads.firstObject];
  197. _humanReadableFilename = [_currentDownloads.firstObject lastPathComponent];
  198. [self _startDownload];
  199. }
  200. - (void)_beginBackgroundDownload
  201. {
  202. if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  203. dispatch_block_t expirationHandler = ^{
  204. APLog(@"Downloads were interrupted after being in background too long, time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
  205. [[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTaskIdentifier];
  206. self->_backgroundTaskIdentifier = 0;
  207. };
  208. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCDownloader" expirationHandler:expirationHandler];
  209. if (_backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  210. APLog(@"Unable to download");
  211. }
  212. }
  213. }
  214. - (void)_triggerNextDownload
  215. {
  216. if ([_currentDownloads count] == 0) {
  217. _currentDownloadType = VLCDownloadSchemeNone;
  218. if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  219. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  220. _backgroundTaskIdentifier = 0;
  221. }
  222. return;
  223. }
  224. [self.activityIndicator startAnimating];
  225. NSString *downloadScheme = [_currentDownloads.firstObject scheme];
  226. if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
  227. [self _downloadSchemeHttp];
  228. } else if ([downloadScheme isEqualToString:@"ftp"]) {
  229. [self _downloadSchemeFtp];
  230. } else {
  231. APLog(@"Unknown download scheme '%@'", downloadScheme);
  232. [_currentDownloads removeObjectAtIndex:0];
  233. _currentDownloadType = VLCDownloadSchemeNone;
  234. }
  235. }
  236. - (IBAction)cancelDownload:(id)sender
  237. {
  238. if (_currentDownloadType == VLCDownloadSchemeHTTP && self.httpDownloader.downloadInProgress) {
  239. [self.httpDownloader cancelDownload];
  240. } else if (_currentDownloadType == VLCDownloadSchemeFTP && _FTPDownloadRequest) {
  241. NSURL *target = _FTPDownloadRequest.downloadLocation;
  242. [_FTPDownloadRequest destroy];
  243. [self requestCompleted:_FTPDownloadRequest];
  244. /* remove partially downloaded content */
  245. [[NSFileManager defaultManager] removeItemAtPath:target.path error:nil];
  246. }
  247. }
  248. #pragma mark - VLC HTTP Downloader delegate
  249. - (void)downloadStarted
  250. {
  251. [self.activityIndicator stopAnimating];
  252. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  253. [activityManager networkActivityStopped];
  254. [activityManager networkActivityStarted];
  255. self.currentDownloadLabel.text = _humanReadableFilename;
  256. self.progressView.progress = 0.;
  257. [self.progressPercent setText:@"0%%"];
  258. [self.speedRate setText:@"0 Kb/s"];
  259. [self.timeDL setText:@"00:00:00"];
  260. _startDL = [NSDate timeIntervalSinceReferenceDate];
  261. self.progressContainer.hidden = NO;
  262. APLog(@"download started");
  263. }
  264. - (void)downloadEnded
  265. {
  266. [[VLCActivityManager defaultManager] networkActivityStopped];
  267. _currentDownloadType = VLCDownloadSchemeNone;
  268. APLog(@"download ended");
  269. self.progressContainer.hidden = YES;
  270. [self _triggerNextDownload];
  271. }
  272. - (void)downloadFailedWithErrorDescription:(NSString *)description
  273. {
  274. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", nil)
  275. message:description
  276. delegate:self
  277. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  278. otherButtonTitles:nil];
  279. [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
  280. }
  281. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  282. {
  283. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  284. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  285. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  286. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  287. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  288. }
  289. [self.progressView setProgress:percentage animated:YES];
  290. }
  291. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  292. {
  293. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  294. CGFloat smoothingFactor = 0.005;
  295. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  296. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  297. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  298. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  299. [formatter setDateFormat:@"HH:mm:ss"];
  300. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  301. NSString *remaingTime = [formatter stringFromDate:date];
  302. return remaingTime;
  303. }
  304. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  305. {
  306. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  307. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  308. string = [string stringByAppendingString:@"/s"];
  309. return string;
  310. }
  311. #pragma mark - ftp networking
  312. - (void)_downloadFTPFile:(NSURL *)URLToFile
  313. {
  314. if (_FTPDownloadRequest)
  315. return;
  316. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  317. _FTPDownloadRequest.delegate = self;
  318. _FTPDownloadRequest.passive = YES;
  319. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  320. NSString *directoryPath = searchPaths[0];
  321. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  322. _FTPDownloadRequest.downloadLocation = destinationURL;
  323. [_FTPDownloadRequest startWithFullURL:URLToFile];
  324. }
  325. - (void)requestStarted:(WRRequest *)request
  326. {
  327. [self downloadStarted];
  328. }
  329. - (void)requestCompleted:(WRRequest *)request
  330. {
  331. _FTPDownloadRequest = nil;
  332. [self downloadEnded];
  333. }
  334. - (void)requestFailed:(WRRequest *)request
  335. {
  336. _FTPDownloadRequest = nil;
  337. [self downloadEnded];
  338. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), request.error.errorCode]
  339. message:request.error.message
  340. delegate:self
  341. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  342. otherButtonTitles:nil];
  343. [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
  344. }
  345. #pragma mark - table view data source
  346. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  347. {
  348. return 1;
  349. }
  350. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  351. {
  352. NSUInteger count = _currentDownloads.count;
  353. self.downloadsTable.hidden = count > 0 ? NO : YES;
  354. return _currentDownloads.count;
  355. }
  356. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  357. {
  358. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  359. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  360. if (cell == nil) {
  361. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  362. cell.textLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  363. cell.detailTextLabel.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  364. }
  365. NSInteger row = indexPath.row;
  366. if ([_currentDownloadFilename[row] isEqualToString:@""])
  367. cell.textLabel.text = [[_currentDownloads[row] lastPathComponent] stringByRemovingPercentEncoding];
  368. else
  369. cell.textLabel.text = [[_currentDownloadFilename[row] lastPathComponent] stringByRemovingPercentEncoding];
  370. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  371. return cell;
  372. }
  373. #pragma mark - table view delegate
  374. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  375. {
  376. cell.backgroundColor = (indexPath.row % 2 == 0)? PresentationTheme.current.colors.cellBackgroundA : PresentationTheme.current.colors.cellBackgroundB;
  377. }
  378. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  379. {
  380. return YES;
  381. }
  382. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  383. {
  384. if (editingStyle == UITableViewCellEditingStyleDelete) {
  385. [_currentDownloads removeObjectAtIndex:indexPath.row];
  386. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  387. [tableView reloadData];
  388. }
  389. }
  390. #pragma mark - communication with other VLC objects
  391. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  392. {
  393. [_currentDownloads addObject:aURL];
  394. if (!fileName)
  395. fileName = @"";
  396. [_currentDownloadFilename addObject:fileName];
  397. [self.downloadsTable reloadData];
  398. [self _triggerNextDownload];
  399. }
  400. #pragma mark - text view delegate
  401. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  402. {
  403. [self.urlField resignFirstResponder];
  404. return NO;
  405. }
  406. @end