VLCDownloadViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  50. NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: [UIColor VLCLightTextColor]}];
  51. self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
  52. }
  53. [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) forState:UIControlStateNormal];
  54. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
  55. self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", nil);
  56. self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", nil), [[UIDevice currentDevice] model]];
  57. self.urlField.delegate = self;
  58. self.urlField.keyboardType = UIKeyboardTypeURL;
  59. self.progressContainer.hidden = YES;
  60. self.downloadsTable.hidden = YES;
  61. if (SYSTEM_RUNS_IOS7_OR_LATER)
  62. self.edgesForExtendedLayout = UIRectEdgeNone;
  63. }
  64. - (void)viewWillAppear:(BOOL)animated
  65. {
  66. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  67. if ([pasteboard containsPasteboardTypes:@[@"public.url"]])
  68. self.urlField.text = [[pasteboard valueForPasteboardType:@"public.url"] absoluteString];
  69. [self _updateUI];
  70. [super viewWillAppear:animated];
  71. }
  72. #pragma mark - UI interaction
  73. - (BOOL)shouldAutorotate
  74. {
  75. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  76. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  77. return NO;
  78. return YES;
  79. }
  80. - (IBAction)goBack:(id)sender
  81. {
  82. [self.view endEditing:YES];
  83. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  84. }
  85. - (IBAction)downloadAction:(id)sender
  86. {
  87. if ([self.urlField.text length] > 0) {
  88. NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
  89. if (([URLtoSave.scheme isEqualToString:@"http"] || [URLtoSave.scheme isEqualToString:@"https"] || [URLtoSave.scheme isEqualToString:@"ftp"])) {
  90. if ([URLtoSave.lastPathComponent isSupportedFormat] || [URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  91. [_currentDownloads addObject:URLtoSave];
  92. [_currentDownloadFilename addObject:@""];
  93. self.urlField.text = @"";
  94. [self.downloadsTable reloadData];
  95. [self _triggerNextDownload];
  96. } else {
  97. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  98. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), URLtoSave.lastPathComponent]
  99. delegate:self
  100. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  101. otherButtonTitles:nil];
  102. [alert show];
  103. }
  104. } else {
  105. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
  106. message:[NSString stringWithFormat:NSLocalizedString(@"SCHEME_NOT_SUPPORTED_LONG", nil), URLtoSave.scheme]
  107. delegate:self
  108. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  109. 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.firstObject 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.firstObject isEqualToString:@""]) {
  137. [_httpDownloader downloadFileFromURL:_currentDownloads.firstObject withFileName:_currentDownloadFilename.firstObject];
  138. _humanReadableFilename = [_currentDownloadFilename objectAtIndex:0];
  139. } else {
  140. [_httpDownloader downloadFileFromURL:_currentDownloads.firstObject];
  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.firstObject];
  151. _humanReadableFilename = [_currentDownloads.firstObject 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. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", nil)
  224. message:description
  225. delegate:self
  226. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  227. otherButtonTitles:nil];
  228. [alert show];
  229. }
  230. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  231. {
  232. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  233. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  234. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  235. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  236. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  237. }
  238. [self.progressView setProgress:percentage animated:YES];
  239. }
  240. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  241. {
  242. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  243. CGFloat smoothingFactor = 0.005;
  244. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  245. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  246. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  247. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  248. [formatter setDateFormat:@"HH:mm:ss"];
  249. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  250. NSString *remaingTime = [formatter stringFromDate:date];
  251. return remaingTime;
  252. }
  253. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  254. {
  255. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  256. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  257. string = [string stringByAppendingString:@"/s"];
  258. return string;
  259. }
  260. #pragma mark - ftp networking
  261. - (void)_downloadFTPFile:(NSURL *)URLToFile
  262. {
  263. if (_FTPDownloadRequest)
  264. return;
  265. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  266. _FTPDownloadRequest.delegate = self;
  267. _FTPDownloadRequest.passive = YES;
  268. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  269. NSString *directoryPath = searchPaths[0];
  270. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  271. _FTPDownloadRequest.downloadLocation = destinationURL;
  272. [_FTPDownloadRequest startWithFullURL:URLToFile];
  273. }
  274. - (void)requestStarted:(WRRequest *)request
  275. {
  276. [self downloadStarted];
  277. }
  278. - (void)requestCompleted:(WRRequest *)request
  279. {
  280. _FTPDownloadRequest = nil;
  281. [self downloadEnded];
  282. }
  283. - (void)requestFailed:(WRRequest *)request
  284. {
  285. _FTPDownloadRequest = nil;
  286. [self downloadEnded];
  287. VLCAlertView * alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), request.error.errorCode]
  288. message:request.error.message
  289. delegate:self
  290. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  291. otherButtonTitles:nil];
  292. [alert show];
  293. }
  294. #pragma mark - table view data source
  295. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  296. {
  297. return 1;
  298. }
  299. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  300. {
  301. NSUInteger count = _currentDownloads.count;
  302. self.downloadsTable.hidden = count > 0 ? NO : YES;
  303. return _currentDownloads.count;
  304. }
  305. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  306. {
  307. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  308. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  309. if (cell == nil) {
  310. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  311. cell.textLabel.textColor = [UIColor whiteColor];
  312. cell.detailTextLabel.textColor = [UIColor VLCLightTextColor];
  313. }
  314. NSInteger row = indexPath.row;
  315. if ([_currentDownloadFilename[row] isEqualToString:@""])
  316. cell.textLabel.text = [_currentDownloads[row] lastPathComponent];
  317. else
  318. cell.textLabel.text = [_currentDownloadFilename[row] lastPathComponent];
  319. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  320. return cell;
  321. }
  322. #pragma mark - table view delegate
  323. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  324. {
  325. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  326. }
  327. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  328. {
  329. return YES;
  330. }
  331. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  332. {
  333. if (editingStyle == UITableViewCellEditingStyleDelete) {
  334. [_currentDownloads removeObjectAtIndex:indexPath.row];
  335. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  336. [tableView reloadData];
  337. }
  338. }
  339. #pragma mark - communication with other VLC objects
  340. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  341. {
  342. [_currentDownloads addObject:aURL];
  343. if (!fileName)
  344. fileName = @"";
  345. [_currentDownloadFilename addObject:fileName];
  346. [self.downloadsTable reloadData];
  347. [self _triggerNextDownload];
  348. }
  349. #pragma mark - text view delegate
  350. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  351. {
  352. [self.urlField resignFirstResponder];
  353. return NO;
  354. }
  355. @end