VLCHTTPFileDownloader.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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_iOS-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. buttonsAction:nil];
  103. [_sessionTask cancel];
  104. [self _downloadEnded];
  105. return;
  106. }
  107. [self.delegate downloadStarted];
  108. } else {
  109. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  110. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  111. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  112. }
  113. }
  114. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  115. {
  116. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  117. if (!fileHandle && _statusCode != 404) {
  118. // create file
  119. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  120. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  121. if (!fileHandle) {
  122. APLog(@"file creation failed, no data was saved");
  123. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  124. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  125. return;
  126. }
  127. }
  128. @try {
  129. [fileHandle seekToEndOfFile];
  130. [fileHandle writeData:data];
  131. _receivedDataSize = _receivedDataSize + [data length];
  132. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  133. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  134. }
  135. @catch (NSException * e) {
  136. APLog(@"exception when writing to file %@", _filePath);
  137. }
  138. [fileHandle closeFile];
  139. }
  140. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  141. {
  142. if (error.code != -999) {
  143. if (error) {
  144. APLog(@"http file download failed (%li)", (long)error.code);
  145. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  146. [self.delegate downloadFailedWithErrorDescription:error.description];
  147. } else {
  148. APLog(@"http file download complete");
  149. }
  150. [self _downloadEnded];
  151. } else {
  152. APLog(@"http file download canceled");
  153. }
  154. }
  155. - (void)cancelDownload
  156. {
  157. [_sessionTask cancel];
  158. /* remove partially downloaded content */
  159. NSFileManager *fileManager = [NSFileManager defaultManager];
  160. if ([fileManager fileExistsAtPath:_filePath])
  161. [fileManager removeItemAtPath:_filePath error:nil];
  162. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  163. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  164. [self _downloadEnded];
  165. }
  166. - (void)_downloadEnded
  167. {
  168. _downloadInProgress = NO;
  169. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  170. [activityManager networkActivityStopped];
  171. [activityManager activateIdleTimer];
  172. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  173. NSString *libraryPath = searchPaths[0];
  174. NSFileManager *fileManager = [NSFileManager defaultManager];
  175. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  176. if ([fileManager fileExistsAtPath:_filePath]) {
  177. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  178. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  179. }
  180. [self.delegate downloadEnded];
  181. }
  182. @end