AFDownloadRequestOperation.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // AFDownloadRequestOperation.m
  2. //
  3. // Copyright (c) 2012 Peter Steinberger (http://petersteinberger.com)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. #import "AFDownloadRequestOperation.h"
  23. #import "AFURLConnectionOperation.h"
  24. #import <CommonCrypto/CommonDigest.h>
  25. #include <fcntl.h>
  26. #include <unistd.h>
  27. #if !__has_feature(objc_arc)
  28. #error "Compile this file with ARC"
  29. #endif
  30. @interface AFURLConnectionOperation (AFInternal)
  31. @property (nonatomic, strong) NSURLRequest *request;
  32. @property (readonly, nonatomic, assign) long long totalBytesRead;
  33. @end
  34. typedef void (^AFURLConnectionProgressiveOperationProgressBlock)(AFDownloadRequestOperation *operation, NSInteger bytes, long long totalBytes, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile);
  35. @interface AFDownloadRequestOperation() {
  36. NSError *_fileError;
  37. id _responseObject;
  38. }
  39. @property (nonatomic, strong) NSString *tempPath;
  40. @property (assign) long long totalContentLength;
  41. @property (nonatomic, assign) long long totalBytesReadPerDownload;
  42. @property (assign) long long offsetContentLength;
  43. @property (nonatomic, copy) AFURLConnectionProgressiveOperationProgressBlock progressiveDownloadProgress;
  44. @end
  45. @implementation AFDownloadRequestOperation
  46. #pragma mark - NSObject
  47. - (void)dealloc {
  48. if (_progressiveDownloadCallbackQueue) {
  49. #if !OS_OBJECT_USE_OBJC
  50. dispatch_release(_progressiveDownloadCallbackQueue);
  51. #endif
  52. _progressiveDownloadCallbackQueue = NULL;
  53. }
  54. }
  55. - (id)initWithRequest:(NSURLRequest *)urlRequest targetPath:(NSString *)targetPath shouldResume:(BOOL)shouldResume {
  56. if ((self = [super initWithRequest:urlRequest])) {
  57. NSParameterAssert(targetPath != nil && urlRequest != nil);
  58. _shouldResume = shouldResume;
  59. // Ee assume that at least the directory has to exist on the targetPath
  60. BOOL isDirectory;
  61. if(![[NSFileManager defaultManager] fileExistsAtPath:targetPath isDirectory:&isDirectory]) {
  62. isDirectory = NO;
  63. }
  64. // \If targetPath is a directory, use the file name we got from the urlRequest.
  65. if (isDirectory) {
  66. NSString *fileName = [urlRequest.URL lastPathComponent];
  67. _targetPath = [NSString pathWithComponents:@[targetPath, fileName]];
  68. }else {
  69. _targetPath = targetPath;
  70. }
  71. // Download is saved into a temorary file and renamed upon completion.
  72. NSString *tempPath = [self tempPath];
  73. // Do we need to resume the file?
  74. BOOL isResuming = [self updateByteStartRangeForRequest];
  75. // Try to create/open a file at the target location
  76. if (!isResuming) {
  77. int fileDescriptor = open([tempPath UTF8String], O_CREAT | O_EXCL | O_RDWR, 0666);
  78. if (fileDescriptor > 0) close(fileDescriptor);
  79. }
  80. self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
  81. // If the output stream can't be created, instantly destroy the object.
  82. if (!self.outputStream) return nil;
  83. // Give the object its default completionBlock.
  84. [self setCompletionBlockWithSuccess:nil failure:nil];
  85. }
  86. return self;
  87. }
  88. // updates the current request to set the correct start-byte-range.
  89. - (BOOL)updateByteStartRangeForRequest {
  90. BOOL isResuming = NO;
  91. if (self.shouldResume) {
  92. unsigned long long downloadedBytes = [self fileSizeForPath:[self tempPath]];
  93. if (downloadedBytes > 1) {
  94. // If the the current download-request's data has been fully downloaded, but other causes of the operation failed (such as the inability of the incomplete temporary file copied to the target location), next, retry this download-request, the starting-value (equal to the incomplete temporary file size) will lead to an HTTP 416 out of range error, unless we subtract one byte here. (We don't know the final size before sending the request)
  95. downloadedBytes--;
  96. NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
  97. NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
  98. [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
  99. self.request = mutableURLRequest;
  100. isResuming = YES;
  101. }
  102. }
  103. return isResuming;
  104. }
  105. #pragma mark - Public
  106. - (BOOL)deleteTempFileWithError:(NSError *__autoreleasing*)error {
  107. NSFileManager *fileManager = [NSFileManager new];
  108. BOOL success = YES;
  109. @synchronized(self) {
  110. NSString *tempPath = [self tempPath];
  111. if ([fileManager fileExistsAtPath:tempPath]) {
  112. success = [fileManager removeItemAtPath:[self tempPath] error:error];
  113. }
  114. }
  115. return success;
  116. }
  117. - (NSString *)tempPath {
  118. NSString *tempPath = nil;
  119. if (self.targetPath) {
  120. NSString *md5URLString = [[self class] md5StringForString:self.targetPath];
  121. tempPath = [[[self class] cacheFolder] stringByAppendingPathComponent:md5URLString];
  122. }
  123. return tempPath;
  124. }
  125. - (void)setProgressiveDownloadProgressBlock:(void (^)(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile))block {
  126. self.progressiveDownloadProgress = block;
  127. }
  128. - (void)setProgressiveDownloadCallbackQueue:(dispatch_queue_t)progressiveDownloadCallbackQueue {
  129. if (progressiveDownloadCallbackQueue != _progressiveDownloadCallbackQueue) {
  130. if (_progressiveDownloadCallbackQueue) {
  131. #if !OS_OBJECT_USE_OBJC
  132. dispatch_release(_progressiveDownloadCallbackQueue);
  133. #endif
  134. _progressiveDownloadCallbackQueue = NULL;
  135. }
  136. if (progressiveDownloadCallbackQueue) {
  137. #if !OS_OBJECT_USE_OBJC
  138. dispatch_retain(progressiveDownloadCallbackQueue);
  139. #endif
  140. _progressiveDownloadCallbackQueue = progressiveDownloadCallbackQueue;
  141. }
  142. }
  143. }
  144. #pragma mark - Private
  145. - (unsigned long long)fileSizeForPath:(NSString *)path {
  146. signed long long fileSize = 0;
  147. NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe
  148. if ([fileManager fileExistsAtPath:path]) {
  149. NSError *error = nil;
  150. NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
  151. if (!error && fileDict) {
  152. fileSize = [fileDict fileSize];
  153. }
  154. }
  155. return fileSize;
  156. }
  157. #pragma mark - AFHTTPRequestOperation
  158. + (NSIndexSet *)acceptableStatusCodes {
  159. NSMutableIndexSet *acceptableStatusCodes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
  160. [acceptableStatusCodes addIndex:416];
  161. return acceptableStatusCodes;
  162. }
  163. #pragma mark - AFURLRequestOperation
  164. - (void)pause {
  165. [super pause];
  166. [self updateByteStartRangeForRequest];
  167. }
  168. - (id)responseObject {
  169. @synchronized(self) {
  170. if (!_responseObject && [self isFinished] && !self.error) {
  171. NSError *localError = nil;
  172. if ([self isCancelled]) {
  173. // should we clean up? most likely we don't.
  174. if (self.isDeletingTempFileOnCancel) {
  175. [self deleteTempFileWithError:&localError];
  176. if (localError) {
  177. _fileError = localError;
  178. }
  179. }
  180. // loss of network connections = error set, but not cancel
  181. }else if(!self.error) {
  182. // move file to final position and capture error
  183. NSFileManager *fileManager = [NSFileManager new];
  184. if (self.shouldOverwrite) {
  185. [fileManager removeItemAtPath:_targetPath error:NULL]; // avoid "File exists" error
  186. }
  187. [fileManager moveItemAtPath:[self tempPath] toPath:_targetPath error:&localError];
  188. if (localError) {
  189. _fileError = localError;
  190. } else {
  191. _responseObject = _targetPath;
  192. }
  193. }
  194. }
  195. }
  196. return _responseObject;
  197. }
  198. - (NSError *)error {
  199. return _fileError ?: [super error];
  200. }
  201. #pragma mark - NSURLConnectionDelegate
  202. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  203. [super connection:connection didReceiveResponse:response];
  204. // check if we have the correct response
  205. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  206. if (![httpResponse isKindOfClass:[NSHTTPURLResponse class]]) return;
  207. // check for valid response to resume the download if possible
  208. long long totalContentLength = self.response.expectedContentLength;
  209. long long fileOffset = 0;
  210. if(httpResponse.statusCode == 206) {
  211. NSString *contentRange = [httpResponse.allHeaderFields valueForKey:@"Content-Range"];
  212. if ([contentRange hasPrefix:@"bytes"]) {
  213. NSArray *bytes = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
  214. if ([bytes count] == 4) {
  215. fileOffset = [bytes[1] longLongValue];
  216. totalContentLength = [bytes[3] longLongValue]; // if this is *, it's converted to 0
  217. }
  218. }
  219. }
  220. self.totalBytesReadPerDownload = 0;
  221. self.offsetContentLength = MAX(fileOffset, 0);
  222. self.totalContentLength = totalContentLength;
  223. // Truncate cache file to offset provided by server.
  224. // Using self.outputStream setProperty:@(_offsetContentLength) forKey:NSStreamFileCurrentOffsetKey]; will not work (in contrary to the documentation)
  225. NSString *tempPath = [self tempPath];
  226. if ([self fileSizeForPath:tempPath] != _offsetContentLength) {
  227. [self.outputStream close];
  228. BOOL isResuming = _offsetContentLength > 0;
  229. if (isResuming) {
  230. NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:tempPath];
  231. [file truncateFileAtOffset:_offsetContentLength];
  232. [file closeFile];
  233. }
  234. self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
  235. [self.outputStream open];
  236. }
  237. }
  238. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  239. if (![self.responseSerializer validateResponse:self.response data:nil error:NULL])
  240. return; // don't write to output stream if any error occurs
  241. [super connection:connection didReceiveData:data];
  242. // track custom bytes read because totalBytesRead persists between pause/resume.
  243. self.totalBytesReadPerDownload += [data length];
  244. if (self.progressiveDownloadProgress) {
  245. dispatch_async(self.progressiveDownloadCallbackQueue ?: dispatch_get_main_queue(), ^{
  246. self.progressiveDownloadProgress(self,(NSInteger)[data length], self.totalBytesRead, self.response.expectedContentLength,self.totalBytesReadPerDownload + self.offsetContentLength, self.totalContentLength);
  247. });
  248. }
  249. }
  250. #pragma mark - Static
  251. + (NSString *)cacheFolder {
  252. NSFileManager *filemgr = [NSFileManager new];
  253. static NSString *cacheFolder;
  254. if (!cacheFolder) {
  255. NSString *cacheDir = NSTemporaryDirectory();
  256. cacheFolder = [cacheDir stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadFolderName];
  257. }
  258. // ensure all cache directories are there
  259. NSError *error = nil;
  260. if(![filemgr createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
  261. NSLog(@"Failed to create cache directory at %@", cacheFolder);
  262. cacheFolder = nil;
  263. }
  264. return cacheFolder;
  265. }
  266. // calculates the MD5 hash of a key
  267. + (NSString *)md5StringForString:(NSString *)string {
  268. const char *str = [string UTF8String];
  269. unsigned char r[CC_MD5_DIGEST_LENGTH];
  270. CC_MD5(str, (uint32_t)strlen(str), r);
  271. return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  272. r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
  273. }
  274. @end