-
Notifications
You must be signed in to change notification settings - Fork 197
/
RNCachingURLProtocol.m
296 lines (253 loc) · 9.8 KB
/
RNCachingURLProtocol.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
//
// RNCachingURLProtocol.m
//
// Created by Robert Napier on 1/10/12.
// Copyright (c) 2012 Rob Napier.
//
// This code is licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#import "RNCachingURLProtocol.h"
#import "Reachability.h"
#import "NSString+Sha1.h"
#define WORKAROUND_MUTABLE_COPY_LEAK 1
#if WORKAROUND_MUTABLE_COPY_LEAK
// required to workaround http://openradar.appspot.com/11596316
@interface NSURLRequest(MutableCopyWorkaround)
- (id) mutableCopyWorkaround;
@end
#endif
@interface RNCachedData : NSObject <NSCoding>
@property (nonatomic, readwrite, strong) NSData *data;
@property (nonatomic, readwrite, strong) NSURLResponse *response;
@property (nonatomic, readwrite, strong) NSURLRequest *redirectRequest;
@end
static NSString *RNCachingURLHeader = @"X-RNCache";
@interface RNCachingURLProtocol () // <NSURLConnectionDelegate, NSURLConnectionDataDelegate> iOS5-only
@property (nonatomic, readwrite, strong) NSURLConnection *connection;
@property (nonatomic, readwrite, strong) NSMutableData *data;
@property (nonatomic, readwrite, strong) NSURLResponse *response;
- (void)appendData:(NSData *)newData;
@end
static NSObject *RNCachingSupportedSchemesMonitor;
static NSSet *RNCachingSupportedSchemes;
@implementation RNCachingURLProtocol
@synthesize connection = connection_;
@synthesize data = data_;
@synthesize response = response_;
+ (void)initialize
{
if (self == [RNCachingURLProtocol class])
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
RNCachingSupportedSchemesMonitor = [NSObject new];
});
[self setSupportedSchemes:[NSSet setWithObject:@"http"]];
}
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
// only handle http requests we haven't marked with our header.
if ([[self supportedSchemes] containsObject:[[request URL] scheme]] &&
([request valueForHTTPHeaderField:RNCachingURLHeader] == nil))
{
return YES;
}
return NO;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
return request;
}
- (NSString *)cachePathForRequest:(NSURLRequest *)aRequest
{
// This stores in the Caches directory, which can be deleted when space is low, but we only use it for offline access
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [[[aRequest URL] absoluteString] sha1];
return [cachesPath stringByAppendingPathComponent:fileName];
}
- (void)startLoading
{
if (![self useCache]) {
NSMutableURLRequest *connectionRequest =
#if WORKAROUND_MUTABLE_COPY_LEAK
[[self request] mutableCopyWorkaround];
#else
[[self request] mutableCopy];
#endif
// we need to mark this request with our header so we know not to handle it in +[NSURLProtocol canInitWithRequest:].
[connectionRequest setValue:@"" forHTTPHeaderField:RNCachingURLHeader];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:connectionRequest
delegate:self];
[self setConnection:connection];
}
else {
RNCachedData *cache = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cachePathForRequest:[self request]]];
if (cache) {
NSData *data = [cache data];
NSURLResponse *response = [cache response];
NSURLRequest *redirectRequest = [cache redirectRequest];
if (redirectRequest) {
[[self client] URLProtocol:self wasRedirectedToRequest:redirectRequest redirectResponse:response];
} else {
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; // we handle caching ourselves.
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}
}
else {
[[self client] URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotConnectToHost userInfo:nil]];
}
}
}
- (void)stopLoading
{
[[self connection] cancel];
}
// NSURLConnection delegates (generally we pass these on to our client)
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
// Thanks to Nick Dowell https://gist.github.com/1885821
if (response != nil) {
NSMutableURLRequest *redirectableRequest =
#if WORKAROUND_MUTABLE_COPY_LEAK
[request mutableCopyWorkaround];
#else
[request mutableCopy];
#endif
// We need to remove our header so we know to handle this request and cache it.
// There are 3 requests in flight: the outside request, which we handled, the internal request,
// which we marked with our header, and the redirectableRequest, which we're modifying here.
// The redirectable request will cause a new outside request from the NSURLProtocolClient, which
// must not be marked with our header.
[redirectableRequest setValue:nil forHTTPHeaderField:RNCachingURLHeader];
NSString *cachePath = [self cachePathForRequest:[self request]];
RNCachedData *cache = [RNCachedData new];
[cache setResponse:response];
[cache setData:[self data]];
[cache setRedirectRequest:redirectableRequest];
[NSKeyedArchiver archiveRootObject:cache toFile:cachePath];
[[self client] URLProtocol:self wasRedirectedToRequest:redirectableRequest redirectResponse:response];
return redirectableRequest;
} else {
return request;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[[self client] URLProtocol:self didLoadData:data];
[self appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[self client] URLProtocol:self didFailWithError:error];
[self setConnection:nil];
[self setData:nil];
[self setResponse:nil];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self setResponse:response];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; // We cache ourselves.
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[[self client] URLProtocolDidFinishLoading:self];
NSString *cachePath = [self cachePathForRequest:[self request]];
RNCachedData *cache = [RNCachedData new];
[cache setResponse:[self response]];
[cache setData:[self data]];
[NSKeyedArchiver archiveRootObject:cache toFile:cachePath];
[self setConnection:nil];
[self setData:nil];
[self setResponse:nil];
}
- (BOOL) useCache
{
BOOL reachable = (BOOL) [[Reachability reachabilityWithHostName:[[[self request] URL] host]] currentReachabilityStatus] != NotReachable;
return !reachable;
}
- (void)appendData:(NSData *)newData
{
if ([self data] == nil) {
[self setData:[newData mutableCopy]];
}
else {
[[self data] appendData:newData];
}
}
+ (NSSet *)supportedSchemes {
NSSet *supportedSchemes;
@synchronized(RNCachingSupportedSchemesMonitor)
{
supportedSchemes = RNCachingSupportedSchemes;
}
return supportedSchemes;
}
+ (void)setSupportedSchemes:(NSSet *)supportedSchemes
{
@synchronized(RNCachingSupportedSchemesMonitor)
{
RNCachingSupportedSchemes = supportedSchemes;
}
}
@end
static NSString *const kDataKey = @"data";
static NSString *const kResponseKey = @"response";
static NSString *const kRedirectRequestKey = @"redirectRequest";
@implementation RNCachedData
@synthesize data = data_;
@synthesize response = response_;
@synthesize redirectRequest = redirectRequest_;
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:[self data] forKey:kDataKey];
[aCoder encodeObject:[self response] forKey:kResponseKey];
[aCoder encodeObject:[self redirectRequest] forKey:kRedirectRequestKey];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self != nil) {
[self setData:[aDecoder decodeObjectForKey:kDataKey]];
[self setResponse:[aDecoder decodeObjectForKey:kResponseKey]];
[self setRedirectRequest:[aDecoder decodeObjectForKey:kRedirectRequestKey]];
}
return self;
}
@end
#if WORKAROUND_MUTABLE_COPY_LEAK
@implementation NSURLRequest(MutableCopyWorkaround)
- (id) mutableCopyWorkaround {
NSMutableURLRequest *mutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:[self URL]
cachePolicy:[self cachePolicy]
timeoutInterval:[self timeoutInterval]];
[mutableURLRequest setAllHTTPHeaderFields:[self allHTTPHeaderFields]];
if ([self HTTPBodyStream]) {
[mutableURLRequest setHTTPBodyStream:[self HTTPBodyStream]];
} else {
[mutableURLRequest setHTTPBody:[self HTTPBody]];
}
[mutableURLRequest setHTTPMethod:[self HTTPMethod]];
return mutableURLRequest;
}
@end
#endif