VLCDownloadViewController.m 16 KB

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