VLCDownloadViewController.m 14 KB

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