|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// Service for fetching the editor settings and other parts of the enrvironment |
| 4 | +/// required to launch the editor. |
| 5 | +public final class EditorService { |
| 6 | + enum EditorServiceError: Error { |
| 7 | + case invalidResponseData |
| 8 | + } |
| 9 | + |
| 10 | + private let siteID: String |
| 11 | + private let baseURL: URL |
| 12 | + private let authHeader: String |
| 13 | + private let urlSession: URLSession |
| 14 | + |
| 15 | + private let storeURL: URL |
| 16 | + private var editorSettingsFileURL: URL { storeURL.appendingPathComponent("settings.json") } |
| 17 | + |
| 18 | + private var refreshTask: Task<Void, Error>? |
| 19 | + |
| 20 | + /// Creates a new EditorService instance |
| 21 | + /// - Parameters: |
| 22 | + /// - siteID: Unique identifier for the site (used for caching) |
| 23 | + /// - baseURL: Root URL for the site API |
| 24 | + /// - authHeader: Authorization header value |
| 25 | + /// - urlSession: URLSession to use for network requests (defaults to .shared) |
| 26 | + public init(siteID: String, baseURL: URL, authHeader: String, urlSession: URLSession = .shared) { |
| 27 | + self.siteID = siteID |
| 28 | + self.baseURL = baseURL |
| 29 | + self.authHeader = authHeader |
| 30 | + self.urlSession = urlSession |
| 31 | + |
| 32 | + self.storeURL = URL.documentsDirectory |
| 33 | + .appendingPathComponent("GutenbergKit", isDirectory: true) |
| 34 | + .appendingPathComponent(siteID.safeFilename, isDirectory: true) |
| 35 | + } |
| 36 | + |
| 37 | + /// Set up the editor for the given site. |
| 38 | + /// |
| 39 | + /// - warning: The request make take a significant amount of time the first |
| 40 | + /// time you open the editor. |
| 41 | + public func setup(_ configuration: inout EditorConfiguration) async throws { |
| 42 | + var builder = configuration.toBuilder() |
| 43 | + |
| 44 | + if !isEditorLoaded { |
| 45 | + try await refresh() |
| 46 | + } |
| 47 | + |
| 48 | + if let data = try? Data(contentsOf: editorSettingsFileURL), |
| 49 | + let settings = String(data: data, encoding: .utf8) { |
| 50 | + builder = builder.setEditorSettings(settings) |
| 51 | + } |
| 52 | + |
| 53 | + return configuration = builder.build() |
| 54 | + } |
| 55 | + |
| 56 | + /// Returns `true` is the resources requied for the editor already exist. |
| 57 | + private var isEditorLoaded: Bool { |
| 58 | + FileManager.default.fileExists(atPath: editorSettingsFileURL.absoluteString) |
| 59 | + } |
| 60 | + |
| 61 | + /// Refresh the editor settings and other resources. |
| 62 | + public func refresh() async throws { |
| 63 | + if let task = refreshTask { |
| 64 | + return try await task.value |
| 65 | + } |
| 66 | + let task = Task { |
| 67 | + defer { refreshTask = nil } |
| 68 | + try await actuallyRefresh() |
| 69 | + } |
| 70 | + refreshTask = task |
| 71 | + return try await task.value |
| 72 | + } |
| 73 | + |
| 74 | + private func actuallyRefresh() async throws { |
| 75 | + try await fetchEditorSettings() |
| 76 | + } |
| 77 | + |
| 78 | + // MARK: – Editor Settings |
| 79 | + |
| 80 | + /// Fetches block editor settings from the WordPress REST API |
| 81 | + /// |
| 82 | + /// - Returns: Raw settings data from the API |
| 83 | + @discardableResult |
| 84 | + private func fetchEditorSettings() async throws -> Data { |
| 85 | + let data = try await getData(for: baseURL.appendingPathComponent("/wp-block-editor/v1/settings")) |
| 86 | + do { |
| 87 | + createStoreDirectoryIfNeeded() |
| 88 | + try data.write(to: editorSettingsFileURL) |
| 89 | + } catch { |
| 90 | + assertionFailure("Failed to save settings: \(error)") |
| 91 | + } |
| 92 | + return data |
| 93 | + } |
| 94 | + |
| 95 | + // MARK: - Private Helpers |
| 96 | + |
| 97 | + private func createStoreDirectoryIfNeeded() { |
| 98 | + if !FileManager.default.fileExists(atPath: storeURL.path) { |
| 99 | + try? FileManager.default.createDirectory(at: storeURL, withIntermediateDirectories: true) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + private func getData(for requestURL: URL) async throws -> Data { |
| 104 | + var request = URLRequest(url: requestURL) |
| 105 | + request.setValue(authHeader, forHTTPHeaderField: "Authorization") |
| 106 | + |
| 107 | + let (data, response) = try await urlSession.data(for: request) |
| 108 | + guard let status = (response as? HTTPURLResponse)?.statusCode, |
| 109 | + (200..<300).contains(status) else { |
| 110 | + throw URLError(.badServerResponse) |
| 111 | + } |
| 112 | + return data |
| 113 | + } |
| 114 | +} |
0 commit comments