VLCHTTPFileDownloader.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. #import "VLC-Swift.h"
  19. @interface VLCHTTPFileDownloader () <NSURLSessionDelegate>
  20. {
  21. NSString *_filePath;
  22. long long _expectedDownloadSize;
  23. NSUInteger _receivedDataSize;
  24. NSString *_fileName;
  25. NSURLSessionTask *_sessionTask;
  26. NSMutableURLRequest *_originalRequest;
  27. NSUInteger _statusCode;
  28. }
  29. @end
  30. @implementation VLCHTTPFileDownloader
  31. - (NSString *)userReadableDownloadName
  32. {
  33. return _fileName;
  34. }
  35. - (void)downloadFileFromURL:(NSURL *)url
  36. {
  37. [self downloadFileFromURL:url withFileName:nil];
  38. }
  39. - (NSString *)createPotentialNameFromName:(NSString *)name
  40. {
  41. NSString *documentDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  42. NSUserDomainMask,
  43. YES).firstObject;
  44. return [[self createPotentialPathFromPath:[documentDirectoryPath
  45. stringByAppendingPathComponent:name]] lastPathComponent];
  46. }
  47. - (NSString *)createPotentialPathFromPath:(NSString *)path
  48. {
  49. NSFileManager *fileManager = [NSFileManager defaultManager];
  50. NSString *fileName = [path lastPathComponent];
  51. NSString *finalFilePath = [path stringByDeletingLastPathComponent];
  52. if ([fileManager fileExistsAtPath:path]) {
  53. NSString *potentialFilename;
  54. NSString *fileExtension = [fileName pathExtension];
  55. NSString *rawFileName = [fileName stringByDeletingPathExtension];
  56. for (NSUInteger x = 1; x < 100; x++) {
  57. potentialFilename = [NSString stringWithFormat:@"%@_%lu.%@",
  58. rawFileName, (unsigned long)x, fileExtension];
  59. if (![fileManager fileExistsAtPath:[finalFilePath stringByAppendingPathComponent:potentialFilename]]) {
  60. break;
  61. }
  62. }
  63. return [finalFilePath stringByAppendingPathComponent:potentialFilename];
  64. }
  65. return path;
  66. }
  67. - (void)downloadFileFromURL:(NSURL *)url withFileName:(NSString*)fileName
  68. {
  69. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  70. NSString *basePath = [searchPaths.firstObject stringByAppendingPathComponent:@"Upload"];
  71. if (fileName)
  72. _fileName = [self createPotentialNameFromName:fileName];
  73. else
  74. _fileName = [url.lastPathComponent stringByRemovingPercentEncoding];
  75. if (_fileName.pathExtension.length == 0 || ![_fileName isSupportedFormat]) {
  76. _fileName = [_fileName stringByAppendingPathExtension:@"vlc"];
  77. }
  78. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  79. NSFileManager *fileManager = [NSFileManager defaultManager];
  80. if (![fileManager fileExistsAtPath:basePath])
  81. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  82. _expectedDownloadSize = _receivedDataSize = 0;
  83. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  84. [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"];
  85. _originalRequest = [theRequest mutableCopy];
  86. NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  87. _sessionTask = [urlSession dataTaskWithRequest:theRequest];
  88. [_sessionTask resume];
  89. if (!_sessionTask) {
  90. APLog(@"failed to establish connection");
  91. _downloadInProgress = NO;
  92. } else {
  93. _downloadInProgress = YES;
  94. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  95. [activityManager networkActivityStarted];
  96. [activityManager disableIdleTimer];
  97. }
  98. }
  99. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  100. {
  101. if (redirectResponse) {
  102. NSURL *URL = [request URL];
  103. NSFileManager *fileManager = [NSFileManager defaultManager];
  104. if ([fileManager fileExistsAtPath:_filePath])
  105. [fileManager removeItemAtPath:_filePath error:nil];
  106. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  107. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  108. _fileName = [[URL lastPathComponent] stringByRemovingPercentEncoding];
  109. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  110. if (![fileManager fileExistsAtPath:basePath])
  111. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  112. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  113. [newRequest setURL:URL];
  114. return newRequest;
  115. } else
  116. return request;
  117. }
  118. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  119. {
  120. completionHandler(NSURLSessionResponseAllow);
  121. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  122. _statusCode = [httpResponse statusCode];
  123. if (_statusCode == 200) {
  124. _expectedDownloadSize = [response expectedContentLength];
  125. APLog(@"expected download size: %lli", _expectedDownloadSize);
  126. if (_expectedDownloadSize > [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) { //handle too big a download
  127. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  128. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  129. viewController:self.delegate];
  130. [_sessionTask cancel];
  131. [self _downloadEnded];
  132. return;
  133. }
  134. [self.delegate downloadStarted];
  135. } else {
  136. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  137. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  138. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  139. }
  140. }
  141. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  142. {
  143. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  144. if (!fileHandle && _statusCode != 404) {
  145. // create file
  146. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  147. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  148. if (!fileHandle) {
  149. APLog(@"file creation failed, no data was saved");
  150. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  151. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  152. return;
  153. }
  154. }
  155. @try {
  156. [fileHandle seekToEndOfFile];
  157. [fileHandle writeData:data];
  158. _receivedDataSize = _receivedDataSize + [data length];
  159. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  160. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  161. }
  162. @catch (NSException * e) {
  163. APLog(@"exception when writing to file %@", _filePath);
  164. }
  165. [fileHandle closeFile];
  166. }
  167. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  168. {
  169. if (error.code != -999) {
  170. if (error) {
  171. APLog(@"http file download failed (%li)", (long)error.code);
  172. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  173. [self.delegate downloadFailedWithErrorDescription:error.description];
  174. } else {
  175. APLog(@"http file download complete");
  176. }
  177. [self _downloadEnded];
  178. } else {
  179. APLog(@"http file download canceled");
  180. }
  181. }
  182. - (void)cancelDownload
  183. {
  184. [_sessionTask cancel];
  185. /* remove partially downloaded content */
  186. NSFileManager *fileManager = [NSFileManager defaultManager];
  187. if ([fileManager fileExistsAtPath:_filePath])
  188. [fileManager removeItemAtPath:_filePath error:nil];
  189. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  190. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  191. [self _downloadEnded];
  192. }
  193. - (void)_downloadEnded
  194. {
  195. _downloadInProgress = NO;
  196. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  197. [activityManager networkActivityStopped];
  198. [activityManager activateIdleTimer];
  199. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  200. NSString *libraryPath = searchPaths[0];
  201. NSFileManager *fileManager = [NSFileManager defaultManager];
  202. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  203. if ([fileManager fileExistsAtPath:_filePath]) {
  204. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  205. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  206. #if TARGET_OS_IOS
  207. // FIXME: Replace notifications by cleaner observers
  208. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  209. object:self];
  210. #endif
  211. }
  212. [self.delegate downloadEnded];
  213. }
  214. @end