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 pathWordPressComRestApi.swift
More file actions
859 lines (714 loc) · 36.6 KB
/
WordPressComRestApi.swift
File metadata and controls
859 lines (714 loc) · 36.6 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
import Foundation
import WordPressShared
import Alamofire
// MARK: - WordPressComRestApiError
@available(*, deprecated, renamed: "WordPressComRestApiErrorCode", message: "`WordPressComRestApiError` is renamed to `WordPressRestApiErrorCode`, and no longer conforms to `Swift.Error`")
public typealias WordPressComRestApiError = WordPressComRestApiErrorCode
/**
Error constants for the WordPress.com REST API
- InvalidInput: The parameters sent to the server where invalid
- InvalidToken: The token provided was invalid
- AuthorizationRequired: Permission required to access resource
- UploadFailed: The upload failed
- RequestSerializationFailed: The serialization of the request failed
- Unknown: Unknow error happen
*/
@objc public enum WordPressComRestApiErrorCode: Int, CaseIterable {
case invalidInput
case invalidToken
case authorizationRequired
case uploadFailed
case requestSerializationFailed
case responseSerializationFailed
case tooManyRequests
case unknown
case preconditionFailure
case malformedURL
case invalidQuery
}
public struct WordPressComRestApiEndpointError: Error {
public var code: WordPressComRestApiErrorCode
var response: HTTPURLResponse?
public var apiErrorCode: String?
public var apiErrorMessage: String?
public var apiErrorData: AnyObject?
var additionalUserInfo: [String: Any]?
}
extension WordPressComRestApiEndpointError: LocalizedError {
public var errorDescription: String? {
apiErrorMessage
}
}
extension WordPressComRestApiEndpointError: HTTPURLResponseProviding {
var httpResponse: HTTPURLResponse? {
response
}
}
public enum ResponseType {
case json
case data
}
// MARK: - WordPressComRestApi
open class WordPressComRestApi: NSObject {
/// Use `URLSession` directly (instead of Alamofire) to send API requests.
public static var useURLSession = false
// MARK: Properties
@objc public static let ErrorKeyErrorCode = "WordPressComRestApiErrorCodeKey"
@objc public static let ErrorKeyErrorMessage = "WordPressComRestApiErrorMessageKey"
@objc public static let ErrorKeyErrorData = "WordPressComRestApiErrorDataKey"
@objc public static let ErrorKeyErrorDataEmail = "email"
@objc public static let LocaleKeyDefault = "locale" // locale is specified with this for v1 endpoints
@objc public static let LocaleKeyV2 = "_locale" // locale is prefixed with an underscore for v2
public typealias RequestEnqueuedBlock = (_ taskID: NSNumber) -> Void
public typealias SuccessResponseBlock = (_ responseObject: AnyObject, _ httpResponse: HTTPURLResponse?) -> Void
public typealias FailureReponseBlock = (_ error: NSError, _ httpResponse: HTTPURLResponse?) -> Void
public typealias APIResult<T> = WordPressAPIResult<HTTPAPIResponse<T>, WordPressComRestApiEndpointError>
@objc public static let apiBaseURL: URL = URL(string: "https://public-api.wordpress.com/")!
@objc public static let defaultBackgroundSessionIdentifier = "org.wordpress.wpcomrestapi"
private let oAuthToken: String?
private let userAgent: String?
@objc public let backgroundSessionIdentifier: String
@objc public let sharedContainerIdentifier: String?
private let backgroundUploads: Bool
private let localeKey: String
@objc public let baseURL: URL
private var invalidTokenHandler: (() -> Void)?
/**
Configure whether or not the user's preferred language locale should be appended. Defaults to true.
*/
@objc open var appendsPreferredLanguageLocale = true
private lazy var sessionManager: Alamofire.SessionManager = {
let sessionConfiguration = URLSessionConfiguration.default
let sessionManager = self.makeSessionManager(configuration: sessionConfiguration)
return sessionManager
}()
private lazy var uploadSessionManager: Alamofire.SessionManager = {
if self.backgroundUploads {
let sessionConfiguration = URLSessionConfiguration.background(withIdentifier: self.backgroundSessionIdentifier)
sessionConfiguration.sharedContainerIdentifier = self.sharedContainerIdentifier
let sessionManager = self.makeSessionManager(configuration: sessionConfiguration)
return sessionManager
}
return self.sessionManager
}()
private func makeSessionManager(configuration sessionConfiguration: URLSessionConfiguration) -> Alamofire.SessionManager {
var additionalHeaders: [String: AnyObject] = [:]
if let oAuthToken = self.oAuthToken {
additionalHeaders["Authorization"] = "Bearer \(oAuthToken)" as AnyObject?
}
if let userAgent = self.userAgent {
additionalHeaders["User-Agent"] = userAgent as AnyObject?
}
sessionConfiguration.httpAdditionalHeaders = additionalHeaders
let sessionManager = Alamofire.SessionManager(configuration: sessionConfiguration)
return sessionManager
}
// MARK: WordPressComRestApi
@objc convenience public init(oAuthToken: String? = nil, userAgent: String? = nil) {
self.init(oAuthToken: oAuthToken, userAgent: userAgent, backgroundUploads: false, backgroundSessionIdentifier: WordPressComRestApi.defaultBackgroundSessionIdentifier)
}
@objc convenience public init(oAuthToken: String? = nil, userAgent: String? = nil, baseURL: URL = WordPressComRestApi.apiBaseURL) {
self.init(oAuthToken: oAuthToken, userAgent: userAgent, backgroundUploads: false, backgroundSessionIdentifier: WordPressComRestApi.defaultBackgroundSessionIdentifier, baseURL: baseURL)
}
/// Creates a new API object to connect to the WordPress Rest API.
///
/// - Parameters:
/// - oAuthToken: the oAuth token to be used for authentication.
/// - userAgent: the user agent to identify the client doing 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.
/// - sharedContainerIdentifier: An optional string used when setting up background sessions for use in an app extension. Default is nil.
/// - localeKey: The key with which to specify locale in the parameters of a request.
/// - baseURL: The base url to use for API requests. Default is https://public-api.wordpress.com/
///
/// - Discussion: When backgroundUploads are activated any request done by the multipartPOST method will use background session. This background session is shared for all multipart
/// requests and the identifier used must be unique in the system, Apple recomends to use invert DNS base on your bundle ID. Keep in mind these requests will continue even
/// after the app is killed by the system and the system will retried them until they are done. If the background session is initiated from an app extension, you *must* provide a value
/// for the sharedContainerIdentifier.
///
@objc public init(oAuthToken: String? = nil, userAgent: String? = nil,
backgroundUploads: Bool = false,
backgroundSessionIdentifier: String = WordPressComRestApi.defaultBackgroundSessionIdentifier,
sharedContainerIdentifier: String? = nil,
localeKey: String = WordPressComRestApi.LocaleKeyDefault,
baseURL: URL = WordPressComRestApi.apiBaseURL) {
self.oAuthToken = oAuthToken
self.userAgent = userAgent
self.backgroundUploads = backgroundUploads
self.backgroundSessionIdentifier = backgroundSessionIdentifier
self.sharedContainerIdentifier = sharedContainerIdentifier
self.localeKey = localeKey
self.baseURL = baseURL
super.init()
}
deinit {
for session in [urlSession, uploadURLSession, sessionManager.session, uploadSessionManager.session] {
session.finishTasksAndInvalidate()
}
}
/// Cancels all outgoing tasks asynchronously without invalidating the session.
public func cancelTasks() {
for session in [urlSession, uploadURLSession, sessionManager.session, uploadSessionManager.session] {
session.getAllTasks { tasks in
tasks.forEach({ $0.cancel() })
}
}
}
/**
Cancels all ongoing taks and makes the session invalid so the object will not fullfil any more request
*/
@objc open func invalidateAndCancelTasks() {
for session in [urlSession, uploadURLSession, sessionManager.session, uploadSessionManager.session] {
session.invalidateAndCancel()
}
}
@objc func setInvalidTokenHandler(_ handler: @escaping () -> Void) {
invalidTokenHandler = handler
}
// MARK: Network requests
private func request(method: HTTPMethod,
urlString: String,
parameters: [String: AnyObject]?,
encoding: ParameterEncoding,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
guard let URLString = buildRequestURLFor(path: urlString, parameters: parameters) else {
failure(Constants.buildRequestError, nil)
return nil
}
let progress = Progress(totalUnitCount: 1)
let progressUpdater = { [weak progress] (taskProgress: Progress) in
progress?.totalUnitCount = taskProgress.totalUnitCount
progress?.completedUnitCount = taskProgress.completedUnitCount
}
let dataRequest = sessionManager.request(URLString, method: method, parameters: parameters, encoding: encoding)
.validate()
.responseJSON(completionHandler: { [weak progress] (response) in
switch response.result {
case .success(let responseObject):
progress?.completedUnitCount = progress?.totalUnitCount ?? 0
success(responseObject as AnyObject, response.response)
case .failure(let error):
let processedError = self.processError(response: response, originalError: error).flatMap { $0 as NSError }
failure(processedError ?? (error as NSError), response.response)
}
}).downloadProgress(closure: progressUpdater)
progress.cancellationHandler = { [weak dataRequest] in
dataRequest?.cancel()
}
return progress
}
/// A request that produces a response in the form of a byte array
private func dataRequest(method: HTTPMethod,
urlString: String,
parameters: [String: AnyObject]?,
encoding: ParameterEncoding,
completion: @escaping (Swift.Result<(Data, HTTPURLResponse?), Error>) -> Void) {
guard let URLString = buildRequestURLFor(path: urlString, parameters: parameters) else {
completion(.failure(Constants.buildRequestError))
return
}
sessionManager.request(URLString, method: method, parameters: parameters, encoding: encoding)
.validate()
.responseData(completionHandler: { (response) in
switch response.result {
case .success(let data):
completion(.success((data, response.response)))
case .failure(let error):
completion(.failure(error))
}
})
}
/**
Executes a GET request to the specified endpoint defined on URLString
- parameter URLString: the url string to be added to the baseURL
- 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 GET(_ URLString: String,
parameters: [String: AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
guard WordPressComRestApi.useURLSession else {
return request(method: .get, urlString: URLString, parameters: parameters, encoding: URLEncoding.default, success: success, failure: failure)
}
let progress = Progress.discreteProgress(totalUnitCount: 100)
Task { @MainActor in
let result = await self.perform(.get, URLString: URLString, parameters: parameters, fulfilling: progress)
switch result {
case let .success(response):
success(response.body, response.response)
case let .failure(error):
failure(error.asNSError(), error.response)
}
}
return progress
}
open func GETData(_ URLString: String,
parameters: [String: AnyObject]?,
completion: @escaping (Swift.Result<(Data, HTTPURLResponse?), Error>) -> Void) {
guard WordPressComRestApi.useURLSession else {
dataRequest(method: .get,
urlString: URLString,
parameters: parameters,
encoding: URLEncoding.default,
completion: completion)
return
}
Task { @MainActor in
let result: APIResult<Data> = await perform(.get, URLString: URLString, parameters: parameters)
completion(
result
.map { ($0.body, $0.response) }
.eraseToError()
)
}
}
/**
Executes a POST request to the specified endpoint defined on URLString
- parameter URLString: the url string to be added to the baseURL
- 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 upload and to cancel the upload. 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 POST(_ URLString: String,
parameters: [String: AnyObject]?,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
guard WordPressComRestApi.useURLSession else {
return request(method: .post, urlString: URLString, parameters: parameters, encoding: JSONEncoding.default, success: success, failure: failure)
}
let progress = Progress.discreteProgress(totalUnitCount: 100)
Task { @MainActor in
let result = await self.perform(.post, URLString: URLString, parameters: parameters, fulfilling: progress)
switch result {
case let .success(response):
success(response.body, response.response)
case let .failure(error):
failure(error.asNSError(), error.response)
}
}
return progress
}
/**
Executes a multipart POST using the current serializer, the parameters defined and the fileParts defined in the request
This request will be streamed from disk, so it's ideally to be used for large media post uploads.
- parameter URLString: the endpoint to connect
- parameter parameters: the parameters to use on the request
- parameter fileParts: the file parameters that are added to the multipart request
- parameter requestEnqueued: callback to be called when the fileparts are serialized and request is added to the background session. Defaults to nil
- 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 upload and to cancel the upload. 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 multipartPOST(_ URLString: String,
parameters: [String: AnyObject]?,
fileParts: [FilePart],
requestEnqueued: RequestEnqueuedBlock? = nil,
success: @escaping SuccessResponseBlock,
failure: @escaping FailureReponseBlock) -> Progress? {
guard !WordPressComRestApi.useURLSession else {
let progress = Progress.discreteProgress(totalUnitCount: 100)
Task { @MainActor in
let result = await upload(URLString: URLString, parameters: parameters, fileParts: fileParts, requestEnqueued: requestEnqueued, fulfilling: progress)
switch result {
case let .success(response):
success(response.body, response.response)
case let .failure(error):
failure(error.asNSError(), error.response)
}
}
return progress
}
guard let URLString = buildRequestURLFor(path: URLString, parameters: parameters) else {
failure(Constants.buildRequestError, nil)
return nil
}
let progress = Progress(totalUnitCount: 1)
let progressUpdater = {(taskProgress: Progress) in
// Sergio Estevao: Add an extra 1 unit to the progress to take in account the upload response and not only the uploading of data
progress.totalUnitCount = taskProgress.totalUnitCount + 1
progress.completedUnitCount = taskProgress.completedUnitCount
}
uploadSessionManager.upload(multipartFormData: { (multipartFormData) in
for filePart in fileParts {
multipartFormData.append(filePart.url, withName: filePart.parameterName, fileName: filePart.filename, mimeType: filePart.mimeType)
}
}, to: URLString, encodingCompletion: { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
if let taskIdentifier = upload.task?.taskIdentifier {
requestEnqueued?(NSNumber(value: taskIdentifier))
}
let dataRequest = upload.validate().responseJSON(completionHandler: { response in
switch response.result {
case .success(let responseObject):
progress.completedUnitCount = progress.totalUnitCount
success(responseObject as AnyObject, response.response)
case .failure(let error):
let processedError = self.processError(response: response, originalError: error).flatMap { $0 as NSError }
failure(processedError ?? (error as NSError), response.response)
}
}).uploadProgress(closure: progressUpdater)
progress.cancellationHandler = {
dataRequest.cancel()
}
case .failure(let encodingError):
failure(encodingError as NSError, nil)
}
})
return progress
}
@objc open func hasCredentials() -> Bool {
guard let authToken = oAuthToken else {
return false
}
return !(authToken.isEmpty)
}
override open var hash: Int {
return "\(String(describing: oAuthToken)),\(String(describing: userAgent))".hashValue
}
/// This method assembles a valid request URL for the specified path & parameters.
/// The framework relies on a field (`appendsPreferredLanguageLocale`) to influence whether or not locale should be
/// added to the path of requests. This approach did not consider request parameters.
///
/// This method now considers both the path and specified request parameters when performing the substitution.
/// It only accounts for the locale parameter. AlamoFire encodes other parameters via `SessionManager.request(_:method:parameters:encoding:headers:)`
///
/// - Parameters:
/// - path: the path for the request, which might include `locale`
/// - parameters: the request parameters, which could conceivably include `locale`
/// - Returns: a request URL if successful, `nil` otherwise.
///
func buildRequestURLFor(path: String, parameters: [String: AnyObject]? = [:]) -> String? {
guard let requestURLString = URL(string: path, relativeTo: baseURL)?.absoluteString,
let urlComponents = URLComponents(string: requestURLString) else {
return nil
}
let urlComponentsWithLocale = applyLocaleIfNeeded(urlComponents: urlComponents, parameters: parameters, localeKey: localeKey)
return urlComponentsWithLocale?.url?.absoluteString
}
private func requestBuilder(URLString: String) throws -> HTTPRequestBuilder {
guard let url = URL(string: URLString, relativeTo: baseURL) else {
throw URLError(.badURL)
}
var builder = HTTPRequestBuilder(url: url)
if appendsPreferredLanguageLocale {
let preferredLanguageIdentifier = WordPressComLanguageDatabase().deviceLanguage.slug
builder = builder.query(defaults: [URLQueryItem(name: localeKey, value: preferredLanguageIdentifier)])
}
return builder
}
private func applyLocaleIfNeeded(urlComponents: URLComponents, parameters: [String: AnyObject]? = [:], localeKey: String) -> URLComponents? {
guard appendsPreferredLanguageLocale else {
return urlComponents
}
var componentsWithLocale = urlComponents
var existingQueryItems = componentsWithLocale.queryItems ?? []
let existingLocaleQueryItems = existingQueryItems.filter { $0.name == localeKey }
let inputParameters = parameters ?? [:]
if inputParameters[localeKey] == nil, existingLocaleQueryItems.isEmpty {
let preferredLanguageIdentifier = WordPressComLanguageDatabase().deviceLanguage.slug
let localeQueryItem = URLQueryItem(name: localeKey, value: preferredLanguageIdentifier)
existingQueryItems.append(localeQueryItem)
}
componentsWithLocale.queryItems = existingQueryItems
return componentsWithLocale
}
@objc public func temporaryFileURL(withExtension fileExtension: String) -> URL {
assert(!fileExtension.isEmpty, "file Extension cannot be empty")
let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.\(fileExtension)"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
return fileURL
}
// MARK: - Async
private lazy var urlSession: URLSession = {
URLSession(configuration: sessionConfiguration(background: false))
}()
private lazy var uploadURLSession: URLSession = {
let configuration = sessionConfiguration(background: backgroundUploads)
configuration.sharedContainerIdentifier = self.sharedContainerIdentifier
return URLSession(configuration: configuration)
}()
private func sessionConfiguration(background: Bool) -> URLSessionConfiguration {
let configuration = background ? URLSessionConfiguration.background(withIdentifier: self.backgroundSessionIdentifier) : URLSessionConfiguration.default
var additionalHeaders: [String: AnyObject] = [:]
if let oAuthToken = self.oAuthToken {
additionalHeaders["Authorization"] = "Bearer \(oAuthToken)" as AnyObject
}
if let userAgent = self.userAgent {
additionalHeaders["User-Agent"] = userAgent as AnyObject
}
configuration.httpAdditionalHeaders = additionalHeaders
return configuration
}
func perform(
_ method: HTTPRequestBuilder.Method,
URLString: String,
parameters: [String: AnyObject]? = nil,
fulfilling progress: Progress? = nil
) async -> APIResult<AnyObject> {
await perform(method, URLString: URLString, parameters: parameters, fulfilling: progress) {
try (JSONSerialization.jsonObject(with: $0) as AnyObject)
}
}
func perform<T: Decodable>(
_ method: HTTPRequestBuilder.Method,
URLString: String,
parameters: [String: AnyObject]? = nil,
fulfilling progress: Progress? = nil,
jsonDecoder: JSONDecoder? = nil,
type: T.Type = T.self
) async -> APIResult<T> {
await perform(method, URLString: URLString, parameters: parameters, fulfilling: progress) {
let decoder = jsonDecoder ?? JSONDecoder()
return try decoder.decode(type, from: $0)
}
}
private func perform<T>(
_ method: HTTPRequestBuilder.Method,
URLString: String,
parameters: [String: AnyObject]?,
fulfilling progress: Progress?,
decoder: @escaping (Data) throws -> T
) async -> APIResult<T> {
var builder: HTTPRequestBuilder
do {
builder = try requestBuilder(URLString: URLString)
.method(method)
} catch {
return .failure(.requestEncodingFailure(underlyingError: error))
}
if let parameters {
if builder.method.allowsHTTPBody {
builder = builder.body(json: parameters as Any)
} else {
builder = builder.query(parameters)
}
}
return await perform(request: builder, fulfilling: progress, decoder: decoder)
}
private func perform<T>(
request: HTTPRequestBuilder,
fulfilling progress: Progress?,
decoder: @escaping (Data) throws -> T,
taskCreated: ((Int) -> Void)? = nil,
session: URLSession? = nil
) async -> APIResult<T> {
await (session ?? self.urlSession)
.perform(request: request, taskCreated: taskCreated, fulfilling: progress, errorType: WordPressComRestApiEndpointError.self)
.mapSuccess { response -> HTTPAPIResponse<T> in
let object = try decoder(response.body)
return HTTPAPIResponse(response: response.response, body: object)
}
.mapUnacceptableStatusCodeError { response, body in
if let error = self.processError(response: response, body: body, additionalUserInfo: nil) {
return error
}
throw URLError(.cannotParseResponse)
}
.mapError { error -> WordPressAPIError<WordPressComRestApiEndpointError> in
switch error {
case .requestEncodingFailure:
return .endpointError(.init(code: .requestSerializationFailed))
case let .unparsableResponse(response, _, _):
return .endpointError(.init(code: .responseSerializationFailed, response: response))
default:
return error
}
}
}
public func upload(
URLString: String,
parameters: [String: AnyObject]?,
fileParts: [FilePart],
requestEnqueued: RequestEnqueuedBlock? = nil,
fulfilling progress: Progress? = nil
) async -> APIResult<AnyObject> {
let builder: HTTPRequestBuilder
do {
let form = try fileParts.map {
try MultipartFormField(fileAtPath: $0.url.path, name: $0.parameterName, filename: $0.filename, mimeType: $0.mimeType)
}
builder = try requestBuilder(URLString: URLString)
.method(.post)
.body(form: form)
} catch {
return .failure(.requestEncodingFailure(underlyingError: error))
}
return await perform(
request: builder.query(parameters ?? [:]),
fulfilling: progress,
decoder: { try JSONSerialization.jsonObject(with: $0) as AnyObject },
taskCreated: { taskID in
DispatchQueue.main.async {
requestEnqueued?(NSNumber(value: taskID))
}
},
session: uploadURLSession
)
}
}
// MARK: - FilePart
/// FilePart represents the infomartion needed to encode a file on a multipart form request
public final class FilePart: NSObject {
@objc let parameterName: String
@objc let url: URL
@objc let filename: String
@objc let mimeType: String
@objc public init(parameterName: String, url: URL, filename: String, mimeType: String) {
self.parameterName = parameterName
self.url = url
self.filename = filename
self.mimeType = mimeType
}
}
// MARK: - Error processing
extension WordPressComRestApi {
/// A custom error processor to handle error responses when status codes are betwen 400 and 500
func processError(response: DataResponse<Any>, originalError: Error) -> WordPressComRestApiEndpointError? {
if let afError = originalError as? AFError, case AFError.responseSerializationFailed(_) = afError {
return .init(code: .responseSerializationFailed, response: response.response)
}
guard let httpResponse = response.response, let data = response.data else {
return nil
}
return processError(response: httpResponse, body: data, additionalUserInfo: (originalError as NSError).userInfo)
}
func processError(response httpResponse: HTTPURLResponse, body data: Data, additionalUserInfo: [String: Any]?) -> WordPressComRestApiEndpointError? {
// Not sure if it's intentional to include 500 status code, but the code seems to be there from the very beginning.
// https://github.com/wordpress-mobile/WordPressKit-iOS/blob/1.0.1/WordPressKit/WordPressComRestApi.swift#L374
guard (400...500).contains(httpResponse.statusCode) else {
return nil
}
guard let responseObject = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let responseDictionary = responseObject as? [String: AnyObject] else {
if let error = checkForThrottleErrorIn(response: httpResponse, data: data) {
return error
}
return .init(code: .unknown, response: httpResponse)
}
// FIXME: A hack to support free WPCom sites and Rewind. Should be obsolote as soon as the backend
// stops returning 412's for those sites.
if httpResponse.statusCode == 412, let code = responseDictionary["code"] as? String, code == "no_connected_jetpack" {
return .init(code: .preconditionFailure, response: httpResponse)
}
var errorDictionary: AnyObject? = responseDictionary as AnyObject?
if let errorArray = responseDictionary["errors"] as? [AnyObject], errorArray.count > 0 {
errorDictionary = errorArray.first
}
guard let errorEntry = errorDictionary as? [String: AnyObject],
let errorCode = errorEntry["error"] as? String,
let errorDescription = errorEntry["message"] as? String
else {
return .init(code: .unknown, response: httpResponse)
}
let errorsMap: [String: WordPressComRestApiErrorCode] = [
"invalid_input": .invalidInput,
"invalid_token": .invalidToken,
"authorization_required": .authorizationRequired,
"upload_error": .uploadFailed,
"unauthorized": .authorizationRequired,
"invalid_query": .invalidQuery
]
let mappedError = errorsMap[errorCode] ?? .unknown
if mappedError == .invalidToken {
// Call `invalidTokenHandler in the main thread since it's typically used by the apps to present an authentication UI.
DispatchQueue.main.async {
self.invalidTokenHandler?()
}
}
var originalErrorUserInfo = additionalUserInfo ?? [:]
originalErrorUserInfo.removeValue(forKey: NSLocalizedDescriptionKey)
return .init(
code: mappedError,
apiErrorCode: errorCode,
apiErrorMessage: errorDescription,
apiErrorData: errorEntry["data"],
additionalUserInfo: originalErrorUserInfo
)
}
func checkForThrottleErrorIn(response: HTTPURLResponse, data: Data) -> WordPressComRestApiEndpointError? {
// This endpoint is throttled, so check if we've sent too many requests and fill that error in as
// when too many requests occur the API just spits out an html page.
guard let responseString = String(data: data, encoding: .utf8),
responseString.contains("Limit reached") else {
return nil
}
let message = NSLocalizedString(
"wordpresskit.api.message.endpoint_throttled",
value: "Limit reached. You can try again in 1 minute. Trying again before that will only increase the time you have to wait before the ban is lifted. If you think this is in error, contact support.",
comment: "Message to show when a request for a WP.com API endpoint is throttled"
)
return .init(
code: .tooManyRequests,
apiErrorCode: "too_many_requests",
apiErrorMessage: message
)
}
}
// MARK: - Anonymous API support
extension WordPressComRestApi {
/// Returns an API object without an OAuth token defined & with the userAgent set for the WordPress App user agent
///
@objc class public func anonymousApi(userAgent: String) -> WordPressComRestApi {
return WordPressComRestApi(oAuthToken: nil, userAgent: userAgent)
}
/// Returns an API object without an OAuth token defined & with both the userAgent & localeKey set for the WordPress App user agent
///
@objc class public func anonymousApi(userAgent: String, localeKey: String) -> WordPressComRestApi {
return WordPressComRestApi(oAuthToken: nil, userAgent: userAgent, localeKey: localeKey)
}
}
// MARK: - Constants
private extension WordPressComRestApi {
enum Constants {
static let buildRequestError = NSError(domain: WordPressComRestApiEndpointError.errorDomain,
code: WordPressComRestApiErrorCode.requestSerializationFailed.rawValue,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Failed to serialize request to the REST API.",
comment: "Error message to show when wrong URL format is used to access the REST API")])
}
}
// MARK: - POST encoding
private extension Dictionary {
func percentEncoded() -> Data? {
return compactMap { key, value in
guard
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed),
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else {
return .none
}
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
private extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
extension WordPressAPIError<WordPressComRestApiEndpointError> {
func asNSError() -> NSError {
// When encoutering `URLError`, return `URLError` to avoid potentially breaking existing error handling code in the apps.
if case let .connection(urlError) = self {
return urlError as NSError
}
return self as NSError
}
}