-
Notifications
You must be signed in to change notification settings - Fork 117
/
DBTransportBaseClient.m
440 lines (384 loc) · 16.8 KB
/
DBTransportBaseClient.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
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
#import <Foundation/Foundation.h>
#import "DBAUTHAccessError.h"
#import "DBAUTHAuthError.h"
#import "DBAUTHRateLimitError.h"
#import "DBAccessTokenProvider+Internal.h"
#import "DBCOMMONPathRootError.h"
#import "DBRequestErrors.h"
#import "DBSDKConstants.h"
#import "DBStoneBase.h"
#import "DBTransportBaseClient.h"
#import "DBTransportBaseConfig.h"
#import "DBTransportBaseHostnameConfig.h"
#pragma mark - Internal serialization helpers
@interface DBTransportBaseClient ()
@property (nonatomic, readonly, copy) DBTransportBaseHostnameConfig *hostnameConfig;
@end
@implementation DBTransportBaseClient
static BOOL kUseFastAsciiEncoding;
static NSLock *kAsciiEscapeSelectorLock;
+ (void)initialize {
[super initialize];
if (self == [DBTransportBaseClient class]) {
kUseFastAsciiEncoding = NO;
kAsciiEscapeSelectorLock = [[NSLock alloc] init];
}
}
- (instancetype)initWithAccessToken:(NSString *)accessToken
tokenUid:(NSString *)tokenUid
transportConfig:(DBTransportBaseConfig *)transportConfig {
DBLongLivedAccessTokenProvider *provider = nil;
if (accessToken) {
provider = [[DBLongLivedAccessTokenProvider alloc] initWithTokenString:accessToken];
}
return [self initWithAccessTokenProvider:provider tokenUid:tokenUid transportConfig:transportConfig];
}
- (instancetype)initWithAccessTokenProvider:(id<DBAccessTokenProvider>)accessTokenProvider
tokenUid:(NSString *)tokenUid
transportConfig:(DBTransportBaseConfig *)transportConfig {
if (self = [super init]) {
_accessTokenProvider = accessTokenProvider;
_tokenUid = [tokenUid copy];
_appKey = transportConfig.appKey;
_appSecret = transportConfig.appSecret;
_hostnameConfig = transportConfig.hostnameConfig ?: [[DBTransportBaseHostnameConfig alloc] init];
NSString *defaultUserAgent = [DBTransportBaseConfig defaultUserAgent];
_userAgent = transportConfig.userAgent ? [[transportConfig.userAgent stringByAppendingString:@"/"]
stringByAppendingString:defaultUserAgent]
: defaultUserAgent;
_asMemberId = transportConfig.asMemberId;
_pathRoot = transportConfig.pathRoot;
_additionalHeaders = transportConfig.additionalHeaders;
}
return self;
}
- (NSDictionary *)headersWithRouteInfo:(NSDictionary<NSString *, NSString *> *)routeAttributes
serializedArg:(NSString *)serializedArg {
return [self headersWithRouteInfo:routeAttributes serializedArg:serializedArg byteOffsetStart:nil byteOffsetEnd:nil];
}
- (NSDictionary *)headersWithRouteInfo:(NSDictionary<NSString *, NSString *> *)routeAttributes
serializedArg:(NSString *)serializedArg
byteOffsetStart:(NSNumber *)byteOffsetStart
byteOffsetEnd:(NSNumber *)byteOffsetEnd {
NSString *routeStyle = routeAttributes[@"style"];
// routeAuthStr is one of user|team|app|noauth|app, user
NSString *routeAuthStr = routeAttributes[@"auth"];
NSArray *routeAuthsSplit = [routeAuthStr componentsSeparatedByString:@","];
NSMutableArray<NSString *> *routeAuths = [NSMutableArray array];
[routeAuthsSplit enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
#pragma unused(idx)
#pragma unused(stop)
[routeAuths addObject:[obj stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
}];
NSMutableDictionary<NSString *, NSString *> *headers = [[NSMutableDictionary alloc] init];
[headers setObject:_userAgent forKey:@"User-Agent"];
BOOL noauth = [routeAuths containsObject:@"noauth"];
if (!noauth) {
if (_asMemberId) {
[headers setObject:_asMemberId forKey:@"Dropbox-Api-Select-User"];
}
if (_pathRoot) {
NSString *pathRootStr = [[self class] serializeStringWithRoute:nil routeArg:_pathRoot];
[headers setObject:pathRootStr forKey:@"Dropbox-Api-Path-Root"];
}
// Order is important here. Route may support multiple auth types, so check from most specific to least.
if (([routeAuths containsObject:@"user"] || [routeAuths containsObject:@"team"]) && (_accessTokenProvider != nil)) {
[headers setObject:[NSString stringWithFormat:@"Bearer %@", _accessTokenProvider.accessToken]
forKey:@"Authorization"];
} else if ([routeAuths containsObject:@"app"] && (_appKey != nil) && (_appSecret != nil)) {
NSString *authString = [NSString stringWithFormat:@"%@:%@", _appKey, _appSecret];
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding];
[headers setObject:[NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]]
forKey:@"Authorization"];
} else {
NSLog(@"Auth info not properly configured. Use custom `DBTransportDefaultConfig` instance to set.");
}
}
if ([routeStyle isEqualToString:@"rpc"]) {
if (serializedArg) {
[headers setObject:@"application/json" forKey:@"Content-Type"];
}
} else if ([routeStyle isEqualToString:@"upload"]) {
[headers setObject:@"application/octet-stream" forKey:@"Content-Type"];
if (serializedArg) {
[headers setObject:serializedArg forKey:@"Dropbox-API-Arg"];
}
} else if ([routeStyle isEqualToString:@"download"]) {
if (serializedArg) {
[headers setObject:serializedArg forKey:@"Dropbox-API-Arg"];
}
}
if (byteOffsetStart && byteOffsetEnd) {
NSString *bytesRangeSpecifier = [NSString
stringWithFormat:@"bytes=%lu-%lu", [byteOffsetStart unsignedLongValue], [byteOffsetEnd unsignedLongValue]];
[headers setObject:bytesRangeSpecifier forKey:@"Range"];
}
if (_additionalHeaders != nil) {
[headers addEntriesFromDictionary:_additionalHeaders];
}
return headers;
}
+ (NSMutableURLRequest *)requestWithHeaders:(NSDictionary *)httpHeaders
url:(NSURL *)url
content:(NSData *)content
stream:(NSInputStream *)stream {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
for (NSString *key in httpHeaders) {
[request addValue:httpHeaders[key] forHTTPHeaderField:key];
}
request.HTTPMethod = @"POST";
if (content) {
request.HTTPBody = content;
}
if (stream) {
request.HTTPBodyStream = stream;
}
return request;
}
- (NSURL *)urlWithRoute:(DBRoute *)route {
NSString *routePrefix = [_hostnameConfig apiV2PrefixWithRoute:route];
return [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@", routePrefix, route.namespace_, route.name]];
}
+ (NSData *)serializeDataWithRoute:(DBRoute *)route routeArg:(id<DBSerializable>)arg {
if (!arg) {
return nil;
}
if (route != nil && route.dataStructSerialBlock) {
return [[self class] jsonDataWithJsonObj:route.dataStructSerialBlock(arg)];
}
NSDictionary *serializedDict = [[arg class] serialize:arg];
return [[self class] jsonDataWithJsonObj:serializedDict];
}
+ (NSString *)serializeStringWithRoute:(DBRoute *)route routeArg:(id<DBSerializable>)arg {
if (!arg) {
return nil;
}
NSData *jsonData = [self serializeDataWithRoute:route routeArg:arg];
if (!jsonData) {
return nil;
}
NSString *asciiEscapedStr = [[self class] asciiEscapeWithString:[[self class] utf8StringWithData:jsonData]];
NSMutableString *filteredStr = [[NSMutableString alloc] initWithString:asciiEscapedStr];
[filteredStr replaceOccurrencesOfString:@"\\/"
withString:@"/"
options:NSLiteralSearch
range:NSMakeRange(0, [filteredStr length])];
return filteredStr;
}
+ (NSData *)jsonDataWithJsonObj:(id)jsonObj {
if (!jsonObj) {
return nil;
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObj options:0 error:&error];
if (!jsonData) {
NSLog(@"Error serializing dictionary: %@", error.localizedDescription);
return nil;
} else {
return jsonData;
}
}
+ (NSString *)utf8StringWithData:(NSData *)jsonData {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
+ (BOOL)useFastAsciiEncoding {
BOOL result;
[kAsciiEscapeSelectorLock lock];
result = kUseFastAsciiEncoding;
[kAsciiEscapeSelectorLock unlock];
return result;
}
+ (void)setUseFastAsciiEncoding:(BOOL)useFastAsciiEncoding {
[kAsciiEscapeSelectorLock lock];
kUseFastAsciiEncoding = useFastAsciiEncoding;
[kAsciiEscapeSelectorLock unlock];
}
+ (NSString *)asciiEscapeWithString:(NSString *)string {
BOOL useFastEncoding = NO;
[kAsciiEscapeSelectorLock lock];
useFastEncoding = kUseFastAsciiEncoding;
[kAsciiEscapeSelectorLock unlock];
NSString *result;
if (useFastEncoding) {
result = [self fast_asciiEscapeWithString:string];
} else {
result = [self slow_asciiEscapeWithString:string];
}
return result;
}
+ (NSString *)slow_asciiEscapeWithString:(NSString *)string {
NSMutableString *result = [[NSMutableString alloc] init];
for (NSUInteger i = 0; i < string.length; i++) {
NSString *substring = [string substringWithRange:NSMakeRange(i, 1)];
if ([substring canBeConvertedToEncoding:NSASCIIStringEncoding]) {
[result appendString:substring];
} else {
[result appendFormat:@"\\u%04x", [string characterAtIndex:i]];
}
}
return result;
}
+ (NSString *)fast_asciiEscapeWithString:(NSString *)string {
// if the string is already ascii, return immediately
if ([string canBeConvertedToEncoding:NSASCIIStringEncoding]) {
return [string copy];
}
NSMutableString *encoded = [NSMutableString stringWithCapacity:[string length]];
for (NSUInteger i = 0; i < [string length]; i++) {
unichar character = [string characterAtIndex:i];
// Anything that is raw ASCII (not extended) can be applied as a regular old character.
if (character < 128) {
[encoded appendFormat:@"%c", character];
} else {
// Everything else needs to be encoded, including the extended ascii set.
[encoded appendFormat:@"\\u%04x", character];
}
}
return [encoded copy];
}
+ (DBRequestError *)dBRequestErrorWithErrorData:(NSData *)errorData
clientError:(NSError *)clientError
statusCode:(int)statusCode
httpHeaders:(NSDictionary *)httpHeaders {
DBRequestError *dbxError;
if (clientError && errorData == nil) {
return [[DBRequestError alloc] initAsClientError:clientError];
}
if (statusCode == 200) {
return nil;
}
NSDictionary *deserializedData = [self deserializeHttpData:errorData];
NSString *requestId = httpHeaders[@"X-Dropbox-Request-Id"];
NSString *errorContent;
if (deserializedData) {
if (deserializedData[@"error_summary"]) {
errorContent = deserializedData[@"error_summary"];
} else if (deserializedData[@"error"]) {
errorContent = deserializedData[@"error"];
} else {
errorContent = errorData ? [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding] : nil;
}
} else {
errorContent = errorData ? [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding] : nil;
}
DBLocalizedUserMessage *userMessage = nil;
NSDictionary *userMessageDict = deserializedData[@"user_message"];
if ([userMessageDict isKindOfClass:[NSDictionary class]]) {
NSString *text = userMessageDict[@"text"];
NSString *locale = userMessageDict[@"locale"];
if ([text isKindOfClass:[NSString class]] && [locale isKindOfClass:[NSString class]]) {
userMessage = [[DBLocalizedUserMessage alloc] initWithText:text locale:locale];
}
}
if (statusCode >= 500 && statusCode < 600) {
dbxError = [[DBRequestError alloc] initAsInternalServerError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage];
} else if (statusCode == 400) {
dbxError = [[DBRequestError alloc] initAsBadInputError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage];
} else if (statusCode == 401) {
DBAUTHAuthError *authError = [DBAUTHAuthErrorSerializer deserialize:deserializedData[@"error"]];
dbxError = [[DBRequestError alloc] initAsAuthError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage
structuredAuthError:authError];
} else if (statusCode == 403) {
DBAUTHAccessError *accessError = [DBAUTHAccessErrorSerializer deserialize:deserializedData[@"error"]];
dbxError = [[DBRequestError alloc] initAsAccessError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage
structuredAccessError:accessError];
} else if (statusCode == 422) {
DBCOMMONPathRootError *pathRootError = [DBCOMMONPathRootErrorSerializer deserialize:deserializedData[@"error"]];
dbxError = [[DBRequestError alloc] initAsPathRootError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage
structuredPathRootError:pathRootError];
} else if (statusCode == 429) {
DBAUTHRateLimitError *rateLimitError = [DBAUTHRateLimitErrorSerializer deserialize:deserializedData[@"error"]];
NSString *retryAfter = httpHeaders[@"Retry-After"];
double retryAfterSeconds = retryAfter.doubleValue;
dbxError = [[DBRequestError alloc] initAsRateLimitError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage
structuredRateLimitError:rateLimitError
backoff:@(retryAfterSeconds)];
} else if ([[self class] statusCodeIsRouteError:statusCode]) {
dbxError = [[DBRequestError alloc] initAsHttpError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage];
} else {
dbxError = [[DBRequestError alloc] initAsHttpError:requestId
statusCode:@(statusCode)
errorContent:errorContent
userMessage:userMessage];
}
return dbxError;
}
+ (id)routeErrorWithRoute:(DBRoute *)route data:(NSData *)data statusCode:(int)statusCode {
if (!data) {
return nil;
}
id routeError = nil;
NSDictionary *deserializedData = [self deserializeHttpData:data];
if ([[self class] statusCodeIsRouteError:statusCode]) {
routeError = [route.errorType deserialize:deserializedData[@"error"]];
}
return routeError;
}
+ (NSDictionary *)deserializeHttpData:(NSData *)data {
if (!data) {
return nil;
}
NSError *error;
return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
+ (id)routeResultWithRoute:(DBRoute *)route data:(NSData *)data serializationError:(NSError **)serializationError {
if (!data) {
return nil;
}
if (!route.resultType) {
return nil;
}
id jsonData =
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:serializationError];
if (*serializationError) {
return nil;
}
if (route.resultType) {
if (route.dataStructDeserialBlock) {
return route.dataStructDeserialBlock(jsonData);
}
return [(Class)route.resultType deserialize:jsonData];
}
return nil;
}
+ (BOOL)statusCodeIsRouteError:(int)statusCode {
return statusCode == 409;
}
+ (nullable id)caseInsensitiveLookupWithKey:(nullable NSString *)lookupKey
headerFieldsDictionary:(nullable NSDictionary<id, id> *)headerFieldsDictionary {
NSString *lowercaseLookupKey = lookupKey.lowercaseString;
for (id key in headerFieldsDictionary) {
if ([key isKindOfClass:[NSString class]]) {
NSString *keyString = (NSString *)key;
if ([keyString.lowercaseString isEqualToString:lowercaseLookupKey]) {
return headerFieldsDictionary[key];
}
}
}
return nil;
}
@end