VLCDownloadViewController.m 17 KB

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