-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIRRemoteResourcesManager.m
More file actions
620 lines (355 loc) · 16.5 KB
/
IRRemoteResourcesManager.m
File metadata and controls
620 lines (355 loc) · 16.5 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//
// IRRemoteResourcesManager.m
// IRWebAPIKit
//
// Created by Evadne Wu on 12/21/10.
// Copyright 2010 Iridia Productions. All rights reserved.
//
#import "IRRemoteResourcesManager.h"
#import "IRRemoteResourceDownloadOperation.h"
NSString * const kIRRemoteResourcesManagerDidRetrieveResourceNotification = @"IRRemoteResourcesManagerDidRetrieveResourceNotification";
@interface IRRemoteResourcesManager () <NSCacheDelegate, IRRemoteResourceDownloadOperationDelegate>
@property (nonatomic, readwrite, retain) NSOperationQueue *queue;
@property (nonatomic, readwrite, retain) NSMutableArray *enqueuedOperations;
- (void) enqueueOperationsIfNeeded;
@property (nonatomic, readwrite, assign) dispatch_queue_t operationQueue;
- (void) performInBackground:(void(^)(void))aBlock;
- (void) performOnMainThread:(void(^)(void))aBlock;
@property (nonatomic, readonly, retain) NSString *cacheDirectoryPath;
- (NSString *) pathForCachedContentsOfRemoteURL:(NSURL *)inRemoteURL usedProspectiveURL:(BOOL *)returnedProspectiveURL;
- (BOOL) clearCacheDirectory;
- (void) notifyUpdatedResourceForRemoteURL:(NSURL *)inRemoteURL;
@property (nonatomic, readwrite, assign) NSInteger operationQueueSuspendingCount;
- (BOOL) isSuspendingOperationQueue;
- (void) beginSuspendingOperationQueue;
- (void) endSuspendingOperationQueue;
@property (nonatomic, readonly, retain) NSMutableDictionary *allOperations;
@property (nonatomic, readonly, assign) dispatch_queue_t allOperationsQueue;
- (IRRemoteResourceDownloadOperation *) operationWithURL:(NSURL *)anURL;
- (BOOL) addOperation:(IRRemoteResourceDownloadOperation *)anOperation;
- (BOOL) removeOperation:(IRRemoteResourceDownloadOperation *)anOperation;
@end
@implementation IRRemoteResourcesManager
@synthesize queue, operationQueue;
@synthesize enqueuedOperations;
@synthesize schedulingStrategy;
@synthesize delegate;
@synthesize cacheDirectoryPath;
@synthesize onRemoteResourceDownloadOperationWillBegin;
@synthesize allOperations, allOperationsQueue;
@synthesize operationQueueSuspendingCount;
+ (IRRemoteResourcesManager *) sharedManager {
static IRRemoteResourcesManager *sharedManagerInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManagerInstance = [[self alloc] init];
});
return sharedManagerInstance;
}
- (id) init {
self = [super init];
if (!self)
return nil;
schedulingStrategy = IRPostponeLowerPriorityOperationsStrategy;
queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 1;
operationQueue = dispatch_queue_create("iridia.remoteResourcesManager.operationQueue", DISPATCH_QUEUE_SERIAL);
enqueuedOperations = [[NSMutableArray array] retain];
allOperations = [[NSMutableDictionary dictionary] retain];
allOperationsQueue = dispatch_queue_create("iridia.remoteResourcesManager.operationsManagingQueue", DISPATCH_QUEUE_SERIAL);
return self;
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (operationQueue)
dispatch_release(operationQueue);
[queue release];
[enqueuedOperations release];
[cacheDirectoryPath release];
[onRemoteResourceDownloadOperationWillBegin release];
[allOperations release];
if (allOperationsQueue)
dispatch_release(allOperationsQueue);
[super dealloc];
}
- (NSInteger) operationQueueSuspendingCount {
NSParameterAssert([NSThread isMainThread]);
return operationQueueSuspendingCount;
}
- (void) setOperationQueueSuspendingCount:(NSInteger)newOperationQueueSuspendingCount {
NSParameterAssert([NSThread isMainThread]);
if (operationQueueSuspendingCount == newOperationQueueSuspendingCount)
return;
[self willChangeValueForKey:@"operationQueueSuspendingCount"];
if ((operationQueueSuspendingCount == 0) && (newOperationQueueSuspendingCount == 1)) {
NSParameterAssert(![self.queue isSuspended]);
[self.queue setSuspended:YES];
} else if ((operationQueueSuspendingCount == 1) && (newOperationQueueSuspendingCount == 0)) {
NSParameterAssert([self.queue isSuspended]);
[self.queue setSuspended:NO];
}
operationQueueSuspendingCount = newOperationQueueSuspendingCount;
[self didChangeValueForKey:@"operationQueueSuspendingCount"];
}
- (BOOL) isSuspendingOperationQueue {
return (BOOL)!!self.operationQueueSuspendingCount;
}
- (void) beginSuspendingOperationQueue {
NSParameterAssert([NSThread isMainThread]);
self.operationQueueSuspendingCount++;
}
- (void) endSuspendingOperationQueue {
NSParameterAssert([NSThread isMainThread]);
NSParameterAssert(self.operationQueueSuspendingCount > 0);
self.operationQueueSuspendingCount--;
}
- (IRRemoteResourceDownloadOperation *) operationWithURL:(NSURL *)anURL {
NSParameterAssert(dispatch_get_current_queue() != self.allOperationsQueue);
__block IRRemoteResourceDownloadOperation *returnedOperation = nil;
dispatch_sync(self.allOperationsQueue, ^ {
returnedOperation = [self.allOperations objectForKey:[anURL absoluteString]];
});
return returnedOperation;
}
- (BOOL) addOperation:(IRRemoteResourceDownloadOperation *)anOperation {
NSParameterAssert(dispatch_get_current_queue() != self.allOperationsQueue);
__block BOOL didAdd = NO;
dispatch_sync(self.allOperationsQueue, ^{
NSString *key = [anOperation.url absoluteString];
if ([self.allOperations objectForKey:key]) {
return;
}
[self.allOperations setObject:anOperation forKey:key];
didAdd = YES;
});
return didAdd;
}
- (BOOL) removeOperation:(IRRemoteResourceDownloadOperation *)anOperation {
NSParameterAssert(dispatch_get_current_queue() != self.allOperationsQueue);
__block BOOL didRemove = NO;
dispatch_sync(self.allOperationsQueue, ^ {
NSString *key = [anOperation.url absoluteString];
if (![self.allOperations objectForKey:key])
return;
[self.allOperations removeObjectForKey:key];
didRemove = YES;
});
return didRemove;
}
- (void) performInBackground:(void (^)(void))aBlock {
dispatch_async(self.operationQueue, aBlock);
}
- (void) performOnMainThread:(void (^)(void))aBlock {
NSParameterAssert(![NSThread isMainThread]);
dispatch_async(dispatch_get_main_queue(), aBlock);
}
- (IRRemoteResourceDownloadOperation *) runningOperationForURL:(NSURL *)anURL {
NSParameterAssert(anURL);
NSArray *allMatches = [self.queue.operations filteredArrayUsingPredicate:[NSPredicate predicateWithBlock: ^ (IRRemoteResourceDownloadOperation *anOperation, NSDictionary *bindings) {
return (BOOL)(![anOperation isCancelled] && [[anOperation.url absoluteString] isEqual:[anURL absoluteString]]);
}]];
NSParameterAssert([allMatches count] <= 1);
return [allMatches lastObject];
}
- (IRRemoteResourceDownloadOperation *) enqueuedOperationForURL:(NSURL *)anURL {
NSParameterAssert(anURL);
NSArray *allMatches = [self.enqueuedOperations filteredArrayUsingPredicate:[NSPredicate predicateWithBlock: ^ (IRRemoteResourceDownloadOperation *anOperation, NSDictionary *bindings) {
return [[anOperation.url absoluteString] isEqual:[anURL absoluteString]];
}]];
NSParameterAssert([allMatches count] <= 1);
return [allMatches lastObject];
}
- (IRRemoteResourceDownloadOperation *) prospectiveOperationForURL:(NSURL *)anURL enqueue:(BOOL)enqueuesOperation {
__block __typeof__(self) nrSelf = self;
__block IRRemoteResourceDownloadOperation *operation = nil;
operation = [IRRemoteResourceDownloadOperation operationWithURL:anURL path:[self pathForCachedContentsOfRemoteURL:anURL usedProspectiveURL:NULL] prelude: ^ {
[nrSelf.delegate remoteResourcesManager:nrSelf didBeginDownloadingResourceAtURL:operation.url];
} completion: ^ {
BOOL didFinish = !!(operation.path);
NSString *operationPath = operation.path;
NSURL *operationURL = operation.url;
if (didFinish) {
[operation retain];
dispatch_async(dispatch_get_main_queue(), ^ {
[operation invokeCompletionBlocks];
[operation autorelease];
[nrSelf notifyUpdatedResourceForRemoteURL:operationURL];
[nrSelf.delegate remoteResourcesManager:nrSelf didFinishDownloadingResourceAtURL:operationURL];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^ {
[nrSelf.delegate remoteResourcesManager:nrSelf didFailDownloadingResourceAtURL:operationURL];
});
}
dispatch_async(dispatch_get_main_queue(), ^{
[nrSelf beginSuspendingOperationQueue];
[nrSelf performInBackground: ^ {
[nrSelf enqueueOperationsIfNeeded];
dispatch_async(dispatch_get_main_queue(), ^{
[nrSelf endSuspendingOperationQueue];
});
}];
});
}];
operation.delegate = self;
if (enqueuesOperation)
[self.enqueuedOperations insertObject:operation atIndex:0];
return operation;
}
- (void) remoteResourceDownloadOperationWillBegin:(IRRemoteResourceDownloadOperation *)anOperation {
if ([self.delegate respondsToSelector:@selector(remoteResourcesManager:invokedURLForResourceAtURL:)]) {
NSMutableURLRequest *request = [anOperation underlyingRequest];
request.URL = [self.delegate remoteResourcesManager:self invokedURLForResourceAtURL:request.URL];
}
if (self.onRemoteResourceDownloadOperationWillBegin)
self.onRemoteResourceDownloadOperationWillBegin(anOperation);
}
- (void) retrieveResourceAtURL:(NSURL *)inRemoteURL withCompletionBlock:(void(^)(NSURL *tempFileURLOrNil))aBlock {
[self retrieveResourceAtURL:inRemoteURL usingPriority:NSOperationQueuePriorityNormal forced:NO withCompletionBlock:aBlock];
}
- (void) retrieveResourceAtURL:(NSURL *)anURL usingPriority:(NSOperationQueuePriority)priority forced:(BOOL)forcesReload withCompletionBlock:(void(^)(NSURL *tempFileURLOrNil))aBlock {
NSParameterAssert(anURL);
if (![NSThread isMainThread]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self retrieveResourceAtURL:anURL usingPriority:priority forced:forcesReload withCompletionBlock:aBlock];
});
return;
}
__block __typeof__(self) nrSelf = self;
[nrSelf performInBackground: ^ {
__block IRRemoteResourceDownloadOperation *operation = [self operationWithURL:anURL];
if (!operation) {
operation = [self prospectiveOperationForURL:anURL enqueue:YES];
operation.queuePriority = priority;
[nrSelf addOperation:operation];
[operation appendCompletionBlock:^{
[nrSelf removeOperation:operation];
}];
} else {
if (forcesReload && [nrSelf.queue.operations containsObject:operation]) {
operation = [operation continuationOperationCancellingCurrentOperation:YES];
operation.queuePriority = priority;
[nrSelf addOperation:operation];
[operation appendCompletionBlock:^{
[nrSelf removeOperation:operation];
}];
}
}
if (aBlock) {
[operation appendCompletionBlock: ^ {
NSString *capturedPath = operation.path;
if (![[NSFileManager defaultManager] fileExistsAtPath:capturedPath]) {
[nrSelf performInBackground:^{
aBlock(nil);
}];
return;
}
[nrSelf performInBackground: ^ {
NSCParameterAssert([[NSFileManager defaultManager] fileExistsAtPath:capturedPath]);
aBlock([NSURL fileURLWithPath:capturedPath]);
}];
}];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self beginSuspendingOperationQueue];
[nrSelf performInBackground: ^ {
[self enqueueOperationsIfNeeded];
if ([self.enqueuedOperations containsObject:operation]) {
// Hoist it — This is last come, first serve
[[operation retain] autorelease];
[self.enqueuedOperations removeObject:operation];
[self.enqueuedOperations insertObject:operation atIndex:0];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self endSuspendingOperationQueue];
});
}];
});
}];
}
- (void) enqueueOperationsIfNeeded {
NSParameterAssert([self.queue isSuspended]);
@autoreleasepool {
NSComparator operationQueuePriorityComparator = (NSComparator) ^ (NSOperation *lhs, NSOperation *rhs) {
return (lhs.queuePriority < rhs.queuePriority) ? NSOrderedDescending :
(lhs.queuePriority == rhs.queuePriority) ? NSOrderedSame :
(lhs.queuePriority > rhs.queuePriority) ? NSOrderedAscending : NSOrderedSame;
};
NSArray * (^sorted)(NSArray *) = ^ (NSArray *anArray) {
return [anArray sortedArrayUsingComparator:operationQueuePriorityComparator];
};
NSArray * (^filtered)(NSArray *, BOOL(^)(id, NSDictionary *)) = ^ (NSArray *filteredArray, BOOL(^predicate)(id evaluatedObject, NSDictionary *bindings)) {
return [filteredArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:predicate]];
};
NSArray *usableCurrentOperations = filtered(self.queue.operations, ^ (NSOperation *anOperation, NSDictionary *bindings){
return (BOOL)![anOperation isCancelled];
});
NSArray *usableEnqueuedOperations = filtered(self.enqueuedOperations, ^ (NSOperation *anOperation, NSDictionary *bindings){
return (BOOL)![anOperation isCancelled];
});
for (NSOperation *anOperation in usableCurrentOperations)
NSParameterAssert(![anOperation isCancelled]);
NSArray *sortedCurrentOperations = sorted(self.queue.operations);
NSArray *sortedEnqueuedOperations = sorted(usableEnqueuedOperations);
NSArray *sortedAllOperations = sorted([sortedCurrentOperations arrayByAddingObjectsFromArray:sortedEnqueuedOperations]);
NSArray *legitimateOperations = [sortedAllOperations objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:(NSRange){
0, MIN(self.queue.maxConcurrentOperationCount, [sortedAllOperations count])
}]];
NSArray *insertedOperations = filtered(legitimateOperations, ^ (id evaluatedObject, NSDictionary *bindings) {
return (BOOL)![sortedCurrentOperations containsObject:evaluatedObject];
});
NSArray *postponedOperations = filtered(sortedCurrentOperations, ^ (id evaluatedObject, NSDictionary *bindings) {
return (BOOL)![legitimateOperations containsObject:evaluatedObject];
});
for (NSOperation *anOperation in insertedOperations)
if (![self.queue.operations containsObject:anOperation])
[self.queue addOperation:anOperation];
[self.enqueuedOperations removeObjectsInArray:insertedOperations];
[postponedOperations enumerateObjectsUsingBlock: ^ (IRRemoteResourceDownloadOperation *anOperation, NSUInteger idx, BOOL *stop) {
[self.enqueuedOperations addObject:[anOperation continuationOperationCancellingCurrentOperation:YES]];
}];
}
}
- (NSString *) cacheDirectoryPath {
if (cacheDirectoryPath)
return cacheDirectoryPath;
NSString *prospectivePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:NSStringFromClass([self class])];
NSError *cacheDirectoryCreationError;
if (![[NSFileManager defaultManager] createDirectoryAtPath:prospectivePath withIntermediateDirectories:YES attributes:nil error:&cacheDirectoryCreationError]) {
NSLog(@"Error occurred while creating or assuring cache directory: %@", cacheDirectoryCreationError);
return nil;
}
cacheDirectoryPath = [prospectivePath retain];
return cacheDirectoryPath;
}
- (NSString *) pathForCachedContentsOfRemoteURL:(NSURL *)inRemoteURL usedProspectiveURL:(BOOL *)returnedProspectiveURL {
return [[self cacheDirectoryPath] stringByAppendingPathComponent:IRWebAPIKitNonce()];
}
- (BOOL) clearCacheDirectory {
NSError *error;
BOOL didClear = [[NSFileManager defaultManager] removeItemAtPath:[self cacheDirectoryPath] error:&error];
if (!didClear)
NSLog(@"Error occurred while removing the cache directory; %@", error);
return didClear;
}
- (void) notifyUpdatedResourceForRemoteURL:(NSURL *)inRemoteURL {
inRemoteURL = [[inRemoteURL copy] autorelease];
dispatch_async(dispatch_get_main_queue(), ^ {
[[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:kIRRemoteResourcesManagerDidRetrieveResourceNotification object:inRemoteURL] postingStyle:NSPostASAP coalesceMask:NSNotificationNoCoalescing forModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSRunLoopCommonModes, nil]];
});
}
@end
@implementation IRRemoteResourcesManager (ImageLoading)
- (void) retrieveImageAtURL:(NSURL *)inRemoteURL forced:(BOOL)forcesReload withCompletionBlock:(void(^)(IRRemoteResourcesManagerImage *tempImage))aBlock {
[self retrieveResourceAtURL:inRemoteURL usingPriority:NSOperationQueuePriorityNormal forced:forcesReload withCompletionBlock:^(NSURL *tempFileURLOrNil) {
if (!tempFileURLOrNil)
return;
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
if (aBlock)
aBlock([UIImage imageWithContentsOfFile:[tempFileURLOrNil path]]);
#else
NSParameterAssert(NO);
#endif
}];
}
@end