-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIRRemoteResourceDownloadOperation.m
More file actions
443 lines (281 loc) · 10.6 KB
/
IRRemoteResourceDownloadOperation.m
File metadata and controls
443 lines (281 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//
// IRRemoteResourceDownloadOperation.m
// IRWebAPIKit
//
// Created by Evadne Wu on 9/16/11.
// Copyright (c) 2011 Iridia Productions. All rights reserved.
//
#import "IRRemoteResourceDownloadOperation.h"
NSString * const kIRRemoteResourcesDownloadOperation_connectionRequest = @"kIRRemoteResourcesDownloadOperation_connectionRequest";
NSString * const kIRRemoteResourceDownloadOperationDidReceiveDataNotification = @"IRRemoteResourceDownloadOperationDidReceiveDataNotification";
NSString * const kIRRemoteResourceDownloadOperationURL = @"IRRemoteResourceDownloadOperationURL";
@interface IRRemoteResourceDownloadOperation ()
@property (nonatomic, readwrite, copy) NSString *path;
@property (nonatomic, readwrite, copy) NSString *mimeType;
@property (nonatomic, readwrite, retain) NSURL *url;
@property (nonatomic, readwrite, assign) long long processedBytes;
@property (nonatomic, readwrite, assign) long long totalBytes;
@property (nonatomic, readwrite, assign) long long preferredByteOffset;
@property (nonatomic, readwrite, assign, getter=isExecuting) BOOL executing;
@property (nonatomic, readwrite, assign, getter=isFinished) BOOL finished;
@property (nonatomic, readwrite, assign, getter=isCancelled) BOOL cancelled;
@property (nonatomic, readwrite, retain) NSFileHandle *fileHandle;
@property (nonatomic, readwrite, retain) NSURLConnection *connection;
@property (nonatomic, readwrite, assign) dispatch_queue_t actualDispatchQueue;
@property (nonatomic, readwrite, retain) NSMutableArray *appendedCompletionBlocks;
- (void) onMainQueue:(void(^)(void))aBlock;
- (void) onOriginalQueue:(void(^)(void))aBlock;
@property (nonatomic, readwrite, copy) void(^onMain)(void);
@end
@implementation IRRemoteResourceDownloadOperation
@synthesize path, mimeType, url, processedBytes, totalBytes, preferredByteOffset, executing, finished, cancelled;
@synthesize fileHandle, connection;
@synthesize actualDispatchQueue;
@synthesize onMain;
@synthesize appendedCompletionBlocks;
@synthesize delegate;
+ (IRRemoteResourceDownloadOperation *) operationWithURL:(NSURL *)aRemoteURL path:(NSString *)aLocalPath prelude:(void(^)(void))aPrelude completion:(void(^)(void))aBlock {
NSParameterAssert(aRemoteURL);
NSParameterAssert(aLocalPath);
IRRemoteResourceDownloadOperation *returnedOperation = [[[self alloc] init] autorelease];
returnedOperation.url = aRemoteURL;
returnedOperation.path = aLocalPath;
returnedOperation.onMain = aPrelude;
returnedOperation.completionBlock = aBlock;
return returnedOperation;
}
- (void) dealloc {
[mimeType release];
[path release];
[url release];
[fileHandle release];
__block NSURLConnection *nrConnection = connection;
dispatch_async(dispatch_get_main_queue(), ^ {
[nrConnection release];
});
[onMain release];
[appendedCompletionBlocks release];
[super dealloc];
}
- (void) onMainQueue:(void(^)(void))aBlock {
if (!self.actualDispatchQueue)
self.actualDispatchQueue = dispatch_get_current_queue();
if ([NSThread isMainThread]) {
aBlock();
return;
}
dispatch_async(dispatch_get_main_queue(), ^ {
aBlock();
});
}
- (void) onOriginalQueue:(void(^)(void))aBlock {
dispatch_async(self.actualDispatchQueue, aBlock);
}
- (void) start {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
if ([self isCancelled]) {
self.finished = YES;
return;
}
self.executing = YES;
[self main];
}
- (void) main {
NSParameterAssert(self.url);
NSParameterAssert(self.path);
if (self.onMain)
self.onMain();
[[NSFileManager defaultManager] createFileAtPath:self.path contents:nil attributes:nil];
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.path];
NSParameterAssert(self.fileHandle);
[self onMainQueue: ^ {
NSMutableURLRequest *usedRequest = [NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSURLConnection *usedConnection = [[[NSURLConnection alloc] initWithRequest:usedRequest delegate:self startImmediately:NO] autorelease];
objc_setAssociatedObject(usedConnection, &kIRRemoteResourcesDownloadOperation_connectionRequest, usedRequest, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.connection = usedConnection;
[self.delegate remoteResourceDownloadOperationWillBegin:self];
usedConnection = [[[NSURLConnection alloc] initWithRequest:usedRequest delegate:self startImmediately:NO] autorelease];
objc_setAssociatedObject(usedConnection, &kIRRemoteResourcesDownloadOperation_connectionRequest, usedRequest, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.connection = usedConnection;
// Do not mutate the URL
// self.url = usedRequest.URL;
[self.connection start];
}];
}
- (void) cancel {
[self onMainQueue: ^ {
[self.connection cancel];
}];
[self onOriginalQueue: ^ {
[self.fileHandle closeFile];
}];
if (self.executing) {
self.executing = NO;
self.finished = YES;
}
self.cancelled = YES;
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([self isCancelled])
return;
[self onOriginalQueue: ^ {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode != 200) {
[self.fileHandle closeFile];
self.fileHandle = nil;
[[NSFileManager defaultManager] removeItemAtPath:self.path error:nil];
}
}
// Per discussion in Apple documentation, this can be called multiple times
[self.fileHandle truncateFileAtOffset:0];
self.mimeType = response.MIMEType;
[self willChangeValueForKey:@"progress"];
self.totalBytes = response.expectedContentLength;
[self didChangeValueForKey:@"progress"];
}];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if ([self isCancelled])
return;
[self onOriginalQueue: ^ {
[self willChangeValueForKey:@"progress"];
self.processedBytes += [data length];
[self didChangeValueForKey:@"progress"];
[self.fileHandle writeData:data];
[[NSNotificationCenter defaultCenter] postNotificationName:kIRRemoteResourceDownloadOperationDidReceiveDataNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
self.url, kIRRemoteResourceDownloadOperationURL,
nil]];
}];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self isCancelled])
return;
[self onOriginalQueue: ^ {
[self.fileHandle closeFile];
if (self.mimeType) {
// If there is a MIME type available, rename the underlying file
NSFileManager *fm = [NSFileManager defaultManager];
NSString *utiType = [(NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (CFStringRef)self.mimeType, NULL) autorelease];
NSString *pathExtension = [(NSString *)UTTypeCopyPreferredTagWithClass((CFStringRef)utiType, kUTTagClassFilenameExtension) autorelease];
NSString *fromPath = self.path;
NSString *toPath = [[self.path stringByDeletingPathExtension] stringByAppendingPathExtension:pathExtension];
NSError *error = nil;
BOOL didMove = [fm moveItemAtPath:fromPath toPath:toPath error:&error];
if (!didMove) {
NSLog(@"%s: %@ -> %@ Error: %@", __PRETTY_FUNCTION__, fromPath, toPath, error);
} else {
self.path = toPath;
}
}
if (self.executing) {
self.executing = NO;
self.finished = YES;
}
}];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if ([self isCancelled])
return;
[self onOriginalQueue: ^ {
[self.fileHandle closeFile];
[[NSFileManager defaultManager] removeItemAtPath:self.path error:nil];
if (self.executing) {
self.executing = NO;
self.finished = YES;
}
}];
}
- (NSURLRequest *) connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)aRequest redirectResponse:(NSURLResponse *)aRedirectResponse {
if (!aRedirectResponse)
return aRequest;
NSMutableURLRequest *mutatedRequest = [[[self underlyingRequest] mutableCopy] autorelease];
mutatedRequest.URL = [aRequest URL];
return mutatedRequest;
}
- (BOOL) isConcurrent {
return YES;
}
- (float_t) progress {
if (totalBytes <= 0)
return 0.0f;
return (float_t)((double_t)processedBytes / (double_t)totalBytes);
}
- (void) setFinished:(BOOL)newFinished {
if (newFinished == finished)
return;
[self willChangeValueForKey:@"isFinished"];
finished = newFinished;
[self didChangeValueForKey:@"isFinished"];
}
- (void) setExecuting:(BOOL)newExecuting {
if (newExecuting == executing)
return;
[self willChangeValueForKey:@"isExecuting"];
executing = newExecuting;
[self didChangeValueForKey:@"isExecuting"];
}
- (NSString *) description {
return [NSString stringWithFormat:
@"<%@: 0x%x> "
// @"Offset: %lu, "
@"URL: %@, "
@"Path: %@, "
@"Completion Blocks: %@, "
@"Executing: %x, "
@"Cancelled: %x, "
@"Finished: %x ",
NSStringFromClass([self class]), (unsigned int)self,
// self.preferredByteOffset,
self.url,
self.path,
self.appendedCompletionBlocks,
self.executing,
self.cancelled,
self.finished
];
}
- (NSMutableArray *) appendedCompletionBlocks {
if (appendedCompletionBlocks)
return appendedCompletionBlocks;
appendedCompletionBlocks = [[NSMutableArray array] retain];
return appendedCompletionBlocks;
}
- (void) appendCompletionBlock:(void (^)(void))aBlock {
[self.appendedCompletionBlocks addObject:[[aBlock copy] autorelease]];
}
- (void) invokeCompletionBlocks {
@synchronized (self) {
for (void(^aBlock)(void) in [[self.appendedCompletionBlocks copy] autorelease])
aBlock();
self.appendedCompletionBlocks = [NSMutableArray array];
}
}
- (IRRemoteResourceDownloadOperation *) continuationOperationCancellingCurrentOperation:(BOOL)cancelsCurrentOperation {
if (!self.path || !self.url)
return nil;
__block IRRemoteResourceDownloadOperation *continuationOperation = [[[[self class] alloc] init] autorelease];
continuationOperation.path = self.path;
continuationOperation.url = self.url;
continuationOperation.preferredByteOffset = self.processedBytes;
continuationOperation.totalBytes = self.totalBytes;
@synchronized (self) {
continuationOperation.appendedCompletionBlocks = self.appendedCompletionBlocks;
[self.appendedCompletionBlocks removeAllObjects];
}
if (cancelsCurrentOperation) {
[self.connection cancel];
[self cancel];
}
return continuationOperation;
}
- (NSURLConnection *) underlyingConnection {
return self.connection;
}
- (NSMutableURLRequest *) underlyingRequest {
return objc_getAssociatedObject([self underlyingConnection], &kIRRemoteResourcesDownloadOperation_connectionRequest);
}
@end