This repository has been archived by the owner on Dec 18, 2022. It is now read-only.
/
SKRequest.m
208 lines (163 loc) · 8.44 KB
/
SKRequest.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
//
// SKRequest.m
// SnapchatKit
//
// Created by Tanner Bennett on 5/18/15.
// Copyright (c) 2015 Tanner Bennett. All rights reserved.
//
#import "SKRequest.h"
#import "SnapchatKit-Constants.h"
#import "NSString+SnapchatKit.h"
#import "NSDictionary+SnapchatKit.h"
#import "NSData+SnapchatKit.h"
@implementation SKRequest
#pragma mark Request overrides
static NSDictionary *headerOverrides;
static NSDictionary *globalParamOverrides;
static NSMutableDictionary *scopeParamOverrides;
static NSMutableDictionary *scopeHeaderOverrides;
static NSDictionary *endpointOverrides;
+ (void)overrideHeaderValuesGlobally:(NSDictionary *)headers {
NSParameterAssert([headers isKindOfClass:[NSDictionary class]] || !headers);
headerOverrides = headers;
}
+ (void)overrideHeaderValues:(NSDictionary *)headers forEndpoint:(NSString *)endpoint {
NSParameterAssert([headers isKindOfClass:[NSDictionary class]] || !headers); NSParameterAssert(endpoint);
if (!scopeHeaderOverrides)
scopeHeaderOverrides = [NSMutableDictionary dictionary];
scopeHeaderOverrides[endpoint] = headers;
}
+ (void)overrideValuesForKeys:(NSDictionary *)queries forEndpoint:(NSString *)endpoint {
NSParameterAssert([queries isKindOfClass:[NSDictionary class]] || !queries); NSParameterAssert(endpoint);
if (!scopeParamOverrides)
scopeParamOverrides = [NSMutableDictionary dictionary];
scopeParamOverrides[endpoint] = queries;
}
+ (void)overrideValuesForKeysGlobally:(NSDictionary *)queries {
NSParameterAssert([queries isKindOfClass:[NSDictionary class]] || !queries);
globalParamOverrides = queries;
}
+ (void)overrideEndpoints:(NSDictionary *)endpoints {
endpointOverrides = endpoints;
}
void SKRequestApplyOverrides(NSString **endpoint, NSDictionary **params) {
if (params != NULL) {
*params = [*params dictionaryByReplacingValuesForKeys:globalParamOverrides];
*params = [*params dictionaryByReplacingValuesForKeys:scopeParamOverrides[*endpoint]];
}
if (*endpoint) {
*endpoint = endpointOverrides[*endpoint] ?: *endpoint;
}
}
NSDictionary * SKRequestApplyHeaderOverrides(NSDictionary *httpHeaders, NSString *endpoint) {
if (!httpHeaders) return @{};
httpHeaders = [httpHeaders dictionaryByReplacingValuesForKeys:headerOverrides];
httpHeaders = [httpHeaders dictionaryByReplacingValuesForKeys:scopeHeaderOverrides[endpoint]];
return httpHeaders;
}
#pragma mark Convenience
+ (NSDictionary *)parseJSON:(NSData *)jsonData {
return [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
+ (NSError *)errorWithMessage:(NSString *)message code:(NSInteger)code {
return [NSError errorWithDomain:@"SnapchatKit" code:code userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(message, @""),
NSLocalizedFailureReasonErrorKey: NSLocalizedString(message, @"")}];
}
+ (NSError *)unknownError {
return [NSError errorWithDomain:@"Unknown" code:1 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Unknown error", @""),
NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Unknown error", @"")}];
}
#pragma mark POST / GET
+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback {
NSParameterAssert(endpoint); NSParameterAssert(callback);
SKRequest *request = [[SKRequest alloc] initWithPOSTEndpoint:endpoint query:json headers:httpHeaders];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:callback];
[dataTask resume];
}
+ (void)get:(NSString *)endpoint headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback {
NSParameterAssert(endpoint); NSParameterAssert(callback);
SKRequest *request = [[SKRequest alloc] initWithGETEndpoint:endpoint headers:httpHeaders];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:callback];
[dataTask resume];
}
+ (void)sendEvents:(NSDictionary *)eventData callback:(RequestBlock)callback {
NSParameterAssert(eventData); NSParameterAssert(callback);
SKRequest *request = [[SKRequest alloc] initWithURLString:SKConsts.eventsURL eventData:eventData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:callback];
[dataTask resume];
}
#pragma mark Initializers
- (id)initWithHeaderFields:(NSDictionary *)httpHeaders {
self = [super init];
if (self) {
// HTTP header fields
[self setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:SKHeaders.contentType];
[self setValue:SKConsts.userAgent forHTTPHeaderField:SKHeaders.userAgent];
[self setValue:SKHeaders.values.language forHTTPHeaderField:SKHeaders.acceptLanguage];
[self setValue:SKHeaders.values.locale forHTTPHeaderField:SKHeaders.acceptLocale];
if (httpHeaders)
[httpHeaders enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
[self setValue:value forHTTPHeaderField:key];
}];
}
return self;
}
- (id)initWithPOSTEndpoint:(NSString *)endpoint query:(NSDictionary *)params headers:(NSDictionary *)httpHeaders {
NSParameterAssert(params[@"timestamp"]);
// [[self class] overrideHeaderValuesGlobally:@{SKHeaders.userAgent: SKConsts.userAgent}];
httpHeaders = SKRequestApplyHeaderOverrides(httpHeaders, endpoint);
self = [self initWithHeaderFields:httpHeaders];
if (self) {
SKRequestApplyOverrides(&endpoint, ¶ms);
self.URL = [NSURL URLWithString:[SKConsts.baseURL stringByAppendingString:endpoint]];
self.HTTPMethod = @"POST";
NSMutableDictionary *json = [params mutableCopy];
// Set HTTPBody
// Only for uploading snaps here
if ([endpoint isEqualToString:SKEPSnaps.upload] ||
[endpoint isEqualToString:SKEPAccount.avatar.set] ||
[endpoint isEqualToString:SKEPStories.post]) {
[self setValue:@"multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY" forHTTPHeaderField:SKHeaders.contentType];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", SKConsts.boundary] dataUsingEncoding:NSUTF8StringEncoding]];
for (NSString *key in json.allKeys) {
if ([key isEqualToString:@"data"] || [key isEqualToString:@"thumbnail_data"]) {
[body appendData:[NSData boundaryWithKey:key forDataValue:json[key]]];
} else {
[body appendData:[NSData boundaryWithKey:key forStringValue:(NSString *)json[key]]];
}
}
// Replace last \r\n with --
[body replaceBytesInRange:NSMakeRange(body.length-2, 2) withBytes:[@"--" dataUsingEncoding:NSUTF8StringEncoding].bytes];
self.HTTPBody = body;
} else {
self.HTTPBody = [[NSString queryStringWithParams:json] dataUsingEncoding:NSUTF8StringEncoding];
}
}
// SKLog(@"\nEndpoint: %@\nParams:\n%@\n\nHeaders:\n%@", self.URL, params, httpHeaders);
return self;
}
- (id)initWithGETEndpoint:(NSString *)endpoint headers:(NSDictionary *)httpHeaders {
httpHeaders = SKRequestApplyHeaderOverrides(httpHeaders, endpoint);
self = [self initWithHeaderFields:httpHeaders];
if (self) {
SKRequestApplyOverrides(&endpoint, NULL);
self.URL = [NSURL URLWithString:[SKConsts.baseURL stringByAppendingPathComponent:endpoint]];
self.HTTPMethod = @"GET";
}
return self;
}
- (id)initWithURLString:(NSString *)url eventData:(NSDictionary *)eventData {
self = [self init];
if (self) {
self.URL = [NSURL URLWithString:url];
self.HTTPMethod = @"POST";
NSData *queryData = [[NSString queryStringWithParams:eventData] dataUsingEncoding:NSUTF8StringEncoding];
self.HTTPBody = queryData;
}
return self;
}
@end