-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWordPressAPI.swift
More file actions
387 lines (331 loc) · 11.5 KB
/
WordPressAPI.swift
File metadata and controls
387 lines (331 loc) · 11.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
import Foundation
import WordPressApiCache
@preconcurrency import WordPressAPIInternal
#if os(Linux)
import FoundationNetworking
#endif
#if canImport(Combine)
import Combine
#endif
public final class WordPressAPI: Sendable {
enum Errors: Error {
case unableToParseResponse
}
private let siteInfo: SiteInfo
private let urlSession: URLSession
let requestExecutor: SafeRequestExecutor
private let apiClientDelegate: WpApiClientDelegate
package let requestBuilder: UniffiWpApiClient
public convenience init(
urlSession: URLSession,
notifyingDelegate: URLSessionTaskDelegate? = nil,
siteInfo: SiteInfo,
authentication: WpAuthentication,
middlewarePipeline: MiddlewarePipeline = .default,
appNotifier: WpAppNotifier? = nil
) {
self.init(
siteInfo: siteInfo,
authenticationProvider: .staticWithAuth(auth: authentication),
executor: WpRequestExecutor(urlSession: urlSession, notifyingDelegate: notifyingDelegate),
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier
)
}
public convenience init(
urlSession: URLSession,
siteInfo: SiteInfo,
authenticationProvider: WpAuthenticationProvider,
middlewarePipeline: MiddlewarePipeline = .default,
appNotifier: WpAppNotifier? = nil
) {
self.init(
siteInfo: siteInfo,
authenticationProvider: authenticationProvider,
executor: WpRequestExecutor(urlSession: urlSession),
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier
)
}
public convenience init(
urlSession: URLSession,
notifyingDelegate: URLSessionTaskDelegate? = nil,
siteInfo: SiteInfo,
authenticationProvider: WpAuthenticationProvider,
middlewarePipeline: MiddlewarePipeline = .default,
appNotifier: WpAppNotifier? = nil
) {
self.init(
siteInfo: siteInfo,
authenticationProvider: authenticationProvider,
executor: WpRequestExecutor(urlSession: urlSession, notifyingDelegate: notifyingDelegate),
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier
)
}
public convenience init(
urlSession: URLSession,
notifyingDelegate: URLSessionTaskDelegate? = nil,
siteUrl: ParsedUrl,
apiRootUrl: ParsedUrl,
username: String,
password: String,
middlewarePipeline: MiddlewarePipeline = .default,
appNotifier: WpAppNotifier? = nil
) {
let siteInfo = SiteInfo.selfHosted(siteUrl: siteUrl, apiRoot: apiRootUrl)
let executor = WpRequestExecutor(urlSession: urlSession, notifyingDelegate: notifyingDelegate)
let provider = CookiesNonceAuthenticationProvider.withSiteUrl(
url: siteUrl.url(),
username: username,
password: password,
requestExecutor: executor
)
self.init(
siteInfo: siteInfo,
authenticationProvider: .dynamic(dynamicAuthenticationProvider: provider),
executor: executor,
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier
)
}
public convenience init(
urlSession: URLSession,
notifyingDelegate: URLSessionTaskDelegate? = nil,
details: AutoDiscoveryAttemptSuccess,
username: String,
password: String,
middlewarePipeline: MiddlewarePipeline = .default,
appNotifier: WpAppNotifier? = nil
) {
let siteInfo = SiteInfo.selfHosted(
siteUrl: details.parsedSiteUrl,
apiRoot: details.apiRootUrl
)
let executor = WpRequestExecutor(urlSession: urlSession, notifyingDelegate: notifyingDelegate)
let provider = CookiesNonceAuthenticationProvider(
username: username,
password: password,
details: details,
requestExecutor: executor
)
self.init(
siteInfo: siteInfo,
authenticationProvider: .dynamic(dynamicAuthenticationProvider: provider),
executor: executor,
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier
)
}
init(
urlSession: URLSession = .shared,
siteInfo: SiteInfo,
authenticationProvider: WpAuthenticationProvider,
executor: SafeRequestExecutor,
middlewarePipeline: MiddlewarePipeline,
appNotifier: WpAppNotifier?
) {
self.urlSession = urlSession
self.siteInfo = siteInfo
self.apiClientDelegate = WpApiClientDelegate(
authProvider: authenticationProvider,
requestExecutor: executor,
middlewarePipeline: middlewarePipeline,
appNotifier: appNotifier ?? EmptyAppNotifier()
)
self.requestBuilder = UniffiWpApiClient(
apiUrlResolver: siteInfo.apiUrlResolver(),
delegate: self.apiClientDelegate
)
self.requestExecutor = executor
}
public func createService(cache: WordPressApiCache) throws -> WpService {
try WpService(siteInfo: siteInfo, delegate: apiClientDelegate, cache: cache.cache)
}
public var users: UsersRequestExecutor {
self.requestBuilder.users()
}
public var plugins: PluginsRequestExecutor {
self.requestBuilder.plugins()
}
public var apiRoot: ApiRootRequestExecutor {
self.requestBuilder.apiRoot()
}
public var applicationPasswords: ApplicationPasswordsRequestExecutor {
self.requestBuilder.applicationPasswords()
}
public var siteHealthTests: WpSiteHealthTestsRequestExecutor {
self.requestBuilder.wpSiteHealthTests()
}
public var postTypes: PostTypesRequestExecutor {
self.requestBuilder.postTypes()
}
public var posts: PostsRequestExecutor {
self.requestBuilder.posts()
}
public var postStatuses: PostStatusesRequestExecutor {
self.requestBuilder.postStatuses()
}
public var revisions: RevisionsRequestExecutor {
self.requestBuilder.postRevisions()
}
public var comments: CommentsRequestExecutor {
self.requestBuilder.comments()
}
public var media: MediaRequestExecutor {
self.requestBuilder.media()
}
public var siteSettings: SiteSettingsRequestExecutor {
self.requestBuilder.siteSettings()
}
public var taxonomies: TaxonomiesRequestExecutor {
self.requestBuilder.taxonomies()
}
public var terms: TermsRequestExecutor {
self.requestBuilder.terms()
}
public var themes: ThemesRequestExecutor {
self.requestBuilder.themes()
}
public var blockEditor: WpBlockEditorRequestExecutor {
self.requestBuilder.wpBlockEditor()
}
public var navigations: NavigationRequestExecutor {
self.requestBuilder.navigations()
}
public var navMenus: NavMenusRequestExecutor {
self.requestBuilder.navMenus()
}
public var navMenuItems: NavMenuItemsRequestExecutor {
self.requestBuilder.navMenuItems()
}
public var navMenuAutosaves: NavMenuItemAutosavesRequestExecutor {
self.requestBuilder.navMenuItemAutosaves()
}
public var menuLocations: MenuLocationsRequestExecutor {
self.requestBuilder.menuLocations()
}
#if PROGRESS_REPORTING_ENABLED
/// Track the progress of the given HTTP API calls in the `apiCall` closure.
///
/// Note: pass the `RequestContext` parameter in `apiCall` to one and only one HTTP API call.
public func fulfill<R: Sendable>(
progress: Progress,
withApiCall apiCall: sending @escaping (RequestContext) async throws -> R
) async throws -> R {
precondition(progress.completedUnitCount == 0 && progress.totalUnitCount > 0)
precondition(progress.cancellationHandler == nil)
let context = RequestContext()
let uploadTask = Task {
try await withTaskCancellationHandler {
try await apiCall(context)
} onCancel: {
requestExecutor.cancel(context: context)
}
}
let progressObserver = Task {
for await task in requestExecutor.progresses(for: context).values {
// For one single request call, the Rust layer should send HTTP requests sequentially.
// For example, the retry mechanism in the Rust layer only send the retry call when the initial
// call fails.
//
// Since we can't know how many HTTP requests will be sent, the best we can do is make the `progress`
// starts from zero to complete for each HTTP request.
progress.completedUnitCount = 0
progress.addChild(task, withPendingUnitCount: progress.totalUnitCount)
}
}
progress.cancellationHandler = {
uploadTask.cancel()
progressObserver.cancel()
}
defer { progressObserver.cancel() }
return try await withTaskCancellationHandler {
try await uploadTask.value
} onCancel: {
progress.cancel()
}
}
public func uploadMedia(
params: MediaCreateParams,
fulfilling progress: Progress
) async throws -> MediaRequestCreateResponse {
try await fulfill(progress: progress) { [media] in
try await media.createCancellation(params: params, context: $0)
}
}
#endif
enum ParseError: Error {
case invalidUrl
case invalidHtml
}
}
public extension WpNetworkHeaderMap {
func toFlatMap() -> [String: String] {
self.toMap().mapValues { $0.joined(separator: ",") }
}
}
public extension WpNetworkRequest {
#if DEBUG
func debugPrint() {
print("\(method().rawValue) \(self.url())")
for (name, value) in self.headerMap().toMap() {
print("\(name): \(value)")
}
print("")
if let bodyString = self.bodyAsString() {
print(bodyString)
}
}
#endif
}
extension Result {
@inlinable public func tryMap<NewSuccess>(
_ transform: (Success) throws -> NewSuccess
) -> Result<NewSuccess, any Error> {
switch self {
case .success(let success):
do {
return .success(try transform(success))
} catch let err {
return .failure(err)
}
case .failure(let error): return .failure(error)
}
}
}
extension HTTPURLResponse {
var httpHeaders: [String: String] {
allHeaderFields.reduce(into: [String: String]()) {
guard
let key = $1.key as? String,
let value = $1.value as? String
else {
return
}
$0.updateValue(value, forKey: key)
}
}
}
// Note: Everything below this line should be moved into the Rust layer
public extension WpAuthentication {
init(username: String, password: String) {
self = .authorizationHeader(token: "\(username):\(password)".data(using: .utf8)!.base64EncodedString())
}
}
extension RequestMethod {
var rawValue: String {
switch self {
case .get: "GET"
case .post: "POST"
case .put: "PUT"
case .delete: "DELETE"
case .head: "HEAD"
}
}
}
public extension ParsedUrl {
static func from(url: URL) throws -> ParsedUrl {
try parse(input: url.absoluteString)
}
}