VLCDownloadViewController.m 16 KB

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