VLCDownloadViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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"])) {
  93. if ([URLtoSave.lastPathComponent isSupportedFormat] || [URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  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. if (!_FTPDownloadRequest) {
  144. _currentDownloadType = kVLCDownloadViaFTP;
  145. [self _downloadFTPFile:_currentDownloads[0]];
  146. _humanReadableFilename = [_currentDownloads[0] lastPathComponent];
  147. [_currentDownloads removeObjectAtIndex:0];
  148. [_currentDownloadFilename removeObjectAtIndex:0];
  149. }
  150. downloadWasStarted = YES;
  151. } else
  152. APLog(@"Unknown download scheme '%@'", downloadScheme);
  153. if (downloadWasStarted) {
  154. if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  155. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCDownloader" expirationHandler:^{
  156. APLog(@"Downloads were interrupted after being in background too long, time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
  157. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  158. _backgroundTaskIdentifier = 0;
  159. }];
  160. }
  161. }
  162. [self _updateUI];
  163. } else {
  164. _currentDownloadType = 0;
  165. if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  166. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  167. _backgroundTaskIdentifier = 0;
  168. }
  169. }
  170. }
  171. - (IBAction)cancelDownload:(id)sender
  172. {
  173. if (_currentDownloadType == kVLCDownloadViaHTTP) {
  174. if (_httpDownloader.downloadInProgress)
  175. [_httpDownloader cancelDownload];
  176. } else if (_currentDownloadType == kVLCDownloadViaFTP) {
  177. if (_FTPDownloadRequest) {
  178. NSURL *target = _FTPDownloadRequest.downloadLocation;
  179. [_FTPDownloadRequest destroy];
  180. [self requestCompleted:_FTPDownloadRequest];
  181. /* remove partially downloaded content */
  182. NSFileManager *fileManager = [NSFileManager defaultManager];
  183. if ([fileManager fileExistsAtPath:target.path])
  184. [fileManager removeItemAtPath:target.path error:nil];
  185. }
  186. }
  187. }
  188. #pragma mark - VLC HTTP Downloader delegate
  189. - (void)downloadStarted
  190. {
  191. [self.activityIndicator stopAnimating];
  192. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStopped];
  193. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  194. self.currentDownloadLabel.text = _humanReadableFilename;
  195. self.progressView.progress = 0.;
  196. [self.progressPercent setText:@"0%%"];
  197. [self.speedRate setText:@"0 Kb/s"];
  198. [self.timeDL setText:@"00:00:00"];
  199. _startDL = [NSDate timeIntervalSinceReferenceDate];
  200. self.progressContainer.hidden = NO;
  201. APLog(@"download started");
  202. }
  203. - (void)downloadEnded
  204. {
  205. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStopped];
  206. _currentDownloadType = 0;
  207. APLog(@"download ended");
  208. self.progressContainer.hidden = YES;
  209. [self _triggerNextDownload];
  210. }
  211. - (void)downloadFailedWithErrorDescription:(NSString *)description
  212. {
  213. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", @"") message:description delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
  214. [alert show];
  215. }
  216. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  217. {
  218. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  219. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  220. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  221. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  222. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  223. }
  224. [self.progressView setProgress:percentage animated:YES];
  225. }
  226. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  227. {
  228. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  229. CGFloat smoothingFactor = 0.005;
  230. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  231. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  232. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  233. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  234. [formatter setDateFormat:@"HH:mm:ss"];
  235. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  236. NSString *remaingTime = [formatter stringFromDate:date];
  237. return remaingTime;
  238. }
  239. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  240. {
  241. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  242. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  243. string = [string stringByAppendingString:@"/s"];
  244. return string;
  245. }
  246. #pragma mark - ftp networking
  247. - (void)_downloadFTPFile:(NSURL *)URLToFile
  248. {
  249. if (_FTPDownloadRequest)
  250. return;
  251. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  252. _FTPDownloadRequest.delegate = self;
  253. _FTPDownloadRequest.passive = YES;
  254. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  255. NSString *directoryPath = searchPaths[0];
  256. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  257. _FTPDownloadRequest.downloadLocation = destinationURL;
  258. [_FTPDownloadRequest startWithFullURL:URLToFile];
  259. }
  260. - (void)requestStarted:(WRRequest *)request
  261. {
  262. [self downloadStarted];
  263. }
  264. - (void)requestCompleted:(WRRequest *)request
  265. {
  266. _FTPDownloadRequest = nil;
  267. [self downloadEnded];
  268. }
  269. - (void)requestFailed:(WRRequest *)request
  270. {
  271. _FTPDownloadRequest = nil;
  272. [self downloadEnded];
  273. 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];
  274. [alert show];
  275. }
  276. #pragma mark - table view data source
  277. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  278. {
  279. return 1;
  280. }
  281. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  282. {
  283. NSUInteger count = _currentDownloads.count;
  284. self.downloadsTable.hidden = count > 0 ? NO : YES;
  285. return _currentDownloads.count;
  286. }
  287. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  288. {
  289. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  290. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  291. if (cell == nil) {
  292. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  293. cell.textLabel.textColor = [UIColor whiteColor];
  294. cell.detailTextLabel.textColor = [UIColor colorWithWhite:.72 alpha:1.];
  295. }
  296. NSInteger row = indexPath.row;
  297. if ([_currentDownloadFilename[row] isEqualToString:@""])
  298. cell.textLabel.text = [_currentDownloads[row] lastPathComponent];
  299. else
  300. cell.textLabel.text = [_currentDownloadFilename[row] lastPathComponent];
  301. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  302. return cell;
  303. }
  304. #pragma mark - table view delegate
  305. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  306. {
  307. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  308. }
  309. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  310. {
  311. return YES;
  312. }
  313. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  314. {
  315. if (editingStyle == UITableViewCellEditingStyleDelete) {
  316. [_currentDownloads removeObjectAtIndex:indexPath.row];
  317. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  318. [tableView reloadData];
  319. }
  320. }
  321. #pragma mark - communication with other VLC objects
  322. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  323. {
  324. [_currentDownloads addObject:aURL];
  325. if (!fileName)
  326. fileName = @"";
  327. [_currentDownloadFilename addObject:fileName];
  328. [self.downloadsTable reloadData];
  329. [self _triggerNextDownload];
  330. }
  331. #pragma mark - text view delegate
  332. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  333. {
  334. [self.urlField resignFirstResponder];
  335. return NO;
  336. }
  337. @end