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 pathPeopleServiceRemote.swift
More file actions
637 lines (564 loc) · 24.5 KB
/
Copy pathPeopleServiceRemote.swift
File metadata and controls
637 lines (564 loc) · 24.5 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
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import Foundation
/// Encapsulates all of the People Management WordPress.com Methods
///
public class PeopleServiceRemote: ServiceRemoteWordPressComREST {
/// Defines the PeopleServiceRemote possible errors.
///
public enum ResponseError: Error {
case decodingFailure
case invalidInputError
case userAlreadyHasRoleError
case unknownError
}
/// Retrieves the collection of users associated to a given Site.
///
/// - Parameters:
/// - siteID: The target site's ID.
/// - offset: The first N users to be skipped in the returned array.
/// - count: Number of objects to retrieve.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on error.
///
/// - Returns: An array of Users.
///
public func getUsers(_ siteID: Int,
offset: Int = 0,
count: Int,
success: @escaping ((_ users: [User], _ hasMore: Bool) -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/users"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters: [String: AnyObject] = [
"number": count as AnyObject,
"offset": offset as AnyObject,
"order_by": "display_name" as AnyObject,
"order": "ASC" as AnyObject,
"fields": "ID, nice_name, first_name, last_name, name, avatar_URL, roles, is_super_admin, linked_user_ID" as AnyObject
]
wordPressComRESTAPI.get(path, parameters: parameters, success: { (responseObject, _) in
guard let response = responseObject as? [String: AnyObject],
let users = response["users"] as? [[String: AnyObject]],
let people = try? self.peopleFromResponse(users, siteID: siteID, type: User.self) else {
failure(ResponseError.decodingFailure)
return
}
let hasMore = self.peopleFoundFromResponse(response) > (offset + people.count)
success(people, hasMore)
}, failure: { (error, _) in
failure(error)
})
}
/// Retrieves the collection of Followers associated to a site.
///
/// - Parameters:
/// - siteID: The target site's ID.
/// - count: The first N followers to be skipped in the returned array.
/// - size: Number of objects to retrieve.
/// - success: Closure to be executed on success
/// - failure: Closure to be executed on error.
///
/// - Returns: An array of Followers.
///
public func getFollowers(_ siteID: Int,
offset: Int = 0,
count: Int,
success: @escaping ((_ followers: [Follower], _ hasMore: Bool) -> Void),
failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/follows"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let pageNumber = (offset / count + 1)
let parameters: [String: AnyObject] = [
"number": count as AnyObject,
"page": pageNumber as AnyObject,
"fields": "ID, nice_name, first_name, last_name, name, avatar_URL" as AnyObject
]
wordPressComRESTAPI.get(path, parameters: parameters, success: { (responseObject, _) in
guard let response = responseObject as? [String: AnyObject],
let followers = response["users"] as? [[String: AnyObject]],
let people = try? self.peopleFromResponse(followers, siteID: siteID, type: Follower.self) else {
failure(ResponseError.decodingFailure)
return
}
let hasMore = self.peopleFoundFromResponse(response) > (offset + people.count)
success(people, hasMore)
}, failure: { (error, _) in
failure(error)
})
}
/// Retrieves the collection of email followers associated to a site.
///
/// - Parameters:
/// - siteID: The target site's ID.
/// - page: The page to fetch.
/// - max: The max number of followers to fetch.
/// - success: Closure to be executed on success with an array of EmailFollower and a bool indicating if more pages are available.
/// - failure: Closure to be executed on error.
///
public func getEmailFollowers(_ siteID: Int,
page: Int = 1,
max: Int = 20,
success: @escaping ((_ followers: [EmailFollower], _ hasMore: Bool) -> Void),
failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/stats/followers"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters: [String: AnyObject] = [
"page": page as AnyObject,
"max": max as AnyObject,
"type": "email" as AnyObject
]
wordPressComRESTAPI.get(path, parameters: parameters, success: { responseObject, _ in
guard let response = responseObject as? [String: AnyObject],
let subscribers = response["subscribers"] as? [[String: AnyObject]],
let totalPages = response["pages"] as? Int else {
failure(ResponseError.decodingFailure)
return
}
let followers = subscribers.compactMap { EmailFollower(siteID: siteID, statsFollower: StatsFollower(jsonDictionary: $0)) }
let hasMore = totalPages > page
success(followers, hasMore)
}, failure: { error, _ in
failure(error)
})
}
/// Retrieves the collection of Viewers associated to a site.
///
/// - Parameters:
/// - siteID: The target site's ID.
/// - count: The first N followers to be skipped in the returned array.
/// - size: Number of objects to retrieve.
/// - success: Closure to be executed on success
/// - failure: Closure to be executed on error.
///
/// - Returns: An array of Followers.
///
public func getViewers(_ siteID: Int,
offset: Int = 0,
count: Int,
success: @escaping ((_ followers: [Viewer], _ hasMore: Bool) -> Void),
failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/viewers"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let pageNumber = (offset / count + 1)
let parameters: [String: AnyObject] = [
"number": count as AnyObject,
"page": pageNumber as AnyObject
]
wordPressComRESTAPI.get(path, parameters: parameters, success: { responseObject, _ in
guard let response = responseObject as? [String: AnyObject],
let viewers = response["viewers"] as? [[String: AnyObject]],
let people = try? self.peopleFromResponse(viewers, siteID: siteID, type: Viewer.self) else {
failure(ResponseError.decodingFailure)
return
}
let hasMore = self.peopleFoundFromResponse(response) > (offset + people.count)
success(people, hasMore)
}, failure: { (error, _) in
failure(error)
})
}
/// Updates a specified User's Role
///
/// - Parameters:
/// - siteID: The ID of the site associated
/// - personID: The ID of the person to be updated
/// - newRole: The new Role that should be assigned to the user.
/// - success: Optional closure to be executed on success
/// - failure: Optional closure to be executed on error.
///
/// - Returns: A single User instance.
///
public func updateUserRole(_ siteID: Int,
userID: Int,
newRole: String,
success: ((RemotePerson) -> Void)? = nil,
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/users/\(userID)"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters = ["roles": [newRole]]
wordPressComRESTAPI.post(path,
parameters: parameters as [String: AnyObject]?,
success: { (responseObject, _) in
guard let response = responseObject as? [String: AnyObject],
let person = try? self.personFromResponse(response, siteID: siteID, type: User.self) else {
failure?(ResponseError.decodingFailure)
return
}
success?(person)
},
failure: { (error, _) in
failure?(error)
})
}
/// Deletes or removes a User from a site.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - userID: The ID of the user to be deleted.
/// - reassignID: When present, all of the posts and pages that belong to `userID` will be reassigned
/// to another person, with the specified ID.
/// - success: Optional closure to be executed on success
/// - failure: Optional closure to be executed on error.
///
public func deleteUser(_ siteID: Int,
userID: Int,
reassignID: Int? = nil,
success: (() -> Void)? = nil,
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/users/\(userID)/delete"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
var parameters = [String: AnyObject]()
if let reassignID = reassignID {
parameters["reassign"] = reassignID as AnyObject?
}
wordPressComRESTAPI.post(path, parameters: nil, success: { (_, _) in
success?()
}, failure: { (error, _) in
failure?(error)
})
}
/// Deletes or removes a Follower from a site.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - userID: The ID of the follower to be deleted.
/// - success: Optional closure to be executed on success
/// - failure: Optional closure to be executed on error.
///
@objc public func deleteFollower(_ siteID: Int,
userID: Int,
success: (() -> Void)? = nil,
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/followers/\(userID)/delete"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
wordPressComRESTAPI.post(path, parameters: nil, success: { (_, _) in
success?()
}, failure: { (error, _) in
failure?(error)
})
}
/// Deletes or removes an Email Follower from a site.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - userID: The ID of the email follower to be deleted.
/// - success: Optional closure to be executed on success
/// - failure: Optional closure to be executed on error.
///
@objc public func deleteEmailFollower(_ siteID: Int,
userID: Int,
success: (() -> Void)? = nil,
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/email-followers/\(userID)/delete"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
wordPressComRESTAPI.post(path, parameters: nil, success: { _, _ in
success?()
}, failure: { error, _ in
failure?(error)
})
}
/// Deletes or removes a User from a site.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - userID: The ID of the viewer to be deleted.
/// - success: Optional closure to be executed on success
/// - failure: Optional closure to be executed on error.
///
@objc public func deleteViewer(_ siteID: Int,
userID: Int,
success: (() -> Void)? = nil,
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/viewers/\(userID)/delete"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
wordPressComRESTAPI.post(path, parameters: nil, success: { (_, _) in
success?()
}, failure: { (error, _) in
failure?(error)
})
}
/// Retrieves all of the Available Roles, for a given SiteID.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - success: Optional closure to be executed on success.
/// - failure: Optional closure to be executed on error.
///
/// - Returns: An array of Person.Role entities.
///
public func getUserRoles(_ siteID: Int,
success: @escaping (([RemoteRole]) -> Void),
failure: ((Error) -> Void)? = nil) {
let endpoint = "sites/\(siteID)/roles"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
wordPressComRESTAPI.get(path, parameters: nil, success: { (responseObject, _) in
guard let response = responseObject as? [String: AnyObject],
let roles = try? self.rolesFromResponse(response) else {
failure?(ResponseError.decodingFailure)
return
}
success(roles)
}, failure: { (error, _) in
failure?(error)
})
}
/// Validates Invitation Recipients.
///
/// - Parameters:
/// - siteID: The ID of the site associated.
/// - usernameOrEmail: Recipient that should be validated.
/// - role: Role that would be granted to the recipient.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on failure. The remote error will be passed on.
///
@objc public func validateInvitation(_ siteID: Int,
usernameOrEmail: String,
role: String,
success: @escaping (() -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/invites/validate"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters = [
"invitees": usernameOrEmail,
"role": role
]
wordPressComRESTAPI.post(path, parameters: parameters as [String: AnyObject]?, success: { (responseObject, _) in
guard let responseDict = responseObject as? [String: AnyObject] else {
failure(ResponseError.decodingFailure)
return
}
if let error = self.errorFromInviteResponse(responseDict, usernameOrEmail: usernameOrEmail) {
failure(error)
return
}
success()
}, failure: { (error, _) in
failure(error)
})
}
/// Sends an Invitation to the specified recipient.
///
/// - Parameters:
/// - siteID: The ID of the associated site.
/// - usernameOrEmail: Recipient that should receive the invite.
/// - role: Role that would be granted to the recipient.
/// - message: String that should be sent to the recipient.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on failure. The remote error will be passed on.
///
@objc public func sendInvitation(_ siteID: Int,
usernameOrEmail: String,
role: String,
message: String,
success: @escaping (() -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/invites/new"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters = [
"invitees": usernameOrEmail,
"role": role,
"message": message
]
wordPressComRESTAPI.post(path, parameters: parameters as [String: AnyObject]?, success: { (responseObject, _) in
guard let responseDict = responseObject as? [String: AnyObject] else {
failure(ResponseError.decodingFailure)
return
}
if let error = self.errorFromInviteResponse(responseDict, usernameOrEmail: usernameOrEmail) {
failure(error)
return
}
success()
}, failure: { (error, _) in
failure(error)
})
}
/// Fetch any existing invite links.
///
/// - Parameters:
/// - siteID: The site ID for the invite links.
/// - success: A success block accepting an array of invite links as an argument.
/// - failure: Closure to be executed on failure. The remote error will be passed on.
///
public func fetchInvites(_ siteID: Int,
success: @escaping (([RemoteInviteLink]) -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/invites"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let params = [
"status": "all",
"number": 100
] as [String: AnyObject]
wordPressComRESTAPI.get(path, parameters: params, success: { (responseObject, _) in
guard let responseDict = responseObject as? [String: AnyObject] else {
failure(ResponseError.decodingFailure)
return
}
var results = [RemoteInviteLink]()
if let links = responseDict["links"] as? [[String: Any]] {
for link in links {
results.append(RemoteInviteLink(dict: link))
}
}
success(results)
}, failure: { (error, _) in
failure(error)
})
}
/// Create a new batch of invite links.
///
/// - Parameters:
/// - siteID: The site ID for the invite links.
/// - success: A success block accepting an array of invite links as an argument.
/// - failure: Closure to be executed on failure. The remote error will be passed on.
///
public func generateInviteLinks(_ siteID: Int,
success: @escaping (([RemoteInviteLink]) -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/invites/links/generate"
let path = self.path(forEndpoint: endpoint, withVersion: ._2_0)
wordPressComRESTAPI.post(path, parameters: nil, success: { (responseObject, _) in
guard let responseArray = responseObject as? [[String: AnyObject]] else {
failure(ResponseError.decodingFailure)
return
}
var results = [RemoteInviteLink]()
for dict in responseArray {
results.append(RemoteInviteLink(dict: dict))
}
success(results)
}, failure: { (error, _) in
failure(error)
})
}
/// Disable any existing invite links.
///
/// - Parameters:
/// - siteID: The site ID for the invite links to disable.
/// - success: A success block.
/// - failure: A failure block
///
public func disableInviteLinks(_ siteID: Int,
success: @escaping (([String]) -> Void),
failure: @escaping ((Error) -> Void)) {
let endpoint = "sites/\(siteID)/invites/links/disable"
let path = self.path(forEndpoint: endpoint, withVersion: ._2_0)
wordPressComRESTAPI.post(path, parameters: nil, success: { (responseObject, _) in
let deletedKeys = responseObject as? [String] ?? [String]()
success(deletedKeys)
}, failure: { (error, _) in
failure(error)
})
}
}
/// Encapsulates PeopleServiceRemote Private Methods
///
private extension PeopleServiceRemote {
/// Parses a dictionary containing an array of RemotePersons, and returns an array of RemotePersons instances.
///
/// - Parameters:
/// - response: Raw array of entity dictionaries
/// - siteID: the ID of the site associated
/// - type: The kind of Person we should parse.
///
/// - Returns: An array of *RemotePerson* instances.
///
func peopleFromResponse<T: RemotePerson>(_ rawPeople: [[String: AnyObject]],
siteID: Int,
type: T.Type) throws -> [T] {
let people = try rawPeople.compactMap { (user) -> T? in
return try personFromResponse(user, siteID: siteID, type: type)
}
return people
}
/// Parses a dictionary representing a RemotePerson, and returns an instance.
///
/// - Parameters:
/// - response: Raw backend dictionary
/// - siteID: the ID of the site associated
/// - type: The kind of Person we should parse.
///
/// - Returns: A single *Person* instance.
///
func personFromResponse<T: RemotePerson>(_ user: [String: AnyObject],
siteID: Int,
type: T.Type) throws -> T {
guard let ID = user["ID"] as? Int else {
throw ResponseError.decodingFailure
}
guard let username = user["nice_name"] as? String else {
throw ResponseError.decodingFailure
}
guard let displayName = user["name"] as? String else {
throw ResponseError.decodingFailure
}
let firstName = user["first_name"] as? String
let lastName = user["last_name"] as? String
let avatarURL = (user["avatar_URL"] as? NSString)
.flatMap { URL(string: $0.wpkit_stringByUrlEncoding())}
let linkedUserID = user["linked_user_ID"] as? Int ?? ID
let isSuperAdmin = user["is_super_admin"] as? Bool ?? false
let roles = user["roles"] as? [String]
let role = roles?.first ?? ""
return T(ID: ID,
username: username,
firstName: firstName,
lastName: lastName,
displayName: displayName,
role: role,
siteID: siteID,
linkedUserID: linkedUserID,
avatarURL: avatarURL,
isSuperAdmin: isSuperAdmin)
}
/// Returns the count of persons that can be retrieved from the backend.
///
/// - Parameters response: Raw backend dictionary
///
func peopleFoundFromResponse(_ response: [String: AnyObject]) -> Int {
return response["found"] as? Int ?? 0
}
/// Parses a collection of Roles, and returns instances of the RemotePerson.Role Enum.
///
/// - Parameter roles: Raw backend dictionary
///
/// - Returns: Collection of the remote roles.
///
func rolesFromResponse(_ roles: [String: AnyObject]) throws -> [RemoteRole] {
guard let rawRoles = roles["roles"] as? [[String: AnyObject]] else {
throw ResponseError.decodingFailure
}
let parsed = try rawRoles.map { (rawRole) -> RemoteRole in
guard let name = rawRole["name"] as? String,
let displayName = rawRole["display_name"] as? String else {
throw ResponseError.decodingFailure
}
return RemoteRole(slug: name, name: displayName)
}
return parsed
}
/// Parses a remote Invitation Error into a PeopleServiceRemote.Error.
///
/// - Parameters:
/// - response: Raw backend dictionary
/// - usernameOrEmail: Recipient that was used to either validate, or effectively send an invite.
///
/// - Returns: The remote error, if any.
///
func errorFromInviteResponse(_ response: [String: AnyObject], usernameOrEmail: String) -> Error? {
guard let errors = response["errors"] as? [String: AnyObject],
let theError = errors[usernameOrEmail] as? [String: String],
let code = theError["code"] else {
return nil
}
switch code {
case "invalid_input":
return ResponseError.invalidInputError
case "invalid_input_has_role":
return ResponseError.userAlreadyHasRoleError
case "invalid_input_following":
return ResponseError.userAlreadyHasRoleError
default:
return ResponseError.unknownError
}
}
}