VLCDownloadViewController.m 17 KB

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