VLCDownloadViewController.m 17 KB

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