VLCDownloadViewController.m 13 KB

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