VLCDownloadViewController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. }
  128. }
  129. } else if ([downloadScheme isEqualToString:@"ftp"]) {
  130. _currentDownloadType = kVLCDownloadViaFTP;
  131. [self _downloadFTPFile:_currentDownloads[0]];
  132. _humanReadableFilename = [_currentDownloads[0] lastPathComponent];
  133. } else
  134. APLog(@"Unknown download scheme '%@'", downloadScheme);
  135. [_currentDownloads removeObjectAtIndex:0];
  136. [_currentDownloadFilename removeObjectAtIndex:0];
  137. [self _updateUI];
  138. } else
  139. _currentDownloadType = 0;
  140. }
  141. - (IBAction)cancelDownload:(id)sender
  142. {
  143. if (_currentDownloadType == kVLCDownloadViaHTTP) {
  144. if (_httpDownloader.downloadInProgress)
  145. [_httpDownloader cancelDownload];
  146. } else if (_currentDownloadType == kVLCDownloadViaFTP) {
  147. if (_FTPDownloadRequest) {
  148. NSURL *target = _FTPDownloadRequest.downloadLocation;
  149. [_FTPDownloadRequest destroy];
  150. [self requestCompleted:_FTPDownloadRequest];
  151. /* remove partially downloaded content */
  152. NSFileManager *fileManager = [NSFileManager defaultManager];
  153. if ([fileManager fileExistsAtPath:target.path])
  154. [fileManager removeItemAtPath:target.path error:nil];
  155. }
  156. }
  157. }
  158. #pragma mark - VLC HTTP Downloader delegate
  159. - (void)downloadStarted
  160. {
  161. [self.activityIndicator stopAnimating];
  162. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  163. self.currentDownloadLabel.text = _humanReadableFilename;
  164. self.progressView.progress = 0.;
  165. [self.progressPourcent setText:@"0%%"];
  166. [self.speedRate setText:@"0 Kb/s"];
  167. [self.timeDL setText:@"00:00:00"];
  168. self.currentDownloadLabel.hidden = NO;
  169. self.progressView.hidden = NO;
  170. self.cancelButton.hidden = NO;
  171. [self.progressPourcent setHidden:NO];
  172. [self.speedRate setHidden:NO];
  173. [self.timeDL setHidden:NO];
  174. _startDL = [NSDate timeIntervalSinceReferenceDate];
  175. APLog(@"download started");
  176. }
  177. - (void)downloadEnded
  178. {
  179. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  180. self.currentDownloadLabel.hidden = YES;
  181. self.progressView.hidden = YES;
  182. self.cancelButton.hidden = YES;
  183. [self.progressPourcent setHidden:YES];
  184. [self.speedRate setHidden:YES];
  185. [self.timeDL setHidden:YES];
  186. _currentDownloadType = 0;
  187. APLog(@"download ended");
  188. [self _triggerNextDownload];
  189. }
  190. - (void)downloadFailedWithErrorDescription:(NSString *)description
  191. {
  192. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", @"") message:description delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
  193. [alert show];
  194. }
  195. - (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  196. {
  197. [self.progressPourcent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
  198. [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
  199. [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
  200. [self.progressView setProgress:percentage animated:YES];
  201. }
  202. - (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  203. {
  204. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  205. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/speed;
  206. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  207. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  208. [formatter setDateFormat:@"HH:mm:ss"];
  209. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  210. NSString *remaingTime = [formatter stringFromDate:date];
  211. return remaingTime;
  212. }
  213. - (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
  214. {
  215. CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  216. NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
  217. string = [string stringByAppendingString:@"/s"];
  218. return string;
  219. }
  220. #pragma mark - ftp networking
  221. - (void)_downloadFTPFile:(NSURL *)URLToFile
  222. {
  223. if (_FTPDownloadRequest)
  224. return;
  225. _FTPDownloadRequest = [[WRRequestDownload alloc] init];
  226. _FTPDownloadRequest.delegate = self;
  227. _FTPDownloadRequest.passive = YES;
  228. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  229. NSString *directoryPath = searchPaths[0];
  230. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
  231. _FTPDownloadRequest.downloadLocation = destinationURL;
  232. [_FTPDownloadRequest startWithFullURL:URLToFile];
  233. }
  234. - (void)requestStarted:(WRRequest *)request
  235. {
  236. [self downloadStarted];
  237. }
  238. - (void)requestCompleted:(WRRequest *)request
  239. {
  240. _FTPDownloadRequest = nil;
  241. [self downloadEnded];
  242. }
  243. - (void)requestFailed:(WRRequest *)request
  244. {
  245. _FTPDownloadRequest = nil;
  246. [self downloadEnded];
  247. 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];
  248. [alert show];
  249. }
  250. #pragma mark - table view data source
  251. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  252. {
  253. return 1;
  254. }
  255. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  256. {
  257. return _currentDownloads.count;
  258. }
  259. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  260. {
  261. static NSString *CellIdentifier = @"ScheduledDownloadsCell";
  262. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  263. if (cell == nil) {
  264. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  265. cell.textLabel.textColor = [UIColor whiteColor];
  266. cell.detailTextLabel.textColor = [UIColor colorWithWhite:.72 alpha:1.];
  267. }
  268. NSInteger row = indexPath.row;
  269. cell.textLabel.text = [_currentDownloads[row] lastPathComponent];
  270. cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
  271. return cell;
  272. }
  273. #pragma mark - table view delegate
  274. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  275. {
  276. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  277. }
  278. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  279. {
  280. return YES;
  281. }
  282. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  283. {
  284. if (editingStyle == UITableViewCellEditingStyleDelete) {
  285. [_currentDownloads removeObjectAtIndex:indexPath.row];
  286. [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
  287. [tableView reloadData];
  288. }
  289. }
  290. #pragma mark - communication with other VLC objects
  291. - (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
  292. {
  293. [_currentDownloads addObject:aURL];
  294. if (!fileName)
  295. fileName = @"";
  296. [_currentDownloadFilename addObject:fileName];
  297. [self.downloadsTable reloadData];
  298. [self _triggerNextDownload];
  299. }
  300. #pragma mark - text view delegate
  301. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  302. [self.urlField resignFirstResponder];
  303. return NO;
  304. }
  305. @end