VLCDownloadViewController.m 14 KB

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