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 pathDomainsServiceRemote.swift
More file actions
321 lines (278 loc) · 12.4 KB
/
Copy pathDomainsServiceRemote.swift
File metadata and controls
321 lines (278 loc) · 12.4 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
import Foundation
/// Allows the construction of a request for domain suggestions.
///
public struct DomainSuggestionRequest {
public typealias DomainSuggestionType = DomainsServiceRemote.DomainSuggestionType
public let query: String
public let segmentID: Int64?
public let quantity: Int?
public let suggestionType: DomainSuggestionType?
public init(query: String, segmentID: Int64? = nil, quantity: Int? = nil, suggestionType: DomainSuggestionType? = nil) {
self.query = query
self.segmentID = segmentID
self.quantity = quantity
self.suggestionType = suggestionType
}
}
public struct DomainSuggestion: Codable {
public let domainName: String
public let productID: Int?
public let supportsPrivacy: Bool?
public let costString: String
public let cost: Double?
public let saleCost: Double?
public let isFree: Bool
public let currencyCode: String?
public var domainNameStrippingSubdomain: String {
return domainName.components(separatedBy: ".").first ?? domainName
}
public init(
domainName: String,
productID: Int?,
supportsPrivacy: Bool?,
costString: String,
cost: Double? = nil,
saleCost: Double? = nil,
isFree: Bool = false,
currencyCode: String? = nil
) {
self.domainName = domainName
self.productID = productID
self.supportsPrivacy = supportsPrivacy
self.costString = costString
self.cost = cost
self.saleCost = saleCost
self.isFree = isFree
self.currencyCode = currencyCode
}
public init(json: [String: AnyObject]) throws {
guard let domain = json["domain_name"] as? String else {
throw DomainsServiceRemote.ResponseError.decodingFailed
}
self.domainName = domain
self.productID = json["product_id"] as? Int ?? nil
self.supportsPrivacy = json["supports_privacy"] as? Bool ?? nil
self.costString = json["cost"] as? String ?? ""
self.cost = json["raw_price"] as? Double
self.saleCost = json["sale_cost"] as? Double
self.isFree = json["is_free"] as? Bool ?? false
self.currencyCode = json["currency_code"] as? String
}
}
public class DomainsServiceRemote: ServiceRemoteWordPressComREST {
public enum ResponseError: Error {
case decodingFailed
}
public enum DomainSuggestionType {
case noWordpressDotCom
case includeWordPressDotCom
case onlyWordPressDotCom
case wordPressDotComAndDotBlogSubdomains
/// Includes free dotcom sudomains and paid domains.
case freeAndPaid
case allowlistedTopLevelDomains([String])
fileprivate func parameters() -> [String: AnyObject] {
switch self {
case .noWordpressDotCom:
return ["include_wordpressdotcom": false as AnyObject]
case .includeWordPressDotCom:
return ["include_wordpressdotcom": true as AnyObject,
"only_wordpressdotcom": false as AnyObject]
case .onlyWordPressDotCom:
return ["only_wordpressdotcom": true as AnyObject]
case .wordPressDotComAndDotBlogSubdomains:
return ["include_dotblogsubdomain": true as AnyObject,
"vendor": "dot" as AnyObject,
"only_wordpressdotcom": true as AnyObject,
"include_wordpressdotcom": true as AnyObject]
case .freeAndPaid:
return ["include_dotblogsubdomain": false as AnyObject,
"include_wordpressdotcom": true as AnyObject,
"vendor": "mobile" as AnyObject]
case .allowlistedTopLevelDomains(let allowlistedTLDs):
return ["tlds": allowlistedTLDs.joined(separator: ",") as AnyObject]
}
}
}
public func getDomainsForSite(_ siteID: Int, success: @escaping ([RemoteDomain]) -> Void, failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/domains"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
wordPressComRESTAPI.get(path, parameters: nil,
success: {
response, _ in
do {
try success(mapDomainsResponse(response))
} catch {
WPKitLogError("Error parsing domains response (\(error)): \(response)")
failure(error)
}
}, failure: {
error, _ in
failure(error)
})
}
public func setPrimaryDomainForSite(siteID: Int, domain: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/domains/primary"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_1)
let parameters: [String: AnyObject] = ["domain": domain as AnyObject]
wordPressComRESTAPI.post(path, parameters: parameters,
success: { _, _ in
success()
}, failure: { error, _ in
failure(error)
})
}
@objc public func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "domains/supported-states/\(countryCode)"
let servicePath = path(forEndpoint: endPoint, withVersion: ._1_1)
wordPressComRESTAPI.get(
servicePath,
parameters: nil,
success: {
response, _ in
do {
guard let json = response as? [AnyObject] else {
throw ResponseError.decodingFailed
}
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let decodedResult = try JSONDecoder.apiDecoder.decode([WPState].self, from: data)
success(decodedResult)
} catch {
WPKitLogError("Error parsing State list for country code (\(error)): \(response)")
failure(error)
}
}, failure: { error, _ in
failure(error)
})
}
public func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "me/domain-contact-information"
let servicePath = path(forEndpoint: endPoint, withVersion: ._1_1)
wordPressComRESTAPI.get(
servicePath,
parameters: nil,
success: { (response, _) in
do {
let data = try JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let decodedResult = try JSONDecoder.apiDecoder.decode(DomainContactInformation.self, from: data)
success(decodedResult)
} catch {
WPKitLogError("Error parsing DomainContactInformation (\(error)): \(response)")
failure(error)
}
}) { (error, _) in
failure(error)
}
}
public func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "me/domain-contact-information/validate"
let servicePath = path(forEndpoint: endPoint, withVersion: ._1_1)
let parameters: [String: AnyObject] = ["contact_information": contactInformation as AnyObject,
"domain_names": domainNames as AnyObject]
wordPressComRESTAPI.post(
servicePath,
parameters: parameters,
success: { response, _ in
do {
let data = try JSONSerialization.data(withJSONObject: response, options: .prettyPrinted)
let decodedResult = try JSONDecoder.apiDecoder.decode(ValidateDomainContactInformationResponse.self, from: data)
success(decodedResult)
} catch {
WPKitLogError("Error parsing ValidateDomainContactInformationResponse (\(error)): \(response)")
failure(error)
}
}) { (error, _) in
failure(error)
}
}
public func getDomainSuggestions(request: DomainSuggestionRequest,
success: @escaping ([DomainSuggestion]) -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "domains/suggestions"
let servicePath = path(forEndpoint: endPoint, withVersion: ._1_1)
var parameters: [String: AnyObject] = [
"query": request.query as AnyObject
]
if let suggestionType = request.suggestionType {
parameters.merge(suggestionType.parameters(), uniquingKeysWith: { $1 })
}
if let segmentID = request.segmentID {
parameters["segment_id"] = segmentID as AnyObject
}
if let quantity = request.quantity {
parameters["quantity"] = quantity as AnyObject
}
wordPressComRESTAPI.get(servicePath,
parameters: parameters,
success: {
response, _ in
do {
let suggestions = try map(suggestions: response)
success(suggestions)
} catch {
WPKitLogError("Error parsing domains response (\(error)): \(response)")
failure(error)
}
}, failure: {
error, _ in
failure(error)
})
}
}
private func map(suggestions response: Any) throws -> [DomainSuggestion] {
guard let jsonSuggestions = response as? [[String: AnyObject]] else {
throw DomainsServiceRemote.ResponseError.decodingFailed
}
var suggestions: [DomainSuggestion] = []
for jsonSuggestion in jsonSuggestions {
do {
let suggestion = try DomainSuggestion(json: jsonSuggestion)
suggestions.append(suggestion)
}
}
return suggestions
}
private func mapDomainsResponse(_ response: Any) throws -> [RemoteDomain] {
guard let json = response as? [String: AnyObject],
let domainsJson = json["domains"] as? [[String: AnyObject]] else {
throw DomainsServiceRemote.ResponseError.decodingFailed
}
let domains = try domainsJson.map { domainJson -> RemoteDomain in
guard let domainName = domainJson["domain"] as? String,
let isPrimary = domainJson["primary_domain"] as? Bool else {
throw DomainsServiceRemote.ResponseError.decodingFailed
}
let autoRenewing = domainJson["auto_renewing"] as? Bool
let autoRenewalDate = domainJson["auto_renewal_date"] as? String
let expirySoon = domainJson["expiry_soon"] as? Bool
let expired = domainJson["expired"] as? Bool
let expiryDate = domainJson["expiry"] as? String
return RemoteDomain(domainName: domainName,
isPrimaryDomain: isPrimary,
domainType: domainTypeFromDomainJSON(domainJson),
autoRenewing: autoRenewing,
autoRenewalDate: autoRenewalDate,
expirySoon: expirySoon,
expired: expired,
expiryDate: expiryDate)
}
return domains
}
private func domainTypeFromDomainJSON(_ domainJson: [String: AnyObject]) -> DomainType {
if let type = domainJson["type"] as? String, type == "redirect" {
return .siteRedirect
}
if let wpComDomain = domainJson["wpcom_domain"] as? Bool, wpComDomain == true {
return .wpCom
}
if let hasRegistration = domainJson["has_registration"] as? Bool, hasRegistration == true {
return .registered
}
return .mapped
}