/
WebViewProxy.m
269 lines (259 loc) · 11.2 KB
/
WebViewProxy.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
#include "WebViewProxy.h"
static NSMutableArray* requestMatchers;
static NSPredicate* webViewUserAgentTest;
static NSPredicate* webViewProxyLoopDetection;
// A request matcher, which matches a UIWebView request to a registered WebViewProxyHandler
@interface WVPRequestMatcher : NSObject
@property (strong,nonatomic) NSPredicate* predicate;
@property (copy) WVPHandler handler;
+ (WVPRequestMatcher*)matchWithPredicate:(NSPredicate*)predicate handler:(WVPHandler)handler;
@end
@implementation WVPRequestMatcher
@synthesize predicate=_predicate, handler=_handler;
+ (WVPRequestMatcher*)matchWithPredicate:(NSPredicate *)predicate handler:(WVPHandler)handler {
WVPRequestMatcher* matcher = [[WVPRequestMatcher alloc] init];
matcher.handler = handler;
matcher.predicate = predicate;
return matcher;
}
@end
// This is the proxy response object, through which we send responses
@implementation WVPResponse {
NSURLRequest* _request;
NSURLProtocol* _protocol;
NSMutableDictionary* _headers;
BOOL _stopped;
}
@synthesize cachePolicy=_cachePolicy, request=_request;
- (id)_initWithRequest:(NSURLRequest *)request protocol:(NSURLProtocol*)protocol {
if (self = [super init]) {
_request = request;
_protocol = protocol;
_headers = [NSMutableDictionary dictionary];
_cachePolicy = NSURLCacheStorageNotAllowed;
}
return self;
}
- (void) _stopLoading {
_stopped = YES;
}
// High level API
- (void)respondWithImage:(UIImage *)image {
[self respondWithImage:image mimeType:nil];
}
- (void)respondWithImage:(UIImage *)image mimeType:(NSString *)mimeType {
NSData* data = nil;
if (!mimeType) {
NSString* extension = _protocol.request.URL.pathExtension;
if ([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"]) {
mimeType = @"image/jpg";
} else {
if (![extension isEqualToString:@"png"]) {
NSLog(@"WebViewProxy: responding with default mimetype image/png");
}
mimeType = @"image/png";
}
}
if ([mimeType isEqualToString:@"image/jpg"]) {
data = UIImageJPEGRepresentation(image, 1.0);
} else if ([mimeType isEqualToString:@"image/png"]) {
data = UIImagePNGRepresentation(image);
}
[self respondWithData:data mimeType:mimeType];
}
- (void)respondWithJSON:(NSDictionary *)jsonObject {
NSData* data = [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:nil];
[self respondWithData:data mimeType:@"application/json"];
}
- (void)respondWithText:(NSString *)text {
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
[self respondWithData:data mimeType:@"text/plain"];
}
- (void)respondWithHTML:(NSString *)html {
NSData* data = [html dataUsingEncoding:NSUTF8StringEncoding];
[self respondWithData:data mimeType:@"text/html"];
}
// Low level API
- (void)setHeader:(NSString *)headerName value:(NSString *)headerValue {
_headers[headerName] = headerValue;
}
- (void)setHeaders:(NSDictionary *)headers {
for (NSString* headerName in headers) {
[self setHeader:headerName value:headers[headerName]];
}
}
- (void)respondWithData:(NSData *)data mimeType:(NSString *)mimeType {
[self respondWithData:data mimeType:mimeType statusCode:200];
}
- (void)respondWithError:(NSInteger)statusCode text:(NSString *)text {
// TODO We need to add an error responder to signal a network error, as opposed to an HTTP error
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
[self respondWithData:data mimeType:@"text/plain" statusCode:statusCode];
}
- (void)respondWithData:(NSData *)data mimeType:(NSString *)mimeType statusCode:(NSInteger)statusCode {
if (_stopped) { return; }
if (!_headers[@"Content-Type"]) {
if (!mimeType) {
mimeType = [self _mimeTypeOf:_protocol.request.URL.pathExtension];
}
if (mimeType) {
_headers[@"Content-Type"] = mimeType;
}
}
if (!_headers[@"Content-Length"]) {
_headers[@"Content-Length"] = [NSString stringWithFormat:@"%d", data.length];
}
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:_protocol.request.URL statusCode:statusCode HTTPVersion:@"HTTP/1.1" headerFields:_headers];
[_protocol.client URLProtocol:_protocol didReceiveResponse:response cacheStoragePolicy:_cachePolicy];
[_protocol.client URLProtocol:_protocol didLoadData:data];
[_protocol.client URLProtocolDidFinishLoading:_protocol];
}
- (NSString*) _mimeTypeOf:(NSString*)pathExtension {
static NSDictionary* mimeTypes = nil;
if (mimeTypes == nil) {
mimeTypes = @{
@"png": @"image/png",
@"jpg": @"image/jpg",
@"jpeg": @"image/jpg",
@"woff": @"font/woff",
@"ttf": @"font/opentype",
@"m4a": @"audio/mp4a-latm",
@"js": @"application/javascript; charset=utf-8",
@"html": @"text/html; charset=utf-8"
};
}
return mimeTypes[pathExtension];
}
// Pipe API
- (void)pipeResponse:(NSURLResponse *)response {
[self pipeResponse:response cachingAllowed:NO];
}
- (void)pipeResponse:(NSURLResponse *)response cachingAllowed:(BOOL)cachingAllowed {
if (_stopped) { return; }
NSURLCacheStoragePolicy cachePolicy = cachingAllowed ? NSURLCacheStorageAllowed : NSURLCacheStorageNotAllowed;
[_protocol.client URLProtocol:_protocol didReceiveResponse:response cacheStoragePolicy:cachePolicy];
}
- (void)pipeData:(NSData *)data {
if (_stopped) { return; }
[_protocol.client URLProtocol:_protocol didLoadData:data];
}
- (void)pipeEnd {
if (_stopped) { return; }
[_protocol.client URLProtocolDidFinishLoading:_protocol];
}
// NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self pipeResponse:response];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self pipeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self pipeEnd];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self pipeEnd];
}
@end
// The NSURLProtocol implementation that allows us to intercept requests.
@interface WebViewProxyURLProtocol : NSURLProtocol
@property (strong,nonatomic) WVPResponse* proxyResponse;
@property (strong,nonatomic) WVPRequestMatcher* requestMatcher;
+ (WVPRequestMatcher*)findRequestMatcher:(NSURL*)url;
@end
@implementation WebViewProxyURLProtocol {
NSMutableURLRequest* _correctedRequest;
}
@synthesize proxyResponse=_proxyResponse, requestMatcher=_requestMatcher;
+ (WVPRequestMatcher *)findRequestMatcher:(NSURL *)url {
for (WVPRequestMatcher* requestMatcher in requestMatchers) {
if ([requestMatcher.predicate evaluateWithObject:url]) {
return requestMatcher;
}
}
return nil;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
NSString* userAgent = request.allHTTPHeaderFields[@"User-Agent"];
if (userAgent && ![webViewUserAgentTest evaluateWithObject:userAgent]) { return NO; }
if ([webViewProxyLoopDetection evaluateWithObject:request.URL]) { return NO; }
return ([self findRequestMatcher:request.URL] != nil);
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
// TODO Implement this here, or expose it through WebViewProxyResponse?
return NO;
}
- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client {
if (self = [super initWithRequest:request cachedResponse:cachedResponse client:client]) {
// TODO How to handle cachedResponse?
_correctedRequest = request.mutableCopy;
NSString* correctedFragment;
if (_correctedRequest.URL.fragment) {
correctedFragment = @"__webviewproxyreq__";
} else {
correctedFragment = @"#__webviewproxyreq__";
}
_correctedRequest.URL = [NSURL URLWithString:[request.URL.absoluteString stringByAppendingString:correctedFragment]];
self.requestMatcher = [self.class findRequestMatcher:request.URL];
self.proxyResponse = [[WVPResponse alloc] _initWithRequest:request protocol:self];
}
return self;
}
- (void)startLoading {
self.requestMatcher.handler(_correctedRequest, self.proxyResponse);
}
- (void)stopLoading {
[self.proxyResponse _stopLoading];
_correctedRequest = nil;
self.proxyResponse = nil;
// TODO Notify self.requestMatcher.handler to stop loading, which in turn should notify WVPResponse handler (which in turn registered with e.g. [response onStopLoading:^(void) { ... }];.
}
@end
// This is the actual WebViewProxy API
@interface WebViewProxy (hidden)
+ (NSString *)_normalizePath:(NSString *)path;
@end
@implementation WebViewProxy
+ (void)handleRequestsWithScheme:(NSString *)scheme handler:(WVPHandler)handler {
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"scheme MATCHES[cd] %@", scheme];
[self handleRequestsMatching:predicate handler:handler];
}
+ (void)handleRequestsWithHost:(NSString *)host handler:(WVPHandler)handler {
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"host MATCHES[cd] %@", host];
[self handleRequestsMatching:predicate handler:handler];
}
+ (void)handleRequestsWithHost:(NSString *)host path:(NSString *)path handler:(WVPHandler)handler {
path = [self _normalizePath:path];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"host MATCHES[cd] %@ AND path MATCHES[cd] %@", host, path];
[self handleRequestsMatching:predicate handler:handler];
}
+ (void)handleRequestsWithHost:(NSString *)host pathPrefix:(NSString *)pathPrefix handler:(WVPHandler)handler {
pathPrefix = [self _normalizePath:pathPrefix];
NSString* pathPrefixRegex = [NSString stringWithFormat:@"^%@.*", pathPrefix];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"host MATCHES[cd] %@ AND path MATCHES[cd] %@", host, pathPrefixRegex];
[self handleRequestsMatching:predicate handler:handler];
}
+ (void)handleRequestsMatching:(NSPredicate*)predicate handler:(WVPHandler)handler {
if (!requestMatchers) {
requestMatchers = [NSMutableArray array];
webViewUserAgentTest = [NSPredicate predicateWithFormat:@"self MATCHES '^Mozilla.*Mac OS X.*'"];
webViewProxyLoopDetection = [NSPredicate predicateWithFormat:@"self.fragment MATCHES '__webviewproxyreq__'"];
// e.g. "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10A403"
[NSURLProtocol registerClass:[WebViewProxyURLProtocol class]];
}
// Match on any property of NSURL, e.g. "scheme MATCHES 'http' AND host MATCHES 'www.google.com'"
[requestMatchers addObject:[WVPRequestMatcher matchWithPredicate:predicate handler:handler]];
}
@end
@implementation WebViewProxy (hidden)
+ (NSString *)_normalizePath:(NSString *)path {
if (![path hasPrefix:@"/"]) {
// Paths always being with "/", so help out people who forget it
path = [@"/" stringByAppendingString:path];
}
return path;
}
@end