This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
RESTResource.m
382 lines (295 loc) · 11 KB
/
RESTResource.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
//
// RESTResource.m
// CouchCocoa
//
// Created by Jens Alfke on 5/28/11.
// Copyright 2011 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#import "RESTResource.h"
#import "RESTInternal.h"
#import "RESTCache.h"
#import "RESTBase64.h"
@implementation RESTResource
@synthesize parent=_parent, relativePath=_relativePath, delegate=_delegate,
cachedURL=_cachedURL;
- (id) initWithURL: (NSURL*)url {
NSParameterAssert(url);
self = [super init];
if (self) {
_url = [url retain];
}
return self;
}
- (id) initUntitledWithParent: (RESTResource*)parent {
NSParameterAssert(parent);
self = [super init];
if (self) {
_parent = [parent retain];
}
return self;
}
- (id) initWithParent: (RESTResource*)parent relativePath: (NSString*)path {
NSParameterAssert(path);
self = [self initUntitledWithParent: parent];
if (self) {
_relativePath = [path copy];
}
return self;
}
- (void) dealloc
{
[_owningCache resourceBeingDealloced: self];
[_activeOperations release];
[_credential release];
[_protectionSpace release];
[_eTag release];
[_lastModified release];
[_url release];
[_cachedURL release];
[_relativePath release];
[_parent release];
[super dealloc];
}
- (RESTCache*) owningCache {
return _owningCache;
}
- (void) setOwningCache:(RESTCache *)cache {
NSAssert(!cache || !_owningCache, @"CouchDocument cannot belong to two caches");
_owningCache = cache;
}
- (NSString*) description {
return [NSString stringWithFormat: @"%@[%@]",
[self class], (_url ? [_url absoluteString] : _relativePath)];
}
- (NSURL*) URL {
if (_url)
return _url;
else if (_relativePath)
return [_parent.URL URLByAppendingPathComponent: _relativePath];
else
return nil;
}
- (void) setURL: (NSURL*)url {
NSParameterAssert(url);
NSAssert(!_parent, @"Can only change URL of root");
[_url autorelease];
_url = [url retain];
}
- (void) assignedRelativePath: (NSString*)relativePath {
NSParameterAssert(relativePath);
NSAssert(!_relativePath, @"Already has relativePath %@", _relativePath);
_relativePath = [relativePath copy];
}
- (void) callDelegate: (SEL)selector forResource: (RESTResource*)resource withObject: (id)object {
if ([_delegate respondsToSelector: selector])
[(id)_delegate performSelector: selector withObject: resource withObject: object];
[_parent callDelegate: selector forResource: resource withObject: object];
}
#pragma mark -
#pragma mark HTTP METHODS:
- (NSMutableURLRequest*) requestWithMethod: (NSString*)method
parameters: (NSDictionary*)parameters
{
NSMutableString* queries = nil;
BOOL firstQuery;
NSURL* url = self.URL;
NSAssert1(url, @"Resource has no URL: %@", self);
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL: url];
request.HTTPMethod = method;
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
for (NSString* key in parameters) {
NSString* value = [[parameters objectForKey: key] description];
if ([key hasPrefix: @"?"]) {
if (!queries) {
queries = [NSMutableString string];
firstQuery = (url.query.length == 0);
}
if (firstQuery) {
[queries appendString: key]; // already includes leading '?'
firstQuery = NO;
} else {
[queries appendString: @"&"];
[queries appendString: [key substringFromIndex: 1]];
}
[queries appendString: @"="];
CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)value,
NULL, (CFStringRef)@"&",
kCFStringEncodingUTF8);
[queries appendString: (id)escaped];
CFRelease(escaped);
} else {
[request setValue: value forHTTPHeaderField: key];
}
}
if (queries) {
NSString* urlStr = [url.absoluteString stringByAppendingString: queries];
request.URL = [NSURL URLWithString: urlStr];
}
// if the URL contains basic-auth credentials, use them without waiting for 401 challenge
NSString* username = [request.URL user];
NSString* password = [request.URL password];
if (username && password) {
NSString *creds = [NSString stringWithFormat:@"%@:%@", username, password];
creds = [RESTBase64 encode: [creds dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:[NSString stringWithFormat:@"Basic %@", creds] forHTTPHeaderField:@"Authorization"];
}
return request;
}
- (RESTOperation*) sendRequest: (NSMutableURLRequest*)request {
[self callDelegate: @selector(resource:willSendRequest:) forResource: self withObject: request];
return [[[RESTOperation alloc] initWithResource: self request: request] autorelease];
}
- (RESTOperation*) sendHTTP: (NSString*)method parameters: (NSDictionary*)parameters {
NSMutableURLRequest* request = [self requestWithMethod: method parameters: parameters];
// Conditional GET?
if ([method isEqualToString: @"GET"] && [_cachedURL isEqual: request.URL]) {
if (_eTag)
[request setValue: _eTag forHTTPHeaderField: @"If-None-Match"];
if (_lastModified)
[request setValue: _lastModified forHTTPHeaderField: @"If-Modified-Since"];
}
return [self sendRequest: request];
}
- (RESTOperation*) GET {
return [self sendHTTP: @"GET" parameters: nil];
}
- (RESTOperation*) POST: (NSData*)body
parameters: (NSDictionary*)parameters
{
NSMutableURLRequest* request = [self requestWithMethod: @"POST" parameters: parameters];
if (body)
[request setHTTPBody:body];
return [self sendRequest: request];
}
- (void) createdByPOST: (RESTOperation*)op {
NSString* location = [op.responseHeaders objectForKey: @"Location"];
if (location) {
NSURL* locationURL = [NSURL URLWithString: location relativeToURL: _parent.URL];
if (locationURL) {
[self assignedRelativePath: [locationURL lastPathComponent]];
if (![self.URL isEqual: locationURL])
_url = [locationURL retain];
}
}
}
- (RESTOperation*) PUT: (NSData*)body
parameters: (NSDictionary*)parameters
{
if (_relativePath) {
NSMutableURLRequest* request = [self requestWithMethod: @"PUT" parameters: parameters];
if (body)
[request setHTTPBody:body];
return [self sendRequest: request];
} else {
// If I have no URL yet, do a POST to my parent:
RESTOperation* op = [self.parent POST: body parameters: parameters];
[op onCompletion: ^{
// ...then when done, use the Location: header of the result to generate my name/URL:
if (!op.error) {
[self createdByPOST: op];
}
}];
return op;
}
}
static NSDictionary* addJSONType(NSDictionary* parameters) {
if ([parameters objectForKey: @"Content-Type"])
return parameters;
NSMutableDictionary* moreParams = parameters ? [parameters mutableCopy]
: [[NSMutableDictionary alloc] init];
[moreParams setObject: @"application/json" forKey: @"Content-Type"];
return [moreParams autorelease];
}
- (RESTOperation*) PUTJSON: (id)body parameters: (NSDictionary*)parameters {
return [self PUT: [RESTBody dataWithJSONObject: body]
parameters: addJSONType(parameters)];
}
- (RESTOperation*) POSTJSON: (id)body parameters: (NSDictionary*)parameters {
NSMutableURLRequest* request = [self requestWithMethod: @"POST"
parameters: addJSONType(parameters)];
[request setHTTPBody: [RESTBody dataWithJSONObject: body]];
return [self sendRequest: request];
}
- (RESTOperation*) DELETE {
return [self sendHTTP: @"DELETE" parameters: nil];
}
#pragma mark -
#pragma mark CONTENT:
@synthesize eTag=_eTag, lastModified=_lastModified;
- (BOOL) cacheResponse: (RESTOperation*)op {
if (op.isSuccessful && op.isGET) {
NSString* eTag = [op.responseHeaders objectForKey: @"Etag"];
NSString* lastModified = [op.responseHeaders objectForKey: @"Last-Modified"];
if (eTag || lastModified) {
self.eTag = eTag;
self.lastModified = lastModified;
self.cachedURL = op.URL;
return YES;
}
} else if (op == nil) {
self.eTag = nil;
self.lastModified = nil;
self.cachedURL = nil;
return YES;
}
return NO;
}
#pragma mark -
#pragma mark CALLBACKS:
@synthesize activeOperations=_activeOperations;
- (void) setTracksActiveOperations: (BOOL)tracks {
if (tracks && !_activeOperations)
_activeOperations = [[NSMutableSet alloc] init];
else if (!tracks && _activeOperations) {
[_activeOperations release];
_activeOperations = nil;
}
}
- (BOOL) tracksActiveOperations {
return _activeOperations != nil;
}
- (void) operationDidStart: (RESTOperation*)op {
[_activeOperations addObject: op];
[_parent operationDidStart: op];
}
- (NSError*) operation: (RESTOperation*)op willCompleteWithError: (NSError*)error {
NSHTTPURLResponse* response = op.response;
if (response)
[self callDelegate: @selector(resource:didReceiveResponse:)
forResource: self withObject: response];
if (op.isGET) {
if (op.httpStatus == 304) {
error = nil; // 304 Not Modified is not an error
}
}
return error;
}
- (void) operationDidComplete: (RESTOperation*)op {
[_activeOperations removeObject: op];
[_parent operationDidComplete: op];
}
#pragma mark -
#pragma mark ACCESS CONTROL:
- (void) setCredential:(NSURLCredential *)credential {
[_credential autorelease];
_credential = [credential retain];
}
- (NSURLCredential*) credentialForOperation: (RESTOperation*)op {
return _credential ? _credential : [_parent credentialForOperation: op];
}
- (void) setProtectionSpace: (NSURLProtectionSpace*)protectionSpace {
[_protectionSpace autorelease];
_protectionSpace = [protectionSpace retain];
}
- (NSURLProtectionSpace*) protectionSpaceForOperation: (RESTOperation*)op {
return _protectionSpace ? _protectionSpace : [_parent protectionSpaceForOperation: op];
}
@end