VLCDownloadViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. //
  2. // VLCDownloadViewController.m
  3. // VLC for iOS
  4. //
  5. // Created by Felix Paul Kühne on 16.06.13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCDownloadViewController.h"
  11. #import "VLCHTTPFileDownloader.h"
  12. #import "VLCAppDelegate.h"
  13. #import "UIBarButtonItem+Theme.h"
  14. #import "WhiteRaccoon.h"
  15. #import "NSString+SupportedMedia.h"
  16. #import "VLCHTTPFileDownloader.h"
  17. #define kVLCDownloadViaHTTP 1
  18. #define kVLCDownloadViaFTP 2
  19. @interface VLCDownloadViewController () <WRRequestDelegate, UITableViewDataSource, UITableViewDelegate, VLCHTTPFileDownloader, UITextFieldDelegate>
  20. {
  21. NSMutableArray *_currentDownloads;
  22. NSUInteger _currentDownloadType;
  23. NSString *_humanReadableFilename;
  24. NSMutableArray *_currentDownloadFilename;
  25. NSTimeInterval _startDL;
  26. VLCHTTPFileDownloader *_httpDownloader;
  27. WRRequestDownload *_FTPDownloadRequest;
  28. }
  29. @end
  30. @implementation VLCDownloadViewController
  31. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  32. {
  33. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  34. if (self){
  35. _currentDownloads = [[NSMutableArray alloc] init];
  36. _currentDownloadFilename = [[NSMutableArray alloc] init];
  37. }
  38. return self;
  39. }
  40. - (void)viewDidLoad
  41. {
  42. [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD",@"") forState:UIControlStateNormal];
  43. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
  44. self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", @"");
  45. self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", @""), [[UIDevice currentDevice] model]];
  46. self.urlField.delegate = self;
  47. self.urlField.keyboardType = UIKeyboardTypeURL;
  48. [super viewDidLoad];
  49. }
  50. - (void)viewWillAppear:(BOOL)animated
  51. {
  52. self.navigationController.navigationBar.translucent = NO;
  53. if ([[UIPasteboard generalPasteboard] containsPasteboardTypes:@[@"public.url", @"public.text"]]) {
  54. NSURL *pasteURL = [[UIPasteboard generalPasteboard] valueForPasteboardType:@"public.url"];
  55. if (!pasteURL || [[pasteURL absoluteString] isEqualToString:@""]) {
  56. NSString *pasteString = [[UIPasteboard generalPasteboard] valueForPasteboardType:@"public.text"];
  57. pasteURL = [NSURL URLWithString:pasteString];
  58. }
  59. if (pasteURL && ![[pasteURL scheme] isEqualToString:@""] && ![[pasteURL absoluteString] isEqualToString:@""])
  60. self.urlField.text = [pasteURL absoluteString];
  61. }
  62. [self _updateUI];
  63. [super viewWillAppear:animated];
  64. }
  65. - (void)viewWillDisappear:(BOOL)animated
  66. {
  67. if (SYSTEM_RUNS_IN_THE_FUTURE)
  68. self.navigationController.navigationBar.translucent = YES;
  69. [super viewWillDisappear:animated];
  70. }
  71. #pragma mark - UI interaction
  72. - (BOOL)shouldAutorotate
  73. {
  74. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  75. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  76. return NO;
  77. return YES;
  78. }
  79. - (IBAction)goBack:(id)sender
  80. {
  81. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  82. }
  83. - (IBAction)downloadAction:(id)sender
  84. {
  85. if ([self.urlField.text length] > 0) {
  86. NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
  87. if (([URLtoSave.scheme isEqualToString:@"http"] || [URLtoSave.scheme isEqualToString:@"https"] || [URLtoSave.scheme isEqualToString:@"ftp"]) && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
  88. if ([URLtoSave.lastPathComponent isSupportedFormat]) {
  89. [_currentDownloads addObject:URLtoSave];
  90. [_currentDownloadFilename addObject:@""];
  91. self.urlField.text = @"";
  92. [self.downloadsTable reloadData];
  93. [self _triggerNextDownload];
  94. } else {
  95. 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];
  96. [alert show];
  97. }
  98. }
  99. }
  100. }
  101. - (void)_updateUI
  102. {
  103. if (_currentDownloadType != 0)
  104. [self downloadStarted];
  105. else
  106. [self downloadEnded];
  107. [self.downloadsTable reloadData];
  108. }
  109. #pragma mark - download management
  110. - (void)_triggerNextDownload
  111. {
  112. if ([_currentDownloads count] > 0) {
  113. NSString *downloadScheme = [_currentDownloads[0] scheme];
  114. if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
  115. if (!_httpDownloader) {
  116. _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
  117. _httpDownloader.delegate = self;
  118. }
  119. if (!_httpDownloader.downloadInProgress) {
  120. _currentDownloadType = kVLCDownloadViaHTTP;
  121. if (![[_currentDownloadFilename objectAtIndex:0] isEqualToString:@""]) {
  122. [_httpDownloader downloadFileFromURLwithFileName:[_currentDownloads objectAtIndex:0] fileNameOfMedia:[_currentDownloadFilename objectAtIndex:0]];
  123. _humanReadableFilename = [_currentDownloadFilename objectAtIndex:0];
  124. } else {
  125. [_httpDownloader downloadFileFromURL:_currentDownloads[0]];
  126. _humanReadableFilename = _httpDownloader.userReadableDownloadName;
  127. [_currentDownloads removeObjectAtIndex:0];
  128. [_currentDownloadFilename removeObjectAtIndex:0];
  129. }
  130. }
  131. } else if ([downloadScheme isEqualToString:@"ftp"]) {
  132. _currentDownloadType = kVLCDownloadViaFTP;
  133. [self _downloadFTPFile:_currentDownloads[0]];
  134. _humanReadableFilename = [_currentDownloads[0] lastPathComponent];
  135. [_currentDownloads removeObjectAtIndex:0];
  136. [_currentDownloadFilename removeObjectAtIndex:0];
  137. } else
  138. APLog(@"Unknown download scheme '%@'", downloadScheme);
  139. [self _updateUI];
  140. } else
  141. _currentDownloadType = 0;
  142. }
  143. - (IBAction)cancelDownload:(id)sender
  144. {
  145. if (_currentDownloadType == kVLCDownloadViaHTTP) {
  146. if (_httpDownloader.downloadInProgress)
  147. [_httpDownloader cancelDownload];
  148. } else if (_currentDownloadType == kVLCDownloadViaFTP) {
  149. if (_FTPDownloadRequest) {
  150. NSURL *target = _FTPDownloadRequest.downloadLocation;
  151. [_FTPDownloadRequest destroy];
  152. [self requestCompleted:_FTPDownloadRequest];
  153. /* remove partially downloaded content */
  154. NSFileManager *fileManager = [NSFileManager defaultManager];
  155. if ([fileManager fileExistsAtPath:target.path])
  156. [fileManager removeItemAtPath:target.path error:nil];
  157. }
  158. }
  159. }
  160. #pragma mark - VLC HTTP Downloader delegate
  161. - (void)downloadStarted
  162. {
  163. [self.activityIndicator stopAnimating];
  164. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  165. self.currentDownloadLabel.text = _humanReadableFilename;
  166. self.progressView.progress = 0.;
  167. [self.progressPercent setText:@"0%%"];
  168. [self.speedRate setText:@"0 Kb/s"];
  169. [self.timeDL setText:@"00:00:00"];
  170. self.currentDownloadLabel.hidden = NO;
  171. self.progressView.hidden = NO;
  172. self.cancelButton.hidden = NO;
  173. [self.progressPercent setHidden:NO];
  174. [self.speedRate setHidden:NO];
  175. [self.timeDL setHidden:NO];
  176. _startDL = [NSDate timeIntervalSinceReferenceDate];
  177. APLog(@"download started");
  178. }
  179. - (void)downloadEnded
  180. {
  181. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  182. self.currentDownloadLabel.hidden = YES;
  183. self.progressView.hidden = YES;
  184. self.cancelButton.hidden = YES;
  185. [self.progressPercent setHidden:YES];
  186. [self.speedRate setHidden:YES];
  187. [self.timeDL setHidden:YES];
  188. _currentDownloadType = 0;
  189. APLog(@"download ended");
  190. [self _triggerNextDownload];
  191. }
  192. - (void)downloadFailedWithErrorDescription:(NSString *)description
  193. {
  194. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", @"") message:description delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
  195. [alert show];
  196. }
  197. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  198. {
  199. [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  200. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  201. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  202. [self.progressView setProgress:percentage animated:YES];
  203. }
  204. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  205. {
  206. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  207. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/speed;
  208. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  209. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  210. [formatter setDateFormat:@"HH:mm:ss"];
  211. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  212. NSString *remaingTime = [formatter stringFromDate:date];
  213. return remaingTime;
  214. }
  215. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  216. {
  217. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  218. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  219. string = [string stringByAppendingString:@"/s"];
  220. return string;
  221. }
  222. #pragma mark - ftp networking
  223. - (void)_downloadFTPFile:(NSURL *)URLToFile
  224. {
  225. if (_FTPDownloadRequest)
  226. return;
  227. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  228. _FTPDownloadRequest.delegate = self;
  229. _FTPDownloadRequest.passive = YES;
  230. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  231. NSString *directoryPath = searchPaths[0];
  232. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  233. _FTPDownloadRequest.downloadLocation = destinationURL;
  234. [_FTPDownloadRequest startWithFullURL:URLToFile];
  235. }
  236. - (void)requestStarted:(WRRequest *)request
  237. {
  238. [self downloadStarted];
  239. }
  240. - (void)requestCompleted:(WRRequest *)request
  241. {
  242. _FTPDownloadRequest = nil;
  243. [self downloadEnded];
  244. }
  245. - (void)requestFailed:(WRRequest *)request
  246. {
  247. _FTPDownloadRequest = nil;
  248. [self downloadEnded];
  249. 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];
  250. [alert show];
  251. }
  252. #pragma mark - table view data source
  253. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  254. {
  255. return 1;
  256. }
  257. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  258. {
  259. return _currentDownloads.count;
  260. }
  261. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  262. {
  263. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  264. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  265. if (cell == nil) {
  266. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  267. cell.textLabel.textColor = [UIColor whiteColor];
  268. cell.detailTextLabel.textColor = [UIColor colorWithWhite:.72 alpha:1.];
  269. }
  270. NSInteger row = indexPath.row;
  271. if ([_currentDownloadFilename[row] isEqualToString:@""])
  272. cell.textLabel.text = [_currentDownloads[row] lastPathComponent];
  273. else
  274. cell.textLabel.text = [_currentDownloadFilename[row] lastPathComponent];
  275. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  276. return cell;
  277. }
  278. #pragma mark - table view delegate
  279. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  280. {
  281. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  282. }
  283. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  284. {
  285. return YES;
  286. }
  287. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  288. {
  289. if (editingStyle == UITableViewCellEditingStyleDelete) {
  290. [_currentDownloads removeObjectAtIndex:indexPath.row];
  291. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  292. [tableView reloadData];
  293. }
  294. }
  295. #pragma mark - communication with other VLC objects
  296. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  297. {
  298. [_currentDownloads addObject:aURL];
  299. if (!fileName)
  300. fileName = @"";
  301. [_currentDownloadFilename addObject:fileName];
  302. [self.downloadsTable reloadData];
  303. [self _triggerNextDownload];
  304. }
  305. #pragma mark - text view delegate
  306. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  307. [self.urlField resignFirstResponder];
  308. return NO;
  309. }
  310. @end