This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathAccountServiceRemoteREST.m
More file actions
395 lines (349 loc) · 17 KB
/
AccountServiceRemoteREST.m
File metadata and controls
395 lines (349 loc) · 17 KB
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
#import "AccountServiceRemoteREST.h"
#import "WPKit-Swift.h"
@import NSObject_SafeExpectations;
@import WordPressShared;
static NSString * const UserDictionaryIDKey = @"ID";
static NSString * const UserDictionaryUsernameKey = @"username";
static NSString * const UserDictionaryEmailKey = @"email";
static NSString * const UserDictionaryDisplaynameKey = @"display_name";
static NSString * const UserDictionaryPrimaryBlogKey = @"primary_blog";
static NSString * const UserDictionaryAvatarURLKey = @"avatar_URL";
static NSString * const UserDictionaryDateKey = @"date";
static NSString * const UserDictionaryEmailVerifiedKey = @"email_verified";
MagicLinkParameter const MagicLinkParameterFlow = @"flow";
MagicLinkParameter const MagicLinkParameterSource = @"source";
MagicLinkSource const MagicLinkSourceDefault = @"default";
MagicLinkSource const MagicLinkSourceJetpackConnect = @"jetpack";
MagicLinkFlow const MagicLinkFlowLogin = @"login";
MagicLinkFlow const MagicLinkFlowSignup = @"signup";
@interface AccountServiceRemoteREST ()
@end
@implementation AccountServiceRemoteREST
- (void)getBlogs:(BOOL)filterJetpackSites
success:(void (^)(NSArray *))success
failure:(void (^)(NSError *))failure
{
if (filterJetpackSites) {
[self getBlogsWithParameters:@{@"filters": @"jetpack"} success:success failure:failure];
} else {
[self getBlogsWithSuccess:success failure:failure];
}
}
- (void)getBlogsWithSuccess:(void (^)(NSArray *))success
failure:(void (^)(NSError *))failure
{
[self getBlogsWithParameters:nil success:success failure:failure];
}
- (void)getVisibleBlogsWithSuccess:(void (^)(NSArray *))success
failure:(void (^)(NSError *))failure
{
[self getBlogsWithParameters:@{@"site_visibility": @"visible"} success:success failure:failure];
}
- (void)getAccountDetailsWithSuccess:(void (^)(RemoteUser *remoteUser))success
failure:(void (^)(NSError *error))failure
{
NSString *requestUrl = [self pathForEndpoint:@"me"
withVersion:WordPressComRESTAPIVersion_1_1];
[self.wordPressComRESTAPI get:requestUrl
parameters:nil
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
RemoteUser *remoteUser = [self remoteUserFromDictionary:responseObject];
success(remoteUser);
}
failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)updateBlogsVisibility:(NSDictionary *)blogs
success:(void (^)(void))success
failure:(void (^)(NSError *))failure
{
NSParameterAssert([blogs isKindOfClass:[NSDictionary class]]);
/*
The `POST me/sites` endpoint expects it's input in a format like:
@{
@"sites": @[
@"1234": {
@"visible": @YES
},
@"2345": {
@"visible": @NO
},
]
}
*/
NSMutableDictionary *sites = [NSMutableDictionary dictionaryWithCapacity:blogs.count];
[blogs enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSParameterAssert([key isKindOfClass:[NSNumber class]]);
NSParameterAssert([obj isKindOfClass:[NSNumber class]]);
/*
Blog IDs are pased as strings because JSON dictionaries can't take
non-string keys. If you try, you get a NSInvalidArgumentException
*/
NSString *blogID = [key stringValue];
sites[blogID] = @{ @"visible": obj };
}];
NSDictionary *parameters = @{
@"sites": sites
};
NSString *path = [self pathForEndpoint:@"me/sites"
withVersion:WordPressComRESTAPIVersion_1_1];
[self.wordPressComRESTAPI post:path
parameters:parameters
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (success) {
success();
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)isPasswordlessAccount:(NSString *)identifier success:(void (^)(BOOL passwordless))success failure:(void (^)(NSError *error))failure
{
NSString *encodedIdentifier = [identifier stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathRFC3986AllowedCharacterSet];
NSString *path = [self pathForEndpoint:[NSString stringWithFormat:@"users/%@/auth-options", encodedIdentifier]
withVersion:WordPressComRESTAPIVersion_1_1];
[self.wordPressComRESTAPI get:path
parameters:nil
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
NSDictionary *dict = (NSDictionary *)responseObject;
BOOL passwordless = [[dict numberForKey:@"passwordless"] boolValue];
success(passwordless);
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)isEmailAvailable:(NSString *)email success:(void (^)(BOOL available))success failure:(void (^)(NSError *error))failure
{
static NSString * const errorEmailAddressInvalid = @"invalid";
static NSString * const errorEmailAddressTaken = @"taken";
[self.wordPressComRESTAPI get:@"is-available/email"
parameters:@{ @"q": email, @"format": @"json"}
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if ([responseObject isKindOfClass:[NSDictionary class]]) {
NSString *error = [responseObject objectForKey:@"error"];
NSString *message = [responseObject objectForKey:@"message"];
if (error != NULL) {
if ([error isEqualToString:errorEmailAddressTaken]) {
// While this is informed as an error by the endpoint, for the purpose of this method
// it's a success case. We just need to inform the caller that the email is not
// available.
success(false);
} else if ([error isEqualToString:errorEmailAddressInvalid]) {
NSError* error = [[NSError alloc] initWithDomain:AccountServiceRemoteErrorDomain
code:AccountServiceRemoteEmailAddressInvalid
userInfo:@{
@"response": responseObject,
NSLocalizedDescriptionKey: message,
}];
if (failure) {
failure(error);
}
} else {
NSError* error = [[NSError alloc] initWithDomain:AccountServiceRemoteErrorDomain
code:AccountServiceRemoteEmailAddressCheckError
userInfo:@{
@"response": responseObject,
NSLocalizedDescriptionKey: message,
}];
if (failure) {
failure(error);
}
}
return;
}
if (success) {
BOOL available = [[responseObject numberForKey:@"available"] boolValue];
success(available);
}
} else {
NSError* error = [[NSError alloc] initWithDomain:AccountServiceRemoteErrorDomain
code:AccountServiceRemoteCantReadServerResponse
userInfo:@{@"response": responseObject}];
if (failure) {
failure(error);
}
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)isUsernameAvailable:(NSString *)username
success:(void (^)(BOOL available))success
failure:(void (^)(NSError *error))failure
{
[self.wordPressComRESTAPI get:@"is-available/username"
parameters:@{ @"q": username, @"format": @"json"}
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
// currently the endpoint will not respond with available=false
// but it could one day, and this should still work in that case
BOOL available = NO;
if ([responseObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)responseObject;
available = [[dict numberForKey:@"available"] boolValue];
}
success(available);
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
// If the username is not available (has already been used)
// the endpoint will reply with a 200 status code but describe
// an error. This causes a JSON error, which we can test for here.
if (httpResponse.statusCode == 200 && [error.description containsString:@"JSON"]) {
if (success) {
success(true);
}
} else if (failure) {
failure(error);
}
}];
}
- (void)requestWPComAuthLinkForEmail:(NSString *)email
clientID:(NSString *)clientID
clientSecret:(NSString *)clientSecret
source:(MagicLinkSource)source
wpcomScheme:(NSString *)scheme
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [self pathForEndpoint:@"auth/send-login-email"
withVersion:WordPressComRESTAPIVersion_1_3];
NSDictionary *extraParams = @{
MagicLinkParameterFlow: MagicLinkFlowLogin,
MagicLinkParameterSource: source
};
[self requestWPComMagicLinkForEmail:email
path:path
clientID:clientID
clientSecret:clientSecret
extraParams:extraParams
wpcomScheme:scheme
success:success
failure:failure];
}
- (void)requestWPComSignupLinkForEmail:(NSString *)email
clientID:(NSString *)clientID
clientSecret:(NSString *)clientSecret
wpcomScheme:(NSString *)scheme
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [self pathForEndpoint:@"auth/send-signup-email"
withVersion:WordPressComRESTAPIVersion_1_1];
NSDictionary *extraParams = @{
@"signup_flow_name": @"mobile-ios",
MagicLinkParameterFlow: MagicLinkFlowSignup
};
[self requestWPComMagicLinkForEmail:email
path:path
clientID:clientID
clientSecret:clientSecret
extraParams:extraParams
wpcomScheme:scheme
success:success
failure:failure];
}
- (void)requestWPComMagicLinkForEmail:(NSString *)email
path:(NSString *)path
clientID:(NSString *)clientID
clientSecret:(NSString *)clientSecret
extraParams:(nullable NSDictionary *)extraParams
wpcomScheme:(NSString *)scheme
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSAssert([email length] > 0, @"Needs an email address.");
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{
@"email": email,
@"client_id": clientID,
@"client_secret": clientSecret
}];
if (![@"wordpress" isEqualToString:scheme]) {
[params setObject:scheme forKey:@"scheme"];
}
if (extraParams != nil) {
[params addEntriesFromDictionary:extraParams];
}
[self.wordPressComRESTAPI post:path
parameters:[NSDictionary dictionaryWithDictionary:params]
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (success) {
success();
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)requestVerificationEmailWithSucccess:(void (^)(void))success
failure:(void (^)(NSError *))failure
{
NSString *path = [self pathForEndpoint:@"me/send-verification-email"
withVersion:WordPressComRESTAPIVersion_1_1];
[self.wordPressComRESTAPI post:path parameters:nil success:^(id _Nonnull responseObject, NSHTTPURLResponse * _Nullable httpResponse) {
if (success) {
success();
}
} failure:^(NSError * _Nonnull error, NSHTTPURLResponse * _Nullable response) {
if (failure) {
failure(error);
}
}];
}
#pragma mark - Private Methods
- (void)getBlogsWithParameters:(NSDictionary *)parameters
success:(void (^)(NSArray *))success
failure:(void (^)(NSError *))failure
{
NSString *requestUrl = [self pathForEndpoint:@"me/sites"
withVersion:WordPressComRESTAPIVersion_1_2];
[self.wordPressComRESTAPI get:requestUrl
parameters:parameters
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (success) {
success([self remoteBlogsFromJSONArray:responseObject[@"sites"]]);
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (RemoteUser *)remoteUserFromDictionary:(NSDictionary *)dictionary
{
RemoteUser *remoteUser = [RemoteUser new];
remoteUser.userID = [dictionary numberForKey:UserDictionaryIDKey];
remoteUser.username = [dictionary stringForKey:UserDictionaryUsernameKey];
remoteUser.email = [dictionary stringForKey:UserDictionaryEmailKey];
remoteUser.displayName = [dictionary stringForKey:UserDictionaryDisplaynameKey];
remoteUser.primaryBlogID = [dictionary numberForKey:UserDictionaryPrimaryBlogKey];
remoteUser.avatarURL = [dictionary stringForKey:UserDictionaryAvatarURLKey];
remoteUser.dateCreated = [NSDate dateWithISO8601String:[dictionary stringForKey:UserDictionaryDateKey]];
remoteUser.emailVerified = [[dictionary numberForKey:UserDictionaryEmailVerifiedKey] boolValue];
return remoteUser;
}
- (NSArray *)remoteBlogsFromJSONArray:(NSArray *)jsonBlogs
{
NSArray *blogs = jsonBlogs;
return [blogs wp_map:^id(NSDictionary *jsonBlog) {
return [[RemoteBlog alloc] initWithJSONDictionary:jsonBlog];
}];
return blogs;
}
@end