VLCDownloadViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. #import "VLC-Swift.h"
  21. typedef NS_ENUM(NSUInteger, VLCDownloadScheme) {
  22. VLCDownloadSchemeNone,
  23. VLCDownloadSchemeHTTP,
  24. VLCDownloadSchemeFTP
  25. };
  26. @interface VLCDownloadViewController () <WRRequestDelegate, UITableViewDataSource, UITableViewDelegate, VLCHTTPFileDownloader, UITextFieldDelegate>
  27. {
  28. NSMutableArray *_currentDownloads;
  29. VLCDownloadScheme _currentDownloadType;
  30. NSString *_humanReadableFilename;
  31. NSMutableArray *_currentDownloadFilename;
  32. NSTimeInterval _startDL;
  33. NSString *_currentDownloadIdentifier;
  34. NSLayoutConstraint *_contentViewHeight;
  35. VLCHTTPFileDownloader *_httpDownloader;
  36. WRRequestDownload *_FTPDownloadRequest;
  37. NSTimeInterval _lastStatsUpdate;
  38. CGFloat _averageSpeed;
  39. UIBackgroundTaskIdentifier _backgroundTaskIdentifier;
  40. }
  41. @end
  42. @implementation VLCDownloadViewController
  43. + (instancetype)sharedInstance
  44. {
  45. static VLCDownloadViewController *sharedInstance = nil;
  46. static dispatch_once_t pred;
  47. dispatch_once(&pred, ^{
  48. sharedInstance = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
  49. });
  50. return sharedInstance;
  51. }
  52. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  53. {
  54. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  55. if (self){
  56. _currentDownloads = [[NSMutableArray alloc] init];
  57. _currentDownloadFilename = [[NSMutableArray alloc] init];
  58. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateForTheme) name:kVLCThemeDidChangeNotification object:nil];
  59. self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", comment:@"");
  60. }
  61. return self;
  62. }
  63. - (void)viewDidLoad
  64. {
  65. [super viewDidLoad];
  66. [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) forState:UIControlStateNormal];
  67. [self.downloadButton setAccessibilityIdentifier:@"Download"];
  68. self.downloadButton.layer.cornerRadius = 4.0;
  69. self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", nil), [[UIDevice currentDevice] model]];
  70. self.urlField.delegate = self;
  71. self.urlField.keyboardType = UIKeyboardTypeURL;
  72. self.progressContainer.hidden = YES;
  73. self.downloadsTable.hidden = YES;
  74. self.downloadsTable.separatorStyle = UITableViewCellSeparatorStyleNone;
  75. self.whatToDownloadHelpLabel.backgroundColor = [UIColor clearColor];
  76. _contentViewHeight = [_contentView.heightAnchor constraintEqualToConstant:0];
  77. _contentViewHeight.active = YES;
  78. [self updateContentViewHeightConstraint];
  79. self.edgesForExtendedLayout = UIRectEdgeNone;
  80. [self updateForTheme];
  81. }
  82. - (void)viewWillAppear:(BOOL)animated
  83. {
  84. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  85. if ([pasteboard containsPasteboardTypes:@[@"public.url"]]) {
  86. id pasteboardValue = [pasteboard valueForPasteboardType:@"public.url"];
  87. if ([pasteboardValue respondsToSelector:@selector(absoluteString)]) {
  88. self.urlField.text = [pasteboardValue absoluteString];
  89. }
  90. }
  91. [self _updateUI];
  92. [super viewWillAppear:animated];
  93. }
  94. - (void)updateForTheme
  95. {
  96. NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: PresentationTheme.current.colors.lightTextColor}];
  97. self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
  98. self.urlField.backgroundColor = PresentationTheme.current.colors.background;
  99. self.urlField.textColor = PresentationTheme.current.colors.cellTextColor;
  100. self.urlBorder.backgroundColor = PresentationTheme.current.colors.mediaCategorySeparatorColor;
  101. self.downloadsTable.backgroundColor = PresentationTheme.current.colors.background;
  102. self.view.backgroundColor = PresentationTheme.current.colors.background;
  103. self.downloadButton.backgroundColor = PresentationTheme.current.colors.orangeUI;
  104. self.whatToDownloadHelpLabel.textColor = PresentationTheme.current.colors.lightTextColor;
  105. self.progressContainer.backgroundColor = PresentationTheme.current.colors.background;
  106. self.currentDownloadLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  107. self.progressPercent.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  108. self.speedRate.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  109. self.timeDL.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  110. self.progressView.progressTintColor = PresentationTheme.current.colors.orangeUI;
  111. [self.downloadsTable reloadData];
  112. [self setNeedsStatusBarAppearanceUpdate];
  113. }
  114. - (UIStatusBarStyle)preferredStatusBarStyle
  115. {
  116. return PresentationTheme.current.colors.statusBarStyle;
  117. }
  118. - (void)viewWillDisappear:(BOOL)animated
  119. {
  120. [super viewWillDisappear:animated];
  121. [self.view endEditing:YES];
  122. }
  123. #pragma mark - UI interaction
  124. - (BOOL)shouldAutorotate
  125. {
  126. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  127. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  128. return NO;
  129. return YES;
  130. }
  131. - (IBAction)downloadAction:(id)sender
  132. {
  133. if ([self.urlField.text length] > 0) {
  134. NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
  135. if (![URLtoSave.lastPathComponent isSupportedFormat] && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  136. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  137. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), URLtoSave.lastPathComponent]
  138. viewController:self];
  139. return;
  140. }
  141. if (![URLtoSave.scheme isEqualToString:@"http"] & ![URLtoSave.scheme isEqualToString:@"https"] && ![URLtoSave.scheme isEqualToString:@"ftp"]) {
  142. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
  143. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"SCHEME_NOT_SUPPORTED_LONG", nil), URLtoSave.scheme]
  144. viewController:self];
  145. return;
  146. }
  147. [_currentDownloads addObject:URLtoSave];
  148. [_currentDownloadFilename addObject:@""];
  149. self.urlField.text = @"";
  150. [self.downloadsTable reloadData];
  151. [self updateContentViewHeightConstraint];
  152. [self _triggerNextDownload];
  153. }
  154. }
  155. - (void)_updateUI
  156. {
  157. _currentDownloadType != VLCDownloadSchemeNone ? [self downloadStartedWithIdentifier:_currentDownloadIdentifier] : [self downloadEndedWithIdentifier:_currentDownloadIdentifier];
  158. [self.downloadsTable reloadData];
  159. [self updateContentViewHeightConstraint];
  160. }
  161. - (void)updateContentViewHeightConstraint
  162. {
  163. _contentViewHeight.constant = _downloadFieldContainer.frame.size.height
  164. + _progressContainer.frame.size.height
  165. + _downloadsTable.contentSize.height;
  166. }
  167. - (VLCHTTPFileDownloader *)httpDownloader
  168. {
  169. if (!_httpDownloader) {
  170. _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
  171. _httpDownloader.delegate = self;
  172. }
  173. return _httpDownloader;
  174. }
  175. - (NSString *)detailText
  176. {
  177. return NSLocalizedString(@"DOWNLOADVC_DETAILTEXT", nil);
  178. }
  179. - (UIImage *)cellImage
  180. {
  181. return [UIImage imageNamed:@"Downloads"];
  182. }
  183. #pragma mark - Download management
  184. - (void)_startDownload
  185. {
  186. [_currentDownloads removeObjectAtIndex:0];
  187. [_currentDownloadFilename removeObjectAtIndex:0];
  188. [self _beginBackgroundDownload];
  189. [self _updateUI];
  190. _startDL = [NSDate timeIntervalSinceReferenceDate];
  191. }
  192. - (void)_downloadSchemeHttp
  193. {
  194. if (_currentDownloadIdentifier) {
  195. return;
  196. }
  197. _currentDownloadType = VLCDownloadSchemeHTTP;
  198. if (![_currentDownloadFilename.firstObject isEqualToString:@""]) {
  199. _humanReadableFilename = [[_currentDownloadFilename firstObject] stringByRemovingPercentEncoding];
  200. _currentDownloadIdentifier = [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject withFileName:_humanReadableFilename];
  201. } else {
  202. _currentDownloadIdentifier = [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject];
  203. _humanReadableFilename = [_currentDownloads.firstObject lastPathComponent];
  204. }
  205. [self _startDownload];
  206. }
  207. - (void)_downloadSchemeFtp
  208. {
  209. if (_FTPDownloadRequest) {
  210. return;
  211. }
  212. _currentDownloadType = VLCDownloadSchemeFTP;
  213. [self _downloadFTPFile:_currentDownloads.firstObject];
  214. _humanReadableFilename = [_currentDownloads.firstObject lastPathComponent];
  215. [self _startDownload];
  216. }
  217. - (void)_beginBackgroundDownload
  218. {
  219. if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  220. dispatch_block_t expirationHandler = ^{
  221. APLog(@"Downloads were interrupted after being in background too long, time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
  222. [[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTaskIdentifier];
  223. self->_backgroundTaskIdentifier = 0;
  224. };
  225. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCDownloader" expirationHandler:expirationHandler];
  226. if (_backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  227. APLog(@"Unable to download");
  228. }
  229. }
  230. }
  231. - (void)_triggerNextDownload
  232. {
  233. if ([_currentDownloads count] == 0) {
  234. _currentDownloadType = VLCDownloadSchemeNone;
  235. if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  236. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  237. _backgroundTaskIdentifier = 0;
  238. }
  239. return;
  240. }
  241. NSString *downloadScheme = [_currentDownloads.firstObject scheme];
  242. if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
  243. [self _downloadSchemeHttp];
  244. } else if ([downloadScheme isEqualToString:@"ftp"]) {
  245. [self _downloadSchemeFtp];
  246. } else {
  247. APLog(@"Unknown download scheme '%@'", downloadScheme);
  248. [_currentDownloads removeObjectAtIndex:0];
  249. _currentDownloadType = VLCDownloadSchemeNone;
  250. }
  251. }
  252. - (IBAction)cancelDownload:(id)sender
  253. {
  254. if (_currentDownloadType == VLCDownloadSchemeHTTP && self.httpDownloader.downloadInProgress) {
  255. [self.httpDownloader cancelDownloadWithIdentifier:_currentDownloadIdentifier];
  256. } else if (_currentDownloadType == VLCDownloadSchemeFTP && _FTPDownloadRequest) {
  257. NSURL *target = _FTPDownloadRequest.downloadLocation;
  258. [_FTPDownloadRequest destroy];
  259. [self requestCompleted:_FTPDownloadRequest];
  260. /* remove partially downloaded content */
  261. [[NSFileManager defaultManager] removeItemAtPath:target.path error:nil];
  262. }
  263. }
  264. #pragma mark - VLC HTTP Downloader delegate
  265. - (void)downloadStartedWithIdentifier:(NSString *)identifier
  266. {
  267. _currentDownloadIdentifier = identifier;
  268. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  269. [activityManager networkActivityStopped];
  270. [activityManager networkActivityStarted];
  271. self.currentDownloadLabel.text = _humanReadableFilename;
  272. self.progressView.progress = 0.;
  273. [self.progressPercent setText:@"0%"];
  274. [self.speedRate setText:@"0 Kb/s"];
  275. [self.timeDL setText:@"00:00:00"];
  276. self.progressContainer.hidden = NO;
  277. APLog(@"download started");
  278. }
  279. - (void)downloadEndedWithIdentifier:(NSString *)identifier
  280. {
  281. _currentDownloadIdentifier = nil;
  282. [[VLCActivityManager defaultManager] networkActivityStopped];
  283. _currentDownloadType = VLCDownloadSchemeNone;
  284. APLog(@"download ended");
  285. self.progressContainer.hidden = YES;
  286. [self _triggerNextDownload];
  287. }
  288. - (void)downloadFailedWithIdentifier:(NSString *)identifier errorDescription:(NSString *)description
  289. {
  290. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", nil)
  291. errorMessage:description
  292. viewController:self];
  293. }
  294. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize identifier:(NSString *)identifier
  295. {
  296. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  297. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  298. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  299. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  300. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  301. }
  302. [self.progressView setProgress:percentage animated:YES];
  303. }
  304. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  305. {
  306. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  307. CGFloat smoothingFactor = 0.005;
  308. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  309. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  310. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  311. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  312. [formatter setDateFormat:@"HH:mm:ss"];
  313. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  314. NSString *remaingTime = [formatter stringFromDate:date];
  315. return remaingTime;
  316. }
  317. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  318. {
  319. CGFloat timeInterval = [NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate;
  320. CGFloat speed = receivedDataSize / timeInterval;
  321. NSString *string = [NSByteCountFormatter stringFromByteCount:speed
  322. countStyle:NSByteCountFormatterCountStyleDecimal];
  323. string = [string stringByAppendingString:@"/s"];
  324. return string;
  325. }
  326. #pragma mark - ftp networking
  327. - (void)_downloadFTPFile:(NSURL *)URLToFile
  328. {
  329. if (_FTPDownloadRequest)
  330. return;
  331. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  332. _FTPDownloadRequest.delegate = self;
  333. _FTPDownloadRequest.passive = YES;
  334. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  335. NSString *directoryPath = searchPaths[0];
  336. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  337. _FTPDownloadRequest.downloadLocation = destinationURL;
  338. [_FTPDownloadRequest startWithFullURL:URLToFile];
  339. }
  340. - (void)requestStarted:(WRRequest *)request
  341. {
  342. [self downloadStartedWithIdentifier:request.fullURLString];
  343. }
  344. - (void)requestCompleted:(WRRequest *)request
  345. {
  346. _FTPDownloadRequest = nil;
  347. [self downloadEndedWithIdentifier:request.fullURLString];
  348. }
  349. - (void)requestFailed:(WRRequest *)request
  350. {
  351. _FTPDownloadRequest = nil;
  352. [self downloadEndedWithIdentifier:request.fullURLString];
  353. [VLCAlertViewController alertViewManagerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), request.error.errorCode]
  354. errorMessage:request.error.message
  355. viewController:self];
  356. }
  357. #pragma mark - table view data source
  358. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  359. {
  360. return 1;
  361. }
  362. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  363. {
  364. NSUInteger count = _currentDownloads.count;
  365. self.downloadsTable.hidden = count > 0 ? NO : YES;
  366. return _currentDownloads.count;
  367. }
  368. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  369. {
  370. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  371. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  372. if (cell == nil) {
  373. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  374. }
  375. NSInteger row = indexPath.row;
  376. if ([_currentDownloadFilename[row] isEqualToString:@""])
  377. cell.textLabel.text = [[_currentDownloads[row] lastPathComponent] stringByRemovingPercentEncoding];
  378. else
  379. cell.textLabel.text = [[_currentDownloadFilename[row] lastPathComponent] stringByRemovingPercentEncoding];
  380. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  381. cell.textLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  382. cell.detailTextLabel.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  383. return cell;
  384. }
  385. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  386. {
  387. return 60;
  388. }
  389. #pragma mark - table view delegate
  390. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  391. {
  392. cell.backgroundColor = PresentationTheme.current.colors.cellBackgroundA;
  393. }
  394. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  395. {
  396. return YES;
  397. }
  398. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  399. {
  400. if (editingStyle == UITableViewCellEditingStyleDelete) {
  401. [_currentDownloads removeObjectAtIndex:indexPath.row];
  402. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  403. [tableView reloadData];
  404. [self updateContentViewHeightConstraint];
  405. }
  406. }
  407. #pragma mark - communication with other VLC objects
  408. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  409. {
  410. [_currentDownloads addObject:aURL];
  411. if (!fileName)
  412. fileName = @"";
  413. [_currentDownloadFilename addObject:fileName];
  414. [self.downloadsTable reloadData];
  415. [self updateContentViewHeightConstraint];
  416. if (_currentDownloadType == VLCDownloadSchemeNone)
  417. [self _triggerNextDownload];
  418. }
  419. #pragma mark - text view delegate
  420. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  421. {
  422. [self.urlField resignFirstResponder];
  423. return NO;
  424. }
  425. @end