VLCDownloadViewController.m 17 KB

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