/
SNPBaseUserTokenOperation.m
executable file
·272 lines (225 loc) · 8.04 KB
/
SNPBaseUserTokenOperation.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
//
// SNPBaseUserTokenOperation.m
// Snapper
//
// Created by Paul Schifferer on 12/18/12.
// Copyright (c) 2012 Pilgrimage Software. All rights reserved.
//
#import "SNPBaseUserTokenOperation.h"
#import <Mantle/Mantle.h>
#import "NSString+URLEncoding.h"
#import "SNPAccountManager.h"
#import "SNPConstants.h"
@implementation SNPBaseUserTokenOperation
#pragma mark - Initializers
- (instancetype)initWithAccountId:(NSString*)accountId
finishBlock:(void (^)(SNPResponse*))finishBlock {
self = [super init];
if(self) {
self.accountId = accountId;
self.finishBlock = finishBlock;
}
return self;
}
- (instancetype)initWithEndpoint:(NSURL*)endpoint
method:(NSString*)method
headers:(NSDictionary*)headers
parameters:(NSDictionary*)parameters
body:(NSData*)body
bodyType:(NSString*)bodyType
accountId:(NSString*)accountId
progressBlock:(void (^)(NSUInteger bytesWritten, NSUInteger totalBytesWritten, NSUInteger totalBytes))progressBlock
finishBlock:(void (^)(SNPResponse* response))finishBlock {
self = [super init];
if(self) {
self.endpoint = endpoint;
self.method = method;
self.headers = headers;
self.parameters = parameters;
self.body = body;
self.bodyType = bodyType;
self.accountId = accountId;
self.progressBlock = progressBlock;
self.finishBlock = finishBlock;
}
return self;
}
#pragma mark - Main
- (void)main {
// Sanity checks.
NSAssert(self.method, @"No method set for API operation!");
NSAssert(self.endpoint, @"No endpoint set for API operation!");
_receivedData = [NSMutableData new];
NSString* accessToken = nil;
NSString* tokenType = nil;
if(_accountId) {
SNPAccount* account = [[SNPAccountManager sharedAccountManager] accountForId:_accountId];
// NSAssert(account, @"No account found for ID: %@", _accountId);
if(account) {
accessToken = account.accessToken;
tokenType = account.tokenType;
if(accessToken == nil) {
SNPMetadata* meta = [[SNPMetadata alloc] init];
meta.errorMessage = [NSString stringWithFormat:NSLocalizedString(@"No access token found for account: %@", nil), account.name];
meta.errorSlug = @"no_token";
SNPResponse* response = [[SNPResponse alloc] init];
response.metadata = meta;
self.finishBlock(response);
return;
}
}
}
// Query parameters
NSMutableString* queryParams = [NSMutableString new];
[self handleQueryParameters];
[self.parameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
if([queryParams length] > 0) {
[queryParams appendString:@"&"];
}
if([value isKindOfClass:[NSNumber class]]) {
[queryParams appendFormat:@"%@=%@", [key encodedURLParameterString], value];
}
else if([value isKindOfClass:[NSArray class]]) {
NSString* paramValue = [value componentsJoinedByString:@","];
[queryParams appendFormat:@"%@=%@", [key encodedURLParameterString], [paramValue encodedURLParameterString]];
}
else {
[queryParams appendFormat:@"%@=%@", [key encodedURLParameterString], [value encodedURLParameterString]];
}
}];
if([queryParams length] > 0) {
NSString* urlString = [NSString stringWithFormat:@"%@?%@", [self.endpoint absoluteString], queryParams];
self.endpoint = [NSURL URLWithString:urlString];
}
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:self.endpoint
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:self.timeout ?: 10];
// Provided headers
[self.headers enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
[request addValue:value
forHTTPHeaderField:key];
}];
// OAuth header
if(accessToken) {
NSString* tokenValue = [NSString stringWithFormat:@"%@ %@", tokenType, accessToken];
[request addValue:tokenValue
forHTTPHeaderField:@"Authorization"];
}
[request addValue:@"application/json"
forHTTPHeaderField:@"Accept"];
// Set request body.
NSString* localMethod = [self.method uppercaseString];
[request setHTTPMethod:localMethod];
if([localMethod isEqualToString:@"POST"] ||
[localMethod isEqualToString:@"PUT"] ||
[localMethod isEqualToString:@"DELETE"]) {
request.HTTPBody = self.body;
if(self.bodyType) {
[request addValue:self.bodyType
forHTTPHeaderField:@"Content-Type"];
}
}
_connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
while(!_done &&
!self.isCancelled) {
NSDate* futureDate = [NSDate dateWithTimeIntervalSinceNow:5];
[[NSRunLoop currentRunLoop] runUntilDate:futureDate];
}
}
- (void)handleQueryParameters {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
if(self.parameters) {
[parameters addEntriesFromDictionary:self.parameters];
}
// Pagination
if(_beforeId) {
parameters[@"before_id"] = [NSString stringWithFormat:@"%ld", (long)_beforeId];
}
if(_sinceId) {
parameters[@"since_id"] = [NSString stringWithFormat:@"%ld", (long)_sinceId];
}
if(_count) {
parameters[@"count"] = [NSString stringWithFormat:@"%ld", (long)_count];
}
// General
if(_includeMuted) {
parameters[@"include_muted"] = @"1";
}
if(_includeDeleted) {
parameters[@"include_deleted"] = @"1";
}
if(_includeDirectedPosts) {
parameters[@"include_directed_posts"] = @"1";
}
if(_includeMachine) {
parameters[@"include_machine"] = @"1";
}
if(_includeStarredBy) {
parameters[@"include_starred_by"] = @"1";
}
if(_includeReposters) {
parameters[@"include_reposters"] = @"1";
}
if(_includePostAnnotations) {
parameters[@"include_post_annotations"] = @"1";
}
if(_includeAnnotations) {
parameters[@"include_annotations"] = @"1";
}
if(_includeUserAnnotations) {
parameters[@"include_user_annotations"] = @"1";
}
// Channel/message
if(_channelTypes) {
parameters[@"channel_types"] = [_channelTypes componentsJoinedByString:@","];
}
if(_includeMarker) {
parameters[@"include_marker"] = @"1";
}
if(_includeRead) {
parameters[@"include_read"] = @"1";
}
if(_includeRecentMessage) {
parameters[@"include_recent_message"] = @"1";
}
if(_includeMessageAnnotations) {
parameters[@"include_message_annotations"] = @"1";
}
// File
if(_fileTypes) {
parameters[@"file_types"] = [_fileTypes componentsJoinedByString:@","];
}
if(_includeIncomplete) {
parameters[@"include_incomplete"] = @"1";
}
if(_includePrivate) {
parameters[@"include_private"] = @"1";
}
if(_includeFileAnnotations) {
parameters[@"include_file_annotations"] = @"1";
}
// User stream
if(_connectionId) {
parameters[@"connection_id"] = _connectionId;
}
// Stream facet parameters
if(_hasOembedPhoto) {
parameters[@"has_oembed_photo"] = @"1";
}
// Common
if(_includeAnnotations) {
parameters[@"include_annotations"] = @"1";
}
if(_includeUserAnnotations) {
parameters[@"include_user_annotations"] = @"1";
}
if(_includeHTML) {
parameters[@"include_html"] = @"1";
}
if([[parameters allKeys] count]) {
self.parameters = [parameters copy];
}
}
@end