VLCDownloadViewController.m 15 KB

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