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 pathSubscribersServiceRemote.swift
More file actions
286 lines (253 loc) · 11.3 KB
/
Copy pathSubscribersServiceRemote.swift
File metadata and controls
286 lines (253 loc) · 11.3 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
import Foundation
public class SubscribersServiceRemote: ServiceRemoteWordPressComREST {
// MARK: GET Subscribers (Paginated List)
public struct GetSubscribersParameters: Hashable {
public var sortField: SortField?
public var sortOrder: SortOrder?
public var subscriptionTypeFilter: FilterSubscriptionType?
public var paymentTypeFilter: FilterPaymentType?
@frozen public enum SortField: String, CaseIterable {
case dateSubscribed = "date_subscribed"
case email = "email"
case name = "name"
case plan = "plan"
case subscriptionStatus = "subscription_status"
}
@frozen public enum SortOrder: String, CaseIterable {
case ascending = "asc"
case descending = "dsc"
}
@frozen public enum FilterSubscriptionType: String, CaseIterable {
case email = "email_subscriber"
case reader = "reader_subscriber"
case unconfirmed = "unconfirmed_subscriber"
case blocked = "blocked_subscriber"
}
@frozen public enum FilterPaymentType: String, CaseIterable {
case free
case paid
}
public var filters: [String] {
[subscriptionTypeFilter?.rawValue, paymentTypeFilter?.rawValue].compactMap { $0 }
}
public init(sortField: SortField? = nil, sortOrder: SortOrder? = nil, subscriptionTypeFilter: FilterSubscriptionType? = nil, paymentTypeFilter: FilterPaymentType? = nil) {
self.sortField = sortField
self.sortOrder = sortOrder
self.subscriptionTypeFilter = subscriptionTypeFilter
self.paymentTypeFilter = paymentTypeFilter
}
}
public struct GetSubscribersResponse: Decodable {
public var total: Int
public var pages: Int
public var page: Int
public var subscribers: [Subscriber]
public struct Subscriber: Decodable, SubsciberBasicInfoResponse {
public let subscriberID: Int
public let dotComUserID: Int
public let displayName: String?
public let avatar: String?
public let emailAddress: String?
public let dateSubscribed: Date
public let isEmailSubscriptionEnabled: Bool
public let subscriptionStatus: String?
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
subscriberID = try container.decode(Int.self, forKey: "subscription_id")
dotComUserID = try container.decode(Int.self, forKey: "user_id")
displayName = try? container.decodeIfPresent(String.self, forKey: "display_name")
avatar = try? container.decodeIfPresent(String.self, forKey: "avatar")
emailAddress = try? container.decodeIfPresent(String.self, forKey: "email_address")
dateSubscribed = try container.decode(Date.self, forKey: "date_subscribed")
isEmailSubscriptionEnabled = try container.decode(Bool.self, forKey: "is_email_subscriber")
subscriptionStatus = try? container.decodeIfPresent(String.self, forKey: "subscription_status")
}
}
}
/// Gets the list of the site subscribers, including WordPress.com users and
/// email subscribers.
public func getSubscribers(
siteID: Int,
page: Int? = nil,
perPage: Int? = 25,
parameters: GetSubscribersParameters = .init(),
search: String? = nil
) async throws -> GetSubscribersResponse {
let url = self.path(forEndpoint: "sites/\(siteID)/subscribers", withVersion: ._2_0)
var query: [String: Any] = [:]
if let page {
query["page"] = page
}
if let perPage {
query["per_page"] = perPage
}
if let sortField = parameters.sortField {
query["sort"] = sortField.rawValue
}
if let sortOrder = parameters.sortOrder {
query["sort_order"] = sortOrder.rawValue
}
if !parameters.filters.isEmpty {
query["filters"] = parameters.filters
}
if let search, !search.isEmpty {
query["search"] = search
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.supportMultipleDateFormats
return try await wordPressComRestApi.perform(
.get,
URLString: url,
parameters: query,
jsonDecoder: decoder,
type: GetSubscribersResponse.self
).get().body
}
// MARK: GET Subscriber (Individual Details)
public protocol SubsciberBasicInfoResponse {
var dotComUserID: Int { get }
var subscriberID: Int { get }
var displayName: String? { get }
var emailAddress: String? { get }
var avatar: String? { get }
var dateSubscribed: Date { get }
}
public final class GetSubscriberDetailsResponse: Decodable, SubsciberBasicInfoResponse {
public let subscriberID: Int
public let dotComUserID: Int
public let displayName: String?
public let avatar: String?
public let emailAddress: String?
public let siteURL: String?
public let dateSubscribed: Date
public let isEmailSubscriptionEnabled: Bool
public let subscriptionStatus: String?
public let country: Country?
public let plans: [Plan]?
public struct Country: Decodable {
public var code: String?
public var name: String?
}
public struct Plan: Decodable {
public let isGift: Bool
public let giftId: Int?
public let paidSubscriptionId: String?
public let status: String
public let title: String
public let currency: String?
public let renewInterval: String?
public let inactiveRenewInterval: String?
public let renewalPrice: Decimal
public let startDate: Date
public let endDate: Date
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
isGift = try container.decode(Bool.self, forKey: "is_gift")
giftId = try container.decodeIfPresent(Int.self, forKey: "gift_id")
paidSubscriptionId = try container.decodeIfPresent(String.self, forKey: "paid_subscription_id")
status = try container.decode(String.self, forKey: "status")
title = try container.decode(String.self, forKey: "title")
currency = try container.decodeIfPresent(String.self, forKey: "currency")
renewInterval = try? container.decodeIfPresent(String.self, forKey: "renew_interval")
inactiveRenewInterval = try? container.decodeIfPresent(String.self, forKey: "inactive_renew_interval")
renewalPrice = try container.decode(Decimal.self, forKey: "renewal_price")
startDate = try container.decode(Date.self, forKey: "start_date")
endDate = try container.decode(Date.self, forKey: "end_date")
}
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
subscriberID = try container.decode(Int.self, forKey: "subscription_id")
dotComUserID = try container.decode(Int.self, forKey: "user_id")
displayName = try? container.decodeIfPresent(String.self, forKey: "display_name")
avatar = try? container.decodeIfPresent(String.self, forKey: "avatar")
emailAddress = try? container.decodeIfPresent(String.self, forKey: "email_address")
siteURL = try? container.decodeIfPresent(String.self, forKey: "url")
dateSubscribed = try container.decode(Date.self, forKey: "date_subscribed")
isEmailSubscriptionEnabled = try container.decode(Bool.self, forKey: "is_email_subscriber")
subscriptionStatus = try? container.decodeIfPresent(String.self, forKey: "subscription_status")
country = try? container.decodeIfPresent(Country.self, forKey: "country")
plans = try container.decodeIfPresent([Plan].self, forKey: "plans")
}
}
/// Gets stats for the given subscriber.
///
/// Example: https://public-api.wordpress.com/wpcom/v2/sites/239619264/subscribers/individual?subscription_id=907116368
public func getSubsciberDetails(
siteID: Int,
subscriberID: Int,
type: String = "email"
) async throws -> GetSubscriberDetailsResponse {
let url = self.path(forEndpoint: "sites/\(siteID)/subscribers/individual", withVersion: ._2_0)
let query: [String: Any] = [
"subscription_id": subscriberID,
"type": type
]
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.supportMultipleDateFormats
return try await wordPressComRestApi.perform(
.get,
URLString: url,
parameters: query,
jsonDecoder: decoder,
type: GetSubscriberDetailsResponse.self
).get().body
}
public struct GetSubscriberStatsResponse: Decodable {
public var emailsSent: Int
public var uniqueOpens: Int
public var uniqueClicks: Int
}
/// Gets stats for the given subscriber.
///
/// Example: https://public-api.wordpress.com/wpcom/v2/sites/239619264/individual-subscriber-stats?subscription_id=907116368
public func getSubsciberStats(
siteID: Int,
subscriberID: Int
) async throws -> GetSubscriberStatsResponse {
let url = self.path(forEndpoint: "sites/\(siteID)/individual-subscriber-stats", withVersion: ._2_0)
let query: [String: Any] = [
"subscription_id": subscriberID
]
return try await wordPressComRestApi.perform(
.get,
URLString: url,
parameters: query,
jsonDecoder: JSONDecoder.apiDecoder,
type: GetSubscriberStatsResponse.self
).get().body
}
// MARK: POST Import Subscribers
/// Example: URL: https://public-api.wordpress.com/wpcom/v2/sites/216878809/subscribers/import?_envelope=1
@discardableResult
public func importSubscribers(
siteID: Int,
emails: [String]
) async throws -> ImportSubscribersResponse {
let url = self.path(forEndpoint: "sites/\(siteID)/subscribers/import", withVersion: ._2_0)
let parameters: [String: Any] = [
"emails": emails,
"parse_only": false
]
return try await wordPressComRestApi.perform(
.post,
URLString: url,
parameters: parameters,
type: ImportSubscribersResponse.self
).get().body
}
public struct ImportSubscribersResponse: Decodable {
public let uploadID: Int
enum CodingKeys: String, CodingKey {
case uploadID = "upload_id"
}
}
}
extension SubscribersServiceRemote.SubsciberBasicInfoResponse {
public var avatarURL: URL? {
avatar.flatMap(URL.init)
}
public var isDotComUser: Bool {
dotComUserID > 0
}
}