Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / XArticlePublishing.swift

Raw 18.5 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import CryptoKit
2import Foundation
3import SwiftUI
4
5/// X's Articles API uses snake_case DraftJS blocks, lowercase styles and a keyed entity array.
6@MainActor enum XArticleDocument {
7 static func payload(title: String, markdown: String) throws -> [String: Any] {
8 guard !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, title.utf16.count <= 300,
9 !markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
10 throw WorkspaceError("Add an article title and text before publishing.")
11 }
12 let document = try NewsletterDocument.parse(markdown)
13 var blocks: [[String: Any]] = []
14 var entities: [[String: Any]] = []
15 func entity(_ type: String, data: [String: Any], mutable: Bool = false) -> Int {
16 let key = entities.count
17 entities.append(["key": String(key), "value": ["type": type, "mutability": mutable ? "mutable" : "immutable", "data": data]])
18 return key
19 }
20 func append(_ node: [String: Any], context: String = "unstyled", depth: Int = 0) throws {
21 guard depth < 32 else { throw WorkspaceError("Simplify the article’s nested formatting.") }
22 let kind = node["type"] as? String ?? ""
23 let children = node["content"] as? [[String: Any]] ?? []
24 let attrs = node["attrs"] as? [String: Any] ?? [:]
25 switch kind {
26 case "doc", "listItem", "bulletList", "orderedList", "blockquote":
27 let type = ["bulletList": "unordered-list-item", "orderedList": "ordered-list-item", "blockquote": "blockquote"][kind] ?? context
28 for child in children { try append(child, context: type, depth: depth + 1) }
29 case "horizontal_rule", "code_block":
30 let code = children.compactMap { $0["text"] as? String }.joined()
31 let language = attrs["language"] as? String ?? ""
32 let key = entity(kind == "horizontal_rule" ? "divider" : "markdown",
33 data: kind == "horizontal_rule" ? [:] : ["markdown": "```\(language)\n\(code)\n```"], mutable: kind != "horizontal_rule")
34 blocks.append(["type": "atomic", "text": " ", "entity_ranges": [["key": key, "offset": 0, "length": 1]]])
35 case "captionedImage":
36 // Preserve external images as links; never download an arbitrary remote image with account credentials.
37 for image in children {
38 let imageAttrs = image["attrs"] as? [String: Any] ?? [:]
39 guard let url = imageAttrs["src"] as? String else { continue }
40 let label = imageAttrs["alt"] as? String ?? "View image"
41 let key = entity("link", data: ["url": url], mutable: true)
42 blocks.append(["type": "unstyled", "text": label, "entity_ranges": [["key": key, "offset": 0, "length": label.utf16.count]]])
43 }
44 case "paragraph", "heading":
45 var text = ""
46 var ranges: [[String: Any]] = []
47 var styles: [[String: Any]] = []
48 for span in children {
49 let value = span["type"] as? String == "hard_break" ? "\n" : span["text"] as? String ?? ""
50 let offset = text.utf16.count
51 text += value
52 for mark in span["marks"] as? [[String: Any]] ?? [] {
53 let markType = mark["type"] as? String ?? ""
54 if let style = ["strong": "bold", "em": "italic", "strikethrough": "strikethrough"][markType] {
55 styles.append(["offset": offset, "length": value.utf16.count, "style": style])
56 } else if markType == "link", let url = (mark["attrs"] as? [String: Any])?["href"] as? String {
57 let key = entity("link", data: ["url": url], mutable: true)
58 ranges.append(["offset": offset, "length": value.utf16.count, "key": key])
59 }
60 }
61 }
62 let type = kind == "heading" ? ((attrs["level"] as? Int ?? 1) == 1 ? "header-one" : "header-two") : context
63 blocks.append(["type": type, "text": text, "inline_style_ranges": styles, "entity_ranges": ranges])
64 default: throw WorkspaceError("This article contains formatting X cannot publish. Check the source before continuing.")
65 }
66 }
67 try append(document)
68 guard !blocks.isEmpty else { throw WorkspaceError("Write the article before publishing.") }
69 return ["title": title, "content_state": ["blocks": blocks, "entities": entities]]
70 }
71}
72
73struct XArticlePublishPlan {
74 let articleID: String
75 let revision: String
76 let title: String
77 let body: String
78 let accountKey: String
79 let accountName: String
80 let fingerprint: String
81 let payload: [String: Any]
82
83 @MainActor init(article: WorkspaceRecord, account: ManagedSocialAccount) throws {
84 guard article.isXArticle, article["state"] == "draft" else {
85 throw WorkspaceError("Choose an unpublished X article. Check any previous publishing attempt before retrying.")
86 }
87 let scopes = (account.session.scopes ?? "").split(whereSeparator: \.isWhitespace)
88 guard scopes.isEmpty || scopes.contains("tweet.write") else {
89 throw WorkspaceError("Reconnect X in Connections with permission to publish.")
90 }
91 articleID = article.id; revision = article["updatedAt"]; title = article.title; body = article.body
92 accountKey = account.connectionKey
93 accountName = account.username.isEmpty ? account.name : "@" + account.username
94 payload = try XArticleDocument.payload(title: title, markdown: article.body)
95 fingerprint = SHA256.hash(data: Data((try NewsletterDocument.canonical(["account": accountKey, "payload": payload])).utf8))
96 .map { String(format: "%02x", $0) }.joined()
97 }
98}
99
100@MainActor struct XArticlePublisher {
101 let workspace: Workspace
102 let transport: SocialTransport
103 let authorize: @MainActor () async throws -> ManagedSocialAccount
104
105 init(workspace: Workspace, transport: SocialTransport = .init(),
106 authorize: (@MainActor () async throws -> ManagedSocialAccount)? = nil) {
107 self.workspace = workspace; self.transport = transport
108 self.authorize = authorize ?? { try await workspace.socialAccounts.authorized(.x) }
109 }
110
111 func review(_ article: WorkspaceRecord) async throws -> XArticlePublishPlan {
112 try XArticlePublishPlan(article: article, account: await authorize())
113 }
114
115 func publish(_ plan: XArticlePublishPlan, fromAgent: Bool = false,
116 using existingLease: PublicationLease? = nil) async throws -> WorkspaceRecord {
117 let account = try await authorize()
118 let lease = try existingLease ?? workspace.claimPublication()
119 defer { withExtendedLifetime(lease) {} }
120 try workspace.reload()
121 guard let article = workspace.records.first(where: { $0.id == plan.articleID && $0.isXArticle }),
122 article["updatedAt"] == plan.revision,
123 try XArticlePublishPlan(article: article, account: account).fingerprint == plan.fingerprint else {
124 throw WorkspaceError("The article or X account changed. Review it again before publishing.")
125 }
126 var receipt = try workspace.beginXArticlePublication(plan, fromAgent: fromAgent)
127 do {
128 if receipt["remoteArticleId"].isEmpty {
129 receipt["phase"] = "creatingDraft"; try workspace.updateXArticlePublication(receipt)
130 let (result, _) = try await transport.request(URL(string: "https://api.x.com/2/articles/draft")!,
131 token: account.session.accessToken, method: "POST", json: plan.payload, publishes: true)
132 guard let id = (result["data"] as? [String: Any])?["id"] as? String, Self.validID(id) else {
133 throw SocialRequestError("X didn’t confirm the article draft. Check Articles on X before retrying.", uncertain: true)
134 }
135 receipt["remoteArticleId"] = id
136 receipt["phase"] = "draftCreated"; try workspace.updateXArticlePublication(receipt)
137 }
138 // Persist the remote draft before publishing so a known rejection can safely reuse it.
139 receipt["phase"] = "publishingArticle"; try workspace.updateXArticlePublication(receipt)
140 let address = "https://api.x.com/2/articles/" + receipt["remoteArticleId"] + "/publish"
141 let (result, _) = try await transport.request(URL(string: address)!, token: account.session.accessToken,
142 method: "POST", publishes: true)
143 guard let id = (result["data"] as? [String: Any])?["post_id"] as? String, Self.validID(id) else {
144 throw SocialRequestError("X didn’t confirm publication. Check your X profile before retrying.", uncertain: true)
145 }
146 receipt["status"] = "published"; receipt["phase"] = "published"
147 receipt["publishedAt"] = WorkspaceRecord.timestamp
148 receipt.fields["steps"] = [["id": id, "url": "https://x.com/i/web/status/" + id, "at": receipt["publishedAt"]]]
149 try workspace.updateXArticlePublication(receipt)
150 return receipt
151 } catch {
152 let uncertain = (error as? SocialRequestError)?.uncertain ?? true
153 receipt["status"] = uncertain ? "uncertain" : "failed"
154 let message: String
155 switch (error as? SocialRequestError)?.statusCode {
156 case 401: message = "Reconnect your X account in Connections, then review the article again."
157 case 403: message = "X declined Article access. Check that this account can publish Articles and the connection has posting permission. Your draft is safe."
158 case 402: message = "X requires API credits to publish this article. Add credits in the X Developer Console, then retry. Your draft is safe."
159 default: message = error.localizedDescription
160 }
161 receipt["error"] = message
162 try? workspace.updateXArticlePublication(receipt)
163 throw SocialRequestError(message, uncertain: uncertain)
164 }
165 }
166
167 private static func validID(_ value: String) -> Bool {
168 value.range(of: #"\A[0-9]{1,19}\z"#, options: .regularExpression) != nil
169 }
170}
171
172extension Workspace {
173 func beginXArticlePublication(_ plan: XArticlePublishPlan, fromAgent: Bool) throws -> WorkspaceRecord {
174 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
175 return try database.transaction {
176 try reload()
177 guard var article = records.first(where: { $0.isXArticle && $0.id == plan.articleID }),
178 article["state"] == "draft", article["updatedAt"] == plan.revision else {
179 throw WorkspaceError("The article changed or has an unresolved publishing attempt.")
180 }
181 if fromAgent, settings["mcpEnabled"] as? Bool != true || settings["mcpAllowPosting"] as? Bool != true {
182 throw WorkspaceError("Immediate agent posting is off in Inkspring Settings.")
183 }
184 let receipts = records.filter { $0.kind == "publication" && $0["draftId"] == article.id }
185 guard !receipts.contains(where: { ["publishing", "published", "uncertain"].contains($0["status"]) }) else {
186 throw WorkspaceError("Check the existing X Article publishing attempt before retrying.")
187 }
188 var receipt = receipts.first { $0["fingerprint"] == plan.fingerprint && $0["status"] == "failed" }
189 ?? .new("publication", projectID: article.projectID)
190 receipt["draftId"] = article.id; receipt["contentKind"] = "article"; receipt["platform"] = "x"
191 receipt["title"] = plan.title; receipt["accountId"] = plan.accountKey; receipt["accountName"] = plan.accountName
192 receipt["fingerprint"] = plan.fingerprint; receipt["status"] = "publishing"; receipt["error"] = ""
193 try database.put(receipt)
194 article["state"] = "publishing"; article["articlePublicationId"] = receipt.id
195 article.fields["articlePublishRequest"] = nil
196 try database.put(article); try reload()
197 return receipt
198 }
199 }
200
201 func updateXArticlePublication(_ input: WorkspaceRecord) throws {
202 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
203 try database.transaction {
204 try reload()
205 var receipt = input; receipt.markUpdated(); try database.put(receipt)
206 if var article = records.first(where: { $0.kind == "article" && $0.id == receipt["draftId"] }) {
207 article["state"] = receipt["status"] == "failed" ? "draft" : receipt["status"]
208 article["articlePublicationStatus"] = receipt["status"]
209 article["articlePublicationError"] = receipt["error"]
210 if receipt["status"] == "published" {
211 article["articleURL"] = (receipt.fields["steps"] as? [[String: String]])?.first?["url"] ?? ""
212 article["articlePublishedAt"] = receipt["publishedAt"]
213 }
214 try database.put(article)
215 }
216 try reload()
217 }
218 }
219
220 func queueXArticlePublication(id: String, revision: String, accountKey: String, requestID: String) throws {
221 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
222 try database.transaction {
223 try reload()
224 guard var article = records.first(where: { $0.isXArticle && $0.id == id }),
225 article["updatedAt"] == revision, article["state"] == "draft", !article.body.isEmpty,
226 !accountKey.isEmpty else { throw WorkspaceError("The article changed. Review the latest text before publishing.") }
227 if let pending = article.fields["articlePublishRequest"] as? [String: String] {
228 guard pending["id"] == requestID else { throw WorkspaceError("This article is already waiting for your Mac to publish.") }
229 return
230 }
231 article.fields["articlePublishRequest"] = ["id": requestID, "revision": revision, "account": accountKey]
232 article["articlePublicationStatus"] = "queued"; article["articlePublicationError"] = ""
233 try database.put(article); try reload()
234 }
235 }
236
237 func publishPendingXArticles(publisher: XArticlePublisher? = nil) async {
238 let publisher = publisher ?? XArticlePublisher(workspace: self)
239 for record in records where record.isXArticle && record.fields["articlePublishRequest"] != nil {
240 guard let request = record.fields["articlePublishRequest"] as? [String: String] else { continue }
241 do {
242 let plan = try await publisher.review(record)
243 guard request["revision"] == plan.revision, request["account"] == plan.accountKey else {
244 throw WorkspaceError("The article or connected X account changed. Review it again before publishing.")
245 }
246 _ = try await publisher.publish(plan)
247 } catch {
248 try? withChanges {
249 guard var current = records.first(where: { $0.id == record.id }), current["state"] == "draft" else { return }
250 current.fields["articlePublishRequest"] = nil
251 current["articlePublicationStatus"] = "failed"; current["articlePublicationError"] = error.localizedDescription
252 try database?.put(current); try reload()
253 }
254 }
255 }
256 }
257}
258
259struct XArticlePublishControls: View {
260 let workspace: Workspace
261 let article: WorkspaceRecord
262 let save: () -> Bool
263 @State private var reviewed: XArticlePublishPlan?
264 @State private var busy = false
265 @State private var error: String?
266 private var current: WorkspaceRecord { workspace.records.first { $0.id == article.id } ?? article }
267 var body: some View {
268 VStack(alignment: .leading, spacing: 8) {
269 HStack {
270 StudioPlatformLabel(name: "x", title: "X article")
271 if current["state"] == "draft" {
272 Button("Review & publish on X…", systemImage: "paperplane") {
273 guard save() else { return }
274 busy = true; error = nil
275 Task {
276 defer { busy = false }
277 do { reviewed = try await XArticlePublisher(workspace: workspace).review(current) }
278 catch { self.error = error.localizedDescription }
279 }
280 }.disabled(busy).accessibilityIdentifier("article.reviewPublish")
281 }
282 if busy || current["state"] == "publishing" { ProgressView().controlSize(.small) }
283 if let url = URL(string: current["articleURL"]), url.scheme == "https", url.host == "x.com" {
284 StudioExternalLink("View published article", destination: url)
285 }
286 }
287 Text("Publishes the full article to your connected X account. Requires X Article access and API credits.")
288 .font(.caption).foregroundStyle(.secondary)
289 if let reviewed {
290 Text("Publish “\(reviewed.title)” publicly as \(reviewed.accountName)?").font(.callout)
291 HStack {
292 Button("Cancel") { self.reviewed = nil }
293 Button("Publish article now", systemImage: "paperplane.fill") {
294 self.reviewed = nil; busy = true
295 Task {
296 defer { busy = false }
297 do { _ = try await XArticlePublisher(workspace: workspace).publish(reviewed) }
298 catch { self.error = error.localizedDescription }
299 }
300 }.disabled(busy).accessibilityIdentifier("article.publish")
301 }
302 }
303 if current["state"] == "uncertain" {
304 Text("X hasn’t confirmed the result. Check your X Articles before allowing another attempt in Publishing history.").font(.callout)
305 }
306 if let message = error ?? (current["articlePublicationError"].isEmpty ? nil : current["articlePublicationError"]) {
307 Text(message).font(.callout).foregroundStyle(.secondary).accessibilityIdentifier("article.publishError")
308 }
309 }.frame(maxWidth: .infinity, alignment: .leading).padding(14).studioSurface()
310 }
311}