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 pathWordPressOrgXMLRPCApi.swift
More file actions
411 lines (357 loc) · 19.2 KB
/
WordPressOrgXMLRPCApi.swift
File metadata and controls
411 lines (357 loc) · 19.2 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
import Foundation
import wpxmlrpc
/// Class to connect to the XMLRPC API on self hosted sites.
open class WordPressOrgXMLRPCApi: NSObject {
public typealias SuccessResponseBlock = (AnyObject, HTTPURLResponse?) -> Void
public typealias FailureReponseBlock = (_ error: NSError, _ httpResponse: HTTPURLResponse?) -> Void
@available(*, deprecated, message: "This property is no longer being used because WordPressKit now sends all HTTP requests using `URLSession` directly.")
public static var useURLSession = true
private let endpoint: URL
private let userAgent: String?
private var backgroundUploads: Bool
private var backgroundSessionIdentifier: String
@objc public static let defaultBackgroundSessionIdentifier = "org.wordpress.wporgxmlrpcapi"
/// onChallenge's Callback Closure Signature. Host Apps should call this method, whenever a proper AuthChallengeDisposition has been
/// picked up (optionally with URLCredentials!).
///
public typealias AuthenticationHandler = (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
/// Closure to be executed whenever we receive a URLSession Authentication Challenge.
///
public static var onChallenge: ((URLAuthenticationChallenge, @escaping AuthenticationHandler) -> Void)?
/// Minimum WordPress.org Supported Version.
///
@objc public static let minimumSupportedVersion = "4.0"
private lazy var urlSession: URLSession = makeSession(configuration: .default)
private lazy var uploadURLSession: URLSession = {
backgroundUploads
? makeSession(configuration: .background(withIdentifier: self.backgroundSessionIdentifier))
: urlSession
}()
private func makeSession(configuration sessionConfiguration: URLSessionConfiguration) -> URLSession {
var additionalHeaders: [String: AnyObject] = ["Accept-Encoding": "gzip, deflate" as AnyObject]
if let userAgent = self.userAgent {
additionalHeaders["User-Agent"] = userAgent as AnyObject?
}
sessionConfiguration.httpAdditionalHeaders = additionalHeaders
// When using a background URLSession, we don't need to apply the authentication challenge related
// implementations in `SessionDelegate`.
if sessionConfiguration.identifier != nil {
return URLSession.backgroundSession(configuration: sessionConfiguration)
} else {
return URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
}
}
// swiftlint:disable weak_delegate
/// `URLSessionDelegate` for the URLSession instances in this class.
private let sessionDelegate = SessionDelegate()
// swiftlint:enable weak_delegate
/// Creates a new API object to connect to the WordPress XMLRPC API for the specified endpoint.
///
/// - Parameters:
/// - endpoint: the endpoint to connect to the xmlrpc api interface.
/// - userAgent: the user agent to use on the connection.
/// - backgroundUploads: If this value is true the API object will use a background session to execute uploads requests when using the `multipartPOST` function. The default value is false.
/// - backgroundSessionIdentifier: The session identifier to use for the background session. This must be unique in the system.
@objc public init(endpoint: URL, userAgent: String? = nil, backgroundUploads: Bool = false, backgroundSessionIdentifier: String) {
self.endpoint = endpoint
self.userAgent = userAgent
self.backgroundUploads = backgroundUploads
self.backgroundSessionIdentifier = backgroundSessionIdentifier
super.init()
}
/// Creates a new API object to connect to the WordPress XMLRPC API for the specified endpoint. The background uploads are disabled when using this initializer.
///
/// - Parameters:
/// - endpoint: the endpoint to connect to the xmlrpc api interface.
/// - userAgent: the user agent to use on the connection.
@objc convenience public init(endpoint: URL, userAgent: String? = nil) {
self.init(endpoint: endpoint, userAgent: userAgent, backgroundUploads: false, backgroundSessionIdentifier: WordPressOrgXMLRPCApi.defaultBackgroundSessionIdentifier + "." + endpoint.absoluteString)
}
deinit {
for session in [urlSession, uploadURLSession] {
session.finishTasksAndInvalidate()
}
}
/**
Cancels all ongoing and makes the session so the object will not fullfil any more request
*/
@objc open func invalidateAndCancelTasks() {
for session in [urlSession, uploadURLSession] {
session.invalidateAndCancel()
}
}
// MARK: - Network requests
/**
Check if username and password are valid credentials for the xmlrpc endpoint.
- parameter username: username to check
- parameter password: password to check
- parameter success: callback block to be invoked if credentials are valid, the object returned in the block is the options dictionary for the site.
- parameter failure: callback block to be invoked is credentials fail
*/
@objc open func checkCredentials(_ username: String,
password: String,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) {
let parameters: [AnyObject] = [0 as AnyObject, username as AnyObject, password as AnyObject]
callMethod("wp.getOptions", parameters: parameters, success: success, failure: failure)
}
/**
Executes a XMLRPC call for the method specificied with the arguments provided.
- parameter method: the xmlrpc method to be invoked
- parameter parameters: the parameters to be encoded on the request
- parameter success: callback to be called on successful request
- parameter failure: callback to be called on failed request
- returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method
returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback
will be invoked with the error specificing the serialization issues.
*/
@objc @discardableResult open func callMethod(_ method: String,
parameters: [AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
let progress = Progress.discreteProgress(totalUnitCount: 100)
Task { @MainActor in
let result = await self.call(method: method, parameters: parameters, fulfilling: progress, streaming: false)
switch result {
case let .success(response):
success(response.body, response.response)
case let .failure(error):
failure(error.asNSError(), error.response)
}
}
return progress
}
/**
Executes a XMLRPC call for the method specificied with the arguments provided, by streaming the request from a file.
This allows to do requests that can use a lot of memory, like media uploads.
- parameter method: the xmlrpc method to be invoked
- parameter parameters: the parameters to be encoded on the request
- parameter success: callback to be called on successful request
- parameter failure: callback to be called on failed request
- returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method
returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback
will be invoked with the error specificing the serialization issues.
*/
@objc @discardableResult open func streamCallMethod(_ method: String,
parameters: [AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
let progress = Progress.discreteProgress(totalUnitCount: 100)
Task { @MainActor in
let result = await self.call(method: method, parameters: parameters, fulfilling: progress, streaming: true)
switch result {
case let .success(response):
success(response.body, response.response)
case let .failure(error):
failure(error.asNSError(), error.response)
}
}
return progress
}
/// Call an XMLRPC method.
///
/// ## Error handling
///
/// Unlike the closure-based APIs, this method returns a concrete error type. You should consider handling the errors
/// as they are, instead of casting them to `NSError` instance. But in case you do need to cast them to `NSError`,
/// considering using the `asNSError` function if you need backward compatibility with existing code.
///
/// - Parameters:
/// - streaming: set to `true` if there are large data (i.e. uploading files) in given `parameters`. `false` by default.
/// - Returns: A `Result` type that contains the XMLRPC success or failure result.
func call(method: String, parameters: [AnyObject]?, fulfilling progress: Progress? = nil, streaming: Bool = false) async -> WordPressAPIResult<HTTPAPIResponse<AnyObject>, WordPressOrgXMLRPCApiFault> {
let session = streaming ? uploadURLSession : urlSession
let builder = HTTPRequestBuilder(url: endpoint)
.method(.post)
.body(xmlrpc: method, parameters: parameters)
return await session
.perform(
request: builder,
// All HTTP responses are treated as successful result. Error handling will be done in `decodeXMLRPCResult`.
acceptableStatusCodes: [1...999],
fulfilling: progress,
errorType: WordPressOrgXMLRPCApiFault.self
)
.decodeXMLRPCResult()
}
@objc public static let WordPressOrgXMLRPCApiErrorKeyData: NSError.UserInfoKey = "WordPressOrgXMLRPCApiErrorKeyData"
@objc public static let WordPressOrgXMLRPCApiErrorKeyDataString: NSError.UserInfoKey = "WordPressOrgXMLRPCApiErrorKeyDataString"
@objc public static let WordPressOrgXMLRPCApiErrorKeyStatusCode: NSError.UserInfoKey = "WordPressOrgXMLRPCApiErrorKeyStatusCode"
fileprivate static func convertError(_ error: NSError, data: Data?, statusCode: Int? = nil) -> NSError {
let responseCode = statusCode == 403 ? 403 : error.code
if let data = data {
var userInfo: [String: Any] = error.userInfo
userInfo[Self.WordPressOrgXMLRPCApiErrorKeyData as String] = data
userInfo[Self.WordPressOrgXMLRPCApiErrorKeyDataString as String] = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
userInfo[Self.WordPressOrgXMLRPCApiErrorKeyStatusCode as String] = statusCode
userInfo[NSLocalizedFailureErrorKey] = error.localizedDescription
if let statusCode = statusCode, (400..<600).contains(statusCode) {
let formatString = NSLocalizedString("An HTTP error code %i was returned.", comment: "A failure reason for when an error HTTP status code was returned from the site, with the specific error code.")
userInfo[NSLocalizedFailureReasonErrorKey] = String(format: formatString, statusCode)
} else {
userInfo[NSLocalizedFailureReasonErrorKey] = error.localizedFailureReason
}
return NSError(domain: error.domain, code: responseCode, userInfo: userInfo)
}
return error
}
}
private class SessionDelegate: NSObject, URLSessionDelegate {
@objc func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
switch challenge.protectionSpace.authenticationMethod {
case NSURLAuthenticationMethodServerTrust:
if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 {
completionHandler(.useCredential, credential)
return
}
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.performDefaultHandling, nil)
return
}
_ = SecTrustEvaluateWithError(serverTrust, nil)
var result = SecTrustResultType.invalid
let certificateStatus = SecTrustGetTrustResult(serverTrust, &result)
guard let hostAppHandler = WordPressOrgXMLRPCApi.onChallenge, certificateStatus == 0, result == .recoverableTrustFailure else {
completionHandler(.performDefaultHandling, nil)
return
}
DispatchQueue.main.async {
hostAppHandler(challenge, completionHandler)
}
default:
completionHandler(.performDefaultHandling, nil)
}
}
@objc func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
switch challenge.protectionSpace.authenticationMethod {
case NSURLAuthenticationMethodHTTPBasic:
if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 {
completionHandler(.useCredential, credential)
return
}
guard let hostAppHandler = WordPressOrgXMLRPCApi.onChallenge else {
completionHandler(.performDefaultHandling, nil)
return
}
DispatchQueue.main.async {
hostAppHandler(challenge, completionHandler)
}
default:
completionHandler(.performDefaultHandling, nil)
}
}
}
public struct WordPressOrgXMLRPCApiFault: LocalizedError, HTTPURLResponseProviding {
public var response: HTTPAPIResponse<Data>
public let code: Int?
public let message: String?
public init(response: HTTPAPIResponse<Data>, code: Int?, message: String?) {
self.response = response
self.code = code
self.message = message
}
public var errorDescription: String? {
message
}
public var httpResponse: HTTPURLResponse? {
response.response
}
}
private extension WordPressAPIResult<HTTPAPIResponse<Data>, WordPressOrgXMLRPCApiFault> {
func decodeXMLRPCResult() -> WordPressAPIResult<HTTPAPIResponse<AnyObject>, WordPressOrgXMLRPCApiFault> {
// This is a re-implementation of `WordPressOrgXMLRPCApi.handleResponseWithData` function:
// https://github.com/wordpress-mobile/WordPressKit-iOS/blob/11.0.0/WordPressKit/WordPressOrgXMLRPCApi.swift#L265
flatMap { response in
guard let contentType = response.response.allHeaderFields["Content-Type"] as? String else {
return .failure(
.unparsableResponse(
response: response.response,
body: response.body,
underlyingError: WordPressOrgXMLRPCApiError(code: .unknown)
)
)
}
if (400..<600).contains(response.response.statusCode) {
if let decoder = WPXMLRPCDecoder(data: response.body), decoder.isFault() {
// when XML-RPC is disabled for authenticated calls (e.g. xmlrpc_enabled is false on WP.org),
// it will return a valid fault payload with a non-200
return .failure(.endpointError(.init(response: response, code: decoder.faultCode(), message: decoder.faultString())))
} else {
return .failure(.unacceptableStatusCode(response: response.response, body: response.body))
}
}
guard contentType.hasPrefix("application/xml") || contentType.hasPrefix("text/xml") else {
return .failure(
.unparsableResponse(
response: response.response,
body: response.body,
underlyingError: WordPressOrgXMLRPCApiError(code: .unknown)
)
)
}
guard let decoder = WPXMLRPCDecoder(data: response.body) else {
return .failure(.unparsableResponse(response: response.response, body: response.body))
}
guard !decoder.isFault() else {
return .failure(.endpointError(.init(response: response, code: decoder.faultCode(), message: decoder.faultString())))
}
if let decoderError = decoder.error() {
return .failure(.unparsableResponse(response: response.response, body: response.body, underlyingError: decoderError))
}
guard let responseXML = decoder.object() else {
return .failure(.unparsableResponse(response: response.response, body: response.body))
}
return .success(HTTPAPIResponse(response: response.response, body: responseXML as AnyObject))
}
}
}
private extension WordPressAPIError where EndpointError == WordPressOrgXMLRPCApiFault {
/// Convert to NSError for backwards compatiblity.
///
/// Some Objective-C code in the WordPress app checks domain of the errors returned by `WordPressOrgXMLRPCApi`,
/// which can be `WordPressOrgXMLRPCApiError` or `WPXMLRPCFaultErrorDomain`.
///
/// Swift code should avoid dealing with NSError instances. Instead, they should use the strongly typed
/// `WordPressAPIError<WordPressOrgXMLRPCApiFault>`.
func asNSError() -> NSError {
let error: NSError
let data: Data?
let statusCode: Int?
switch self {
case let .requestEncodingFailure(underlyingError):
error = underlyingError as NSError
data = nil
statusCode = nil
case let .connection(urlError):
error = urlError as NSError
data = nil
statusCode = nil
case let .endpointError(fault):
error = NSError(domain: WPXMLRPCFaultErrorDomain, code: fault.code ?? 0, userInfo: [NSLocalizedDescriptionKey: fault.message].compactMapValues { $0 })
data = fault.response.body
statusCode = nil
case let .unacceptableStatusCode(response, body):
error = WordPressOrgXMLRPCApiError(code: .httpErrorStatusCode) as NSError
data = body
statusCode = response.statusCode
case let .unparsableResponse(_, body, underlyingError):
error = underlyingError as NSError
data = body
statusCode = nil
case let .unknown(underlyingError):
error = underlyingError as NSError
data = nil
statusCode = nil
}
return WordPressOrgXMLRPCApi.convertError(error, data: data, statusCode: statusCode)
}
}