forked from facebookarchive/three20
/
TTURLRequestQueue.m
622 lines (520 loc) · 18.2 KB
/
TTURLRequestQueue.m
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
621
622
#import "Three20/TTURLRequestQueue.h"
#import "Three20/TTURLRequest.h"
#import "Three20/TTURLResponse.h"
#import "Three20/TTURLCache.h"
//////////////////////////////////////////////////////////////////////////////////////////////////
static const NSTimeInterval kFlushDelay = 0.3;
static const NSTimeInterval kTimeout = 300.0;
static const NSInteger kLoadMaxRetries = 2;
static const NSInteger kMaxConcurrentLoads = 5;
static NSUInteger kDefaultMaxContentLength = 150000;
static NSString* kSafariUserAgent = @"Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_2 like Mac OS X;\
en-us) AppleWebKit/525.181 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11 Safari/525.20";
static TTURLRequestQueue* gMainQueue = nil;
//////////////////////////////////////////////////////////////////////////////////////////////////
@interface TTRequestLoader : NSObject {
NSString* _url;
TTURLRequestQueue* _queue;
NSString* _cacheKey;
TTURLRequestCachePolicy _cachePolicy;
NSTimeInterval _cacheExpirationAge;
NSMutableArray* _requests;
NSURLConnection* _connection;
NSHTTPURLResponse* _response;
NSMutableData* _responseData;
int _retriesLeft;
}
@property(nonatomic,readonly) NSArray* requests;
@property(nonatomic,readonly) NSString* url;
@property(nonatomic,readonly) NSString* cacheKey;
@property(nonatomic,readonly) TTURLRequestCachePolicy cachePolicy;
@property(nonatomic,readonly) NSTimeInterval cacheExpirationAge;
@property(nonatomic,readonly) BOOL isLoading;
- (id)initForRequest:(TTURLRequest*)request queue:(TTURLRequestQueue*)queue;
- (void)addRequest:(TTURLRequest*)request;
- (void)removeRequest:(TTURLRequest*)request;
- (void)load:(NSURL*)url;
- (BOOL)cancel:(TTURLRequest*)request;
@end
@implementation TTRequestLoader
@synthesize url = _url, requests = _requests, cacheKey = _cacheKey,
cachePolicy = _cachePolicy, cacheExpirationAge = _cacheExpirationAge;
- (id)initForRequest:(TTURLRequest*)request queue:(TTURLRequestQueue*)queue {
if (self = [super init]) {
_url = [request.url copy];
_queue = queue;
_cacheKey = [request.cacheKey retain];
_cachePolicy = request.cachePolicy;
_cacheExpirationAge = request.cacheExpirationAge;
_requests = [[NSMutableArray alloc] init];
_connection = nil;
_retriesLeft = kLoadMaxRetries;
_response = nil;
_responseData = nil;
[self addRequest:request];
}
return self;
}
- (void)dealloc {
[_connection cancel];
[_connection release];
[_response release];
[_responseData release];
[_url release];
[_cacheKey release];
[_requests release];
[super dealloc];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connectToURL:(NSURL*)url {
TTLOG(@"Connecting to %@", _url);
TTNetworkRequestStarted();
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:kTimeout];
[urlRequest setValue:_queue.userAgent forHTTPHeaderField:@"User-Agent"];
if (_requests.count == 1) {
TTURLRequest* request = [_requests objectAtIndex:0];
[urlRequest setHTTPShouldHandleCookies:request.shouldHandleCookies];
NSString* method = request.httpMethod;
if (method) {
[urlRequest setHTTPMethod:method];
}
NSString* contentType = request.contentType;
if (contentType) {
[urlRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
}
NSData* body = request.httpBody;
if (body) {
[urlRequest setHTTPBody:body];
}
NSMutableDictionary *headers = request.headers;
if (headers && [headers count] > 0){
for (NSString *key in headers) {
[urlRequest setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
_connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
- (void)cancel {
NSArray* requestsToCancel = [_requests copy];
for (id request in requestsToCancel) {
[self cancel:request];
}
[requestsToCancel release];
}
- (NSError*)processResponse:(NSHTTPURLResponse*)response data:(id)data {
for (TTURLRequest* request in _requests) {
NSError* error = [request.response request:request processResponse:response data:data];
if (error) {
return error;
}
}
return nil;
}
- (void)dispatchLoaded:(NSDate*)timestamp {
for (TTURLRequest* request in [[_requests copy] autorelease]) {
request.timestamp = timestamp;
request.isLoading = NO;
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(requestDidFinishLoad:)]) {
[delegate requestDidFinishLoad:request];
}
}
}
}
- (void)dispatchError:(NSError*)error {
for (TTURLRequest* request in [[_requests copy] autorelease]) {
request.isLoading = NO;
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[delegate request:request didFailLoadWithError:error];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// NSURLConnectionDelegate
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response {
_response = [response retain];
NSDictionary* headers = [response allHeaderFields];
int contentLength = [[headers objectForKey:@"Content-Length"] intValue];
if (contentLength > _queue.maxContentLength && _queue.maxContentLength) {
TTLOG(@"MAX CONTENT LENGTH EXCEEDED (%d) %@", contentLength, _url);
[self cancel];
}
_responseData = [[NSMutableData alloc] initWithCapacity:contentLength];
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
TTNetworkRequestStopped();
if (_response.statusCode == 200) {
[_queue performSelector:@selector(loader:didLoadResponse:data:) withObject:self
withObject:_response withObject:_responseData];
} else {
TTLOG(@" FAILED LOADING (%d) %@", _response.statusCode, _url);
NSError* error = [NSError errorWithDomain:NSURLErrorDomain code:_response.statusCode
userInfo:nil];
[_queue performSelector:@selector(loader:didFailLoadWithError:) withObject:self
withObject:error];
}
[_responseData release];
_responseData = nil;
[_connection release];
_connection = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
TTLOG(@" FAILED LOADING %@ FOR %@", _url, error);
TTNetworkRequestStopped();
[_responseData release];
_responseData = nil;
[_connection release];
_connection = nil;
if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCannotFindHost
&& _retriesLeft) {
// If there is a network error then we will wait and retry a few times just in case
// it was just a temporary blip in connectivity
--_retriesLeft;
[self load:[NSURL URLWithString:_url]];
} else {
[_queue performSelector:@selector(loader:didFailLoadWithError:) withObject:self
withObject:error];
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isLoading {
return !!_connection;
}
- (void)addRequest:(TTURLRequest*)request {
[_requests addObject:request];
}
- (void)removeRequest:(TTURLRequest*)request {
[_requests removeObject:request];
}
- (void)load:(NSURL*)url {
if (!_connection) {
[self connectToURL:url];
}
}
- (BOOL)cancel:(TTURLRequest*)request {
NSUInteger index = [_requests indexOfObject:request];
if (index != NSNotFound) {
request.isLoading = NO;
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(requestDidCancelLoad:)]) {
[delegate requestDidCancelLoad:request];
}
}
[_requests removeObjectAtIndex:index];
}
if (![_requests count]) {
[_queue performSelector:@selector(loaderDidCancel:wasLoading:) withObject:self
withObject:(id)!!_connection];
if (_connection) {
TTNetworkRequestStopped();
[_connection cancel];
_connection = nil;
}
return NO;
} else {
return YES;
}
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////
@implementation TTURLRequestQueue
@synthesize maxContentLength = _maxContentLength, userAgent = _userAgent, suspended = _suspended,
imageCompressionQuality = _imageCompressionQuality;
+ (TTURLRequestQueue*)mainQueue {
if (!gMainQueue) {
gMainQueue = [[TTURLRequestQueue alloc] init];
}
return gMainQueue;
}
+ (void)setMainQueue:(TTURLRequestQueue*)queue {
if (gMainQueue != queue) {
[gMainQueue release];
gMainQueue = [queue retain];
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init {
if (self == [super init]) {
_loaders = [[NSMutableDictionary alloc] init];
_loaderQueue = [[NSMutableArray alloc] init];
_loaderQueueTimer = nil;
_totalLoading = 0;
_maxContentLength = kDefaultMaxContentLength;
_imageCompressionQuality = 0.75;
_userAgent = [kSafariUserAgent copy];
_suspended = NO;
}
return self;
}
- (void)dealloc {
[_loaders release];
[_loaderQueue release];
[_loaderQueueTimer invalidate];
[_userAgent release];
[super dealloc];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
- (NSData*)loadFromBundle:(NSString*)url error:(NSError**)error {
NSString* path = TTPathForBundleResource([url substringFromIndex:9]);
NSFileManager* fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:path]) {
return [NSData dataWithContentsOfFile:path];
} else {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileReadNoSuchFileError userInfo:nil];
return nil;
}
}
- (NSData*)loadFromDocuments:(NSString*)url error:(NSError**)error {
NSString* path = TTPathForDocumentsResource([url substringFromIndex:12]);
NSFileManager* fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:path]) {
return [NSData dataWithContentsOfFile:path];
} else {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileReadNoSuchFileError userInfo:nil];
return nil;
}
}
- (BOOL)loadFromCache:(NSString*)url cacheKey:(NSString*)cacheKey
expires:(NSTimeInterval)expirationAge fromDisk:(BOOL)fromDisk data:(id*)data
error:(NSError**)error timestamp:(NSDate**)timestamp {
UIImage* image = [[TTURLCache sharedCache] imageForURL:url fromDisk:fromDisk];
if (image) {
*data = image;
return YES;
} else if (fromDisk) {
if (TTIsBundleURL(url)) {
*data = [self loadFromBundle:url error:error];
return YES;
} else if (TTIsDocumentsURL(url)) {
*data = [self loadFromDocuments:url error:error];
return YES;
} else {
*data = [[TTURLCache sharedCache] dataForKey:cacheKey expires:expirationAge
timestamp:timestamp];
if (*data) {
return YES;
}
}
}
return NO;
}
- (BOOL)loadRequestFromCache:(TTURLRequest*)request {
if (!request.cacheKey) {
request.cacheKey = [[TTURLCache sharedCache] keyForURL:request.url];
}
if (request.cachePolicy & (TTURLRequestCachePolicyDisk|TTURLRequestCachePolicyMemory)) {
id data = nil;
NSDate* timestamp = nil;
NSError* error = nil;
if ([self loadFromCache:request.url cacheKey:request.cacheKey
expires:request.cacheExpirationAge
fromDisk:!_suspended && request.cachePolicy & TTURLRequestCachePolicyDisk
data:&data error:&error timestamp:×tamp]) {
request.isLoading = NO;
if (!error) {
error = [request.response request:request processResponse:nil data:data];
}
if (error) {
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[delegate request:request didFailLoadWithError:error];
}
}
} else {
request.timestamp = timestamp;
request.respondedFromCache = YES;
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(requestDidFinishLoad:)]) {
[delegate requestDidFinishLoad:request];
}
}
}
return YES;
}
}
return NO;
}
- (void)executeLoader:(TTRequestLoader*)loader {
id data = nil;
NSDate* timestamp = nil;
NSError* error = nil;
if ((loader.cachePolicy & (TTURLRequestCachePolicyDisk|TTURLRequestCachePolicyMemory))
&& [self loadFromCache:loader.url cacheKey:loader.cacheKey
expires:loader.cacheExpirationAge
fromDisk:loader.cachePolicy & TTURLRequestCachePolicyDisk
data:&data error:&error timestamp:×tamp]) {
if (!error) {
error = [loader processResponse:nil data:data];
}
if (error) {
[loader dispatchError:error];
} else {
[loader dispatchLoaded:timestamp];
}
[_loaders removeObjectForKey:loader.cacheKey];
} else {
++_totalLoading;
[loader load:[NSURL URLWithString:loader.url]];
}
}
- (void)loadNextInQueueDelayed {
if (!_loaderQueueTimer) {
_loaderQueueTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushDelay target:self
selector:@selector(loadNextInQueue) userInfo:nil repeats:NO];
}
}
- (void)loadNextInQueue {
_loaderQueueTimer = nil;
for (int i = 0;
i < kMaxConcurrentLoads && _totalLoading < kMaxConcurrentLoads
&& _loaderQueue.count;
++i) {
TTRequestLoader* loader = [[_loaderQueue objectAtIndex:0] retain];
[_loaderQueue removeObjectAtIndex:0];
[self executeLoader:loader];
[loader release];
}
if (_loaderQueue.count && !_suspended) {
[self loadNextInQueueDelayed];
}
}
- (void)loadNextInQueueAfterLoader:(TTRequestLoader*)loader {
--_totalLoading;
[_loaders removeObjectForKey:loader.cacheKey];
[self loadNextInQueue];
}
- (void)loader:(TTRequestLoader*)loader didLoadResponse:(NSHTTPURLResponse*)response
data:(id)data {
NSError* error = [loader processResponse:response data:data];
if (error) {
[loader dispatchError:error];
} else {
if (!(loader.cachePolicy & TTURLRequestCachePolicyNoCache)) {
[[TTURLCache sharedCache] storeData:data forKey:loader.cacheKey];
}
[loader dispatchLoaded:[NSDate date]];
}
[self loadNextInQueueAfterLoader:loader];
}
- (void)loader:(TTRequestLoader*)loader didFailLoadWithError:(NSError*)error {
[loader dispatchError:error];
[self loadNextInQueueAfterLoader:loader];
}
- (void)loaderDidCancel:(TTRequestLoader*)loader wasLoading:(BOOL)wasLoading {
if (wasLoading) {
[self loadNextInQueueAfterLoader:loader];
} else {
[_loaders removeObjectForKey:loader.cacheKey];
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setSuspended:(BOOL)isSuspended {
// TTLOG(@"SUSPEND LOADING %d", isSuspended);
_suspended = isSuspended;
if (!_suspended) {
[self loadNextInQueue];
} else if (_loaderQueueTimer) {
[_loaderQueueTimer invalidate];
_loaderQueueTimer = nil;
}
}
- (BOOL)sendRequest:(TTURLRequest*)request {
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(requestDidStartLoad:)]) {
[delegate requestDidStartLoad:request];
}
}
if ([self loadRequestFromCache:request]) {
return YES;
}
if (!request.url.length) {
NSError* error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
for (id<TTURLRequestDelegate> delegate in request.delegates) {
if ([delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[delegate request:request didFailLoadWithError:error];
}
}
return NO;
}
request.isLoading = YES;
TTRequestLoader* loader = nil;
if (![request.httpMethod isEqualToString:@"POST"]) {
// Next, see if there is an active loader for the URL and if so join that bandwagon
loader = [_loaders objectForKey:request.cacheKey];
if (loader) {
[loader addRequest:request];
return NO;
}
}
// Finally, create a new loader and hit the network (unless we are suspended)
loader = [[TTRequestLoader alloc] initForRequest:request queue:self];
[_loaders setObject:loader forKey:request.cacheKey];
if (_suspended || _totalLoading == kMaxConcurrentLoads) {
[_loaderQueue addObject:loader];
} else {
++_totalLoading;
[loader load:[NSURL URLWithString:request.url]];
}
[loader release];
return NO;
}
- (void)cancelRequest:(TTURLRequest*)request {
if (request) {
TTRequestLoader* loader = [_loaders objectForKey:request.cacheKey];
if (loader) {
[loader retain];
if (![loader cancel:request]) {
[_loaderQueue removeObject:loader];
}
[loader release];
}
}
}
- (void)cancelRequestsWithDelegate:(id)delegate {
NSMutableArray* requestsToCancel = nil;
for (TTRequestLoader* loader in [_loaders objectEnumerator]) {
for (TTURLRequest* request in loader.requests) {
for (id<TTURLRequestDelegate> requestDelegate in request.delegates) {
if (delegate == requestDelegate) {
if (!requestsToCancel) {
requestsToCancel = [NSMutableArray array];
}
[requestsToCancel addObject:request];
break;
}
}
if ([request.userInfo isKindOfClass:[TTUserInfo class]]) {
TTUserInfo* userInfo = request.userInfo;
if (userInfo.weak && userInfo.weak == delegate) {
if (!requestsToCancel) {
requestsToCancel = [NSMutableArray array];
}
[requestsToCancel addObject:request];
}
}
}
}
for (TTURLRequest* request in requestsToCancel) {
[self cancelRequest:request];
}
}
- (void)cancelAllRequests {
for (TTRequestLoader* loader in [[[_loaders copy] autorelease] objectEnumerator]) {
[loader cancel];
}
}
@end