VLCHTTPFileDownloader.m 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*****************************************************************************
  2. * VLCHTTPFileDownloader.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2018 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Pierre Sagaspe <pierre.sagaspe # me.com>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCHTTPFileDownloader.h"
  14. #import "NSString+SupportedMedia.h"
  15. #import "VLCActivityManager.h"
  16. #import "UIDevice+VLC.h"
  17. #import "VLCMediaFileDiscoverer.h"
  18. @interface VLCHTTPFileDownloader () <NSURLSessionDelegate>
  19. {
  20. NSString *_filePath;
  21. long long _expectedDownloadSize;
  22. NSUInteger _receivedDataSize;
  23. NSString *_fileName;
  24. NSURLSessionTask *_sessionTask;
  25. NSMutableURLRequest *_originalRequest;
  26. NSUInteger _statusCode;
  27. }
  28. @end
  29. @implementation VLCHTTPFileDownloader
  30. - (NSString *)userReadableDownloadName
  31. {
  32. return _fileName;
  33. }
  34. - (void)downloadFileFromURL:(NSURL *)url
  35. {
  36. [self downloadFileFromURL:url withFileName:nil];
  37. }
  38. - (void)downloadFileFromURL:(NSURL *)url withFileName:(NSString*)fileName
  39. {
  40. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  41. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  42. if (fileName)
  43. _fileName = fileName;
  44. else
  45. _fileName = [url.lastPathComponent stringByRemovingPercentEncoding];
  46. if (_fileName.pathExtension.length == 0 || ![_fileName isSupportedFormat]) {
  47. _fileName = [_fileName stringByAppendingPathExtension:@"vlc"];
  48. }
  49. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  50. NSFileManager *fileManager = [NSFileManager defaultManager];
  51. if (![fileManager fileExistsAtPath:basePath])
  52. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  53. _expectedDownloadSize = _receivedDataSize = 0;
  54. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  55. [theRequest addValue:[NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/%@ Mobile/11A465 Safari/9537.53 VLC for iOS/%@", UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone", [[UIDevice currentDevice] systemVersion], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"User-Agent"];
  56. _originalRequest = [theRequest mutableCopy];
  57. NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  58. _sessionTask = [urlSession dataTaskWithRequest:theRequest];
  59. [_sessionTask resume];
  60. if (!_sessionTask) {
  61. APLog(@"failed to establish connection");
  62. _downloadInProgress = NO;
  63. } else {
  64. _downloadInProgress = YES;
  65. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  66. [activityManager networkActivityStarted];
  67. [activityManager disableIdleTimer];
  68. }
  69. }
  70. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  71. {
  72. if (redirectResponse) {
  73. NSURL *URL = [request URL];
  74. NSFileManager *fileManager = [NSFileManager defaultManager];
  75. if ([fileManager fileExistsAtPath:_filePath])
  76. [fileManager removeItemAtPath:_filePath error:nil];
  77. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  78. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  79. _fileName = [[URL lastPathComponent] stringByRemovingPercentEncoding];
  80. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  81. if (![fileManager fileExistsAtPath:basePath])
  82. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  83. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  84. [newRequest setURL:URL];
  85. return newRequest;
  86. } else
  87. return request;
  88. }
  89. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  90. {
  91. completionHandler(NSURLSessionResponseAllow);
  92. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  93. _statusCode = [httpResponse statusCode];
  94. if (_statusCode == 200) {
  95. _expectedDownloadSize = [response expectedContentLength];
  96. APLog(@"expected download size: %lli", _expectedDownloadSize);
  97. if (![[response suggestedFilename] isSupportedFormat]) { //handle unsupported format
  98. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  99. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [response suggestedFilename]]
  100. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  101. otherButtonTitles:nil];
  102. [alert show];
  103. [_sessionTask cancel];
  104. [self _downloadEnded];
  105. return;
  106. }
  107. if (_expectedDownloadSize > [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) { //handle too big a download
  108. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  109. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  110. delegate:self
  111. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  112. otherButtonTitles:nil];
  113. [alert show];
  114. [_sessionTask cancel];
  115. [self _downloadEnded];
  116. return;
  117. }
  118. [self.delegate downloadStarted];
  119. } else {
  120. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  121. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  122. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  123. }
  124. }
  125. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  126. {
  127. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  128. if (!fileHandle && _statusCode != 404) {
  129. // create file
  130. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  131. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  132. if (!fileHandle) {
  133. APLog(@"file creation failed, no data was saved");
  134. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  135. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  136. return;
  137. }
  138. }
  139. @try {
  140. [fileHandle seekToEndOfFile];
  141. [fileHandle writeData:data];
  142. _receivedDataSize = _receivedDataSize + [data length];
  143. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  144. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  145. }
  146. @catch (NSException * e) {
  147. APLog(@"exception when writing to file %@", _filePath);
  148. }
  149. [fileHandle closeFile];
  150. }
  151. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  152. {
  153. if (error.code != -999) {
  154. if (error) {
  155. APLog(@"http file download failed (%li)", (long)error.code);
  156. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  157. [self.delegate downloadFailedWithErrorDescription:error.description];
  158. } else {
  159. APLog(@"http file download complete");
  160. }
  161. [self _downloadEnded];
  162. } else {
  163. APLog(@"http file download canceled");
  164. }
  165. }
  166. - (void)cancelDownload
  167. {
  168. [_sessionTask cancel];
  169. /* remove partially downloaded content */
  170. NSFileManager *fileManager = [NSFileManager defaultManager];
  171. if ([fileManager fileExistsAtPath:_filePath])
  172. [fileManager removeItemAtPath:_filePath error:nil];
  173. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  174. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  175. [self _downloadEnded];
  176. }
  177. - (void)_downloadEnded
  178. {
  179. _downloadInProgress = NO;
  180. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  181. [activityManager networkActivityStopped];
  182. [activityManager activateIdleTimer];
  183. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  184. NSString *libraryPath = searchPaths[0];
  185. NSFileManager *fileManager = [NSFileManager defaultManager];
  186. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  187. if ([fileManager fileExistsAtPath:_filePath]) {
  188. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  189. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  190. }
  191. [self.delegate downloadEnded];
  192. }
  193. @end