VLCDownloadViewController.m 16 KB

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