VLCHTTPFileDownloader.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. - (void)downloadFileFromURL:(NSURL *)url withFileName:(NSString*)fileName
  40. {
  41. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  42. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  43. if (fileName)
  44. _fileName = fileName;
  45. else
  46. _fileName = [url.lastPathComponent stringByRemovingPercentEncoding];
  47. if (_fileName.pathExtension.length == 0 || ![_fileName isSupportedFormat]) {
  48. _fileName = [_fileName stringByAppendingPathExtension:@"vlc"];
  49. }
  50. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  51. NSFileManager *fileManager = [NSFileManager defaultManager];
  52. if (![fileManager fileExistsAtPath:basePath])
  53. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  54. _expectedDownloadSize = _receivedDataSize = 0;
  55. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  56. [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"];
  57. _originalRequest = [theRequest mutableCopy];
  58. NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  59. _sessionTask = [urlSession dataTaskWithRequest:theRequest];
  60. [_sessionTask resume];
  61. if (!_sessionTask) {
  62. APLog(@"failed to establish connection");
  63. _downloadInProgress = NO;
  64. } else {
  65. _downloadInProgress = YES;
  66. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  67. [activityManager networkActivityStarted];
  68. [activityManager disableIdleTimer];
  69. }
  70. }
  71. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  72. {
  73. if (redirectResponse) {
  74. NSURL *URL = [request URL];
  75. NSFileManager *fileManager = [NSFileManager defaultManager];
  76. if ([fileManager fileExistsAtPath:_filePath])
  77. [fileManager removeItemAtPath:_filePath error:nil];
  78. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  79. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  80. _fileName = [[URL lastPathComponent] stringByRemovingPercentEncoding];
  81. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  82. if (![fileManager fileExistsAtPath:basePath])
  83. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  84. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  85. [newRequest setURL:URL];
  86. return newRequest;
  87. } else
  88. return request;
  89. }
  90. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  91. {
  92. completionHandler(NSURLSessionResponseAllow);
  93. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  94. _statusCode = [httpResponse statusCode];
  95. if (_statusCode == 200) {
  96. _expectedDownloadSize = [response expectedContentLength];
  97. APLog(@"expected download size: %lli", _expectedDownloadSize);
  98. if (_expectedDownloadSize > [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) { //handle too big a download
  99. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  100. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  101. viewController:self.delegate];
  102. [_sessionTask cancel];
  103. [self _downloadEnded];
  104. return;
  105. }
  106. [self.delegate downloadStarted];
  107. } else {
  108. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  109. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  110. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  111. }
  112. }
  113. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  114. {
  115. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  116. if (!fileHandle && _statusCode != 404) {
  117. // create file
  118. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  119. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  120. if (!fileHandle) {
  121. APLog(@"file creation failed, no data was saved");
  122. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  123. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  124. return;
  125. }
  126. }
  127. @try {
  128. [fileHandle seekToEndOfFile];
  129. [fileHandle writeData:data];
  130. _receivedDataSize = _receivedDataSize + [data length];
  131. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  132. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  133. }
  134. @catch (NSException * e) {
  135. APLog(@"exception when writing to file %@", _filePath);
  136. }
  137. [fileHandle closeFile];
  138. }
  139. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  140. {
  141. if (error.code != -999) {
  142. if (error) {
  143. APLog(@"http file download failed (%li)", (long)error.code);
  144. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  145. [self.delegate downloadFailedWithErrorDescription:error.description];
  146. } else {
  147. APLog(@"http file download complete");
  148. }
  149. [self _downloadEnded];
  150. } else {
  151. APLog(@"http file download canceled");
  152. }
  153. }
  154. - (void)cancelDownload
  155. {
  156. [_sessionTask cancel];
  157. /* remove partially downloaded content */
  158. NSFileManager *fileManager = [NSFileManager defaultManager];
  159. if ([fileManager fileExistsAtPath:_filePath])
  160. [fileManager removeItemAtPath:_filePath error:nil];
  161. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  162. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  163. [self _downloadEnded];
  164. }
  165. - (void)_downloadEnded
  166. {
  167. _downloadInProgress = NO;
  168. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  169. [activityManager networkActivityStopped];
  170. [activityManager activateIdleTimer];
  171. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  172. NSString *libraryPath = searchPaths[0];
  173. NSFileManager *fileManager = [NSFileManager defaultManager];
  174. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  175. if ([fileManager fileExistsAtPath:_filePath]) {
  176. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  177. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  178. }
  179. [self.delegate downloadEnded];
  180. }
  181. @end