VLCDownloadViewController.m 16 KB

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