Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / NewsletterWorkflowTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | |
| 5 | @Test @MainActor func newsletterEditorSavesDraftsWithMissingDeliverySettings() throws { |
| 6 | let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 7 | defer { try? FileManager.default.removeItem(at: root) } |
| 8 | let workspace = Workspace(directory: root) |
| 9 | let database = try #require(workspace.database) |
| 10 | var legacy = WorkspaceRecord.new("newsletter", projectID: workspace.projectID) |
| 11 | legacy["title"] = "A saved newsletter" |
| 12 | legacy["body"] = "We has a plan." |
| 13 | legacy.fields["revision"] = 4 |
| 14 | legacy.fields["audience"] = nil |
| 15 | legacy.fields["sendEmail"] = nil |
| 16 | legacy = try database.put(legacy) |
| 17 | |
| 18 | var edited = legacy |
| 19 | edited["body"] = "We have a plan." |
| 20 | let saved = try workspace.saveNewsletterEditor(edited, basedOn: legacy) |
| 21 | #expect(saved.body == "We have a plan.") |
| 22 | #expect(saved["audience"] == "everyone") |
| 23 | #expect(saved.fields["sendEmail"] as? Bool == false) |
| 24 | #expect(saved.fields["revision"] as? Int == 5) |
| 25 | #expect(saved["state"] == "draft") |
| 26 | |
| 27 | var invalid = saved |
| 28 | invalid["subtitle"] = String(repeating: "a", count: 1_001) |
| 29 | do { |
| 30 | _ = try workspace.saveNewsletterEditor(invalid, basedOn: saved) |
| 31 | Issue.record("An overlong subtitle should not save.") |
| 32 | } catch { |
| 33 | #expect(error.localizedDescription == "Shorten the subtitle to 1,000 characters or less.") |
| 34 | } |
| 35 | #expect(try database.records().first { $0.id == saved.id }?.fields["revision"] as? Int == 5) |
| 36 | } |
| 37 | |
| 38 | @Test @MainActor func newsletterMarkdownMatchesElectronFingerprint() throws { |
| 39 | let markdown = """ |
| 40 | ## Heading |
| 41 | |
| 42 | > Bold **word** |
| 43 | |
| 44 | 3. First |
| 45 | 4. Second |
| 46 | |
| 47 | ```swift |
| 48 | let item = 1 |
| 49 | ``` |
| 50 | |
| 51 | ~~struck~~ and [link](https://example.com/) |
| 52 | |
| 53 |  |
| 54 | """ |
| 55 | let document = try NewsletterDocument.parse(markdown) |
| 56 | let post: [String: Any] = [ |
| 57 | "draft_title": "Test", "draft_subtitle": "", "draft_body": try NewsletterDocument.canonical(document), |
| 58 | "audience": "everyone", "should_send_email": false, "cover_image": NSNull(), "draft_section_id": NSNull() |
| 59 | ] |
| 60 | #expect(try Substack.fingerprint(post) == "5d01928146decb1dc5a4bd8ec93229451ba800a4c3f0f4f29c5d471ab6fc2b63") |
| 61 | let unsafe = try NewsletterDocument.parse("<script>alert(1)</script>") |
| 62 | let html = NewsletterDocument.html(unsafe, title: "Test & compare", subtitle: "") |
| 63 | #expect(html.contains("Test & compare")) |
| 64 | #expect(!html.contains("<script>")) |
| 65 | } |
| 66 | |
| 67 | @Test(arguments: [false, true]) |
| 68 | @MainActor func substackChecksRemoteDraftAndConfirmsScheduleCancellationAndPublication(emailSubscribers: Bool) async throws { |
| 69 | let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 70 | defer { try? FileManager.default.removeItem(at: root) } |
| 71 | let workspace = Workspace(directory: root) |
| 72 | var now = Date(timeIntervalSince1970: 1_800_000_010) |
| 73 | let when = PostScheduling.fiveMinutesFromNow(now) |
| 74 | let coverURL = "https://images.substackcdn.com/example.png" |
| 75 | var requests: [String] = [] |
| 76 | var remote: [String: Any] = [:] |
| 77 | var signedInUser = 18 |
| 78 | var canEditPublication = true |
| 79 | let service = Substack(workspace: workspace, now: { now }) { method, url, payload in |
| 80 | requests.append(method + " " + url.path) |
| 81 | if url.host() == "substack.com" { |
| 82 | #expect(method == "GET") |
| 83 | return ["id": signedInUser, "name": "Fixture author", "publicationUsers": canEditPublication ? [ |
| 84 | ["role": "owner", "publication": ["id": 95, "name": "Fixture newsletter", "subdomain": "fixture"]] |
| 85 | ] : []] |
| 86 | } |
| 87 | #expect(url.host() == "fixture.substack.com") |
| 88 | switch (method, url.path) { |
| 89 | case ("POST", "/api/v1/image"): |
| 90 | #expect((payload?["image"] as? String)?.hasPrefix("data:image/png;base64,") == true) |
| 91 | return ["url": coverURL] |
| 92 | case ("POST", "/api/v1/drafts"), ("PUT", "/api/v1/drafts/73"): |
| 93 | remote = try #require(payload) |
| 94 | #expect(remote["should_send_email"] as? Bool == emailSubscribers) |
| 95 | #expect(remote["cover_image"] as? String == coverURL) |
| 96 | let body = try #require(remote["draft_body"] as? String) |
| 97 | let document = try #require(JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any]) |
| 98 | let blocks = try #require(document["content"] as? [[String: Any]]) |
| 99 | let image = try #require((blocks.first?["content"] as? [[String: Any]])?.first) |
| 100 | #expect(blocks.map { $0["type"] as? String } == ["captionedImage", "paragraph"]) |
| 101 | #expect((image["attrs"] as? [String: String])?["src"] == coverURL) |
| 102 | remote["id"] = 73 |
| 103 | remote["is_published"] = false |
| 104 | return ["id": 73] |
| 105 | case ("GET", "/api/v1/drafts/73"): |
| 106 | return remote |
| 107 | case ("GET", "/api/v1/drafts/73/prepublish"): |
| 108 | if let query = url.query() { #expect(query == "publish_date=" + workspaceTimestamp(when)) } |
| 109 | return ["errors": [String]()] |
| 110 | case ("POST", "/api/v1/drafts/73/scheduled_release"): |
| 111 | #expect(payload?["trigger_at"] as? String == workspaceTimestamp(when)) |
| 112 | #expect(payload?["email_audience"] as? String == "everyone") |
| 113 | remote["trigger_at"] = payload?["trigger_at"] |
| 114 | return [:] |
| 115 | case ("DELETE", "/api/v1/drafts/73/scheduled_release"): |
| 116 | remote["trigger_at"] = nil |
| 117 | throw SubstackRequestError("Substack returned an unreadable cancellation response.", uncertain: true) |
| 118 | case ("POST", "/api/v1/drafts/73/publish"): |
| 119 | #expect(payload?["send"] as? Bool == emailSubscribers) |
| 120 | remote["is_published"] = true |
| 121 | remote["post_date"] = workspaceTimestamp(now) |
| 122 | remote["slug"] = "swift-fixture" |
| 123 | return [:] |
| 124 | default: |
| 125 | Issue.record("Unexpected Substack request.") |
| 126 | throw WorkspaceError("Unexpected request.") |
| 127 | } |
| 128 | } |
| 129 | try await service.connect() |
| 130 | #expect(service.selected == nil) |
| 131 | try service.select("95") |
| 132 | let beforeCheck = requests.count |
| 133 | try await service.checkConnection() |
| 134 | #expect(Array(requests.dropFirst(beforeCheck)) == ["GET /api/v1/user/profile/self"]) |
| 135 | signedInUser = 19 |
| 136 | await #expect(throws: WorkspaceError.self) { try await service.checkConnection() } |
| 137 | signedInUser = 18 |
| 138 | canEditPublication = false |
| 139 | await #expect(throws: WorkspaceError.self) { try await service.checkConnection() } |
| 140 | canEditPublication = true |
| 141 | #expect(service.selected?.id == "95") |
| 142 | var item = WorkspaceRecord.new("newsletter", projectID: workspace.projectID) |
| 143 | #expect(Substack.emails(item)) |
| 144 | if !emailSubscribers { item.fields["sendEmail"] = false } |
| 145 | item["title"] = "Swift fixture" |
| 146 | item["body"] = "A draft in **Markdown**." |
| 147 | let cover = root.appending(path: "cover.png") |
| 148 | let png = try #require(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR1sAAAAASUVORK5CYII=")) |
| 149 | try png.write(to: cover) |
| 150 | item.fields["coverImage"] = try workspace.attachImage(cover) |
| 151 | item = try workspace.save(item) |
| 152 | item = try await service.sync(item.id) |
| 153 | #expect(item["state"] == "synced") |
| 154 | #expect(item.fields["syncedRevision"] as? Int == 1) |
| 155 | #expect(item["embeddedCoverURL"] == coverURL) |
| 156 | var legacyCover = item |
| 157 | legacyCover["embeddedCoverURL"] = "" |
| 158 | #expect(Substack.needsSync(legacyCover)) |
| 159 | #expect(workspace.workspaceDrafts.contains { $0.id == item.id }) |
| 160 | |
| 161 | let firstReview = try await service.prepare(item.id, at: when) |
| 162 | remote["draft_title"] = "Edited externally" |
| 163 | await #expect(throws: WorkspaceError.self) { _ = try await service.commit(firstReview) } |
| 164 | #expect(!requests.contains("POST /api/v1/drafts/73/scheduled_release")) |
| 165 | remote["draft_title"] = item.title |
| 166 | |
| 167 | let expiredReview = try await service.prepare(item.id, at: when) |
| 168 | let initialTime = now |
| 169 | now = when.addingTimeInterval(-59) |
| 170 | await #expect(throws: WorkspaceError.self) { _ = try await service.commit(expiredReview) } |
| 171 | #expect(!requests.contains("POST /api/v1/drafts/73/scheduled_release")) |
| 172 | now = initialTime |
| 173 | |
| 174 | let scheduleReview = try await service.prepare(item.id, at: when) |
| 175 | #expect(scheduleReview.sendEmail == emailSubscribers) |
| 176 | item = try await service.commit(scheduleReview) |
| 177 | #expect(item["state"] == "scheduled") |
| 178 | #expect(item["scheduledAt"] == workspaceTimestamp(when)) |
| 179 | await #expect(throws: WorkspaceError.self) { _ = try await service.commit(scheduleReview) } |
| 180 | now = when.addingTimeInterval(10) |
| 181 | remote["trigger_at"] = nil |
| 182 | item = try await service.refresh(item.id) |
| 183 | #expect(item["state"] == "scheduled") |
| 184 | remote["trigger_at"] = workspaceTimestamp(when) |
| 185 | item = try await service.cancel(item.id) |
| 186 | #expect(item["state"] == "synced") |
| 187 | #expect(item["scheduledAt"].isEmpty) |
| 188 | |
| 189 | let publishReview = try await service.prepare(item.id, at: nil) |
| 190 | item = try await service.commit(publishReview) |
| 191 | #expect(item["state"] == "published") |
| 192 | #expect(item["postUrl"] == "https://fixture.substack.com/p/swift-fixture") |
| 193 | #expect(!workspace.workspaceDrafts.contains { $0.id == item.id }) |
| 194 | await #expect(throws: WorkspaceError.self) { _ = try await service.commit(publishReview) } |
| 195 | #expect(requests.filter { $0 == "POST /api/v1/drafts/73/publish" }.count == 1) |
| 196 | |
| 197 | let requestsBeforeCopy = requests |
| 198 | let copy = NewsletterDocument.localCopy(of: item) |
| 199 | #expect(copy.id != item.id) |
| 200 | #expect(copy.title == item.title + " (copy)") |
| 201 | #expect(copy.body == item.body) |
| 202 | #expect(copy["audience"] == item["audience"]) |
| 203 | #expect(Substack.emails(copy) == Substack.emails(item)) |
| 204 | #expect(workspace.records.first { $0.id == copy.id } == nil) |
| 205 | let savedCopy = try workspace.save(copy) |
| 206 | #expect(savedCopy["state"] == "draft") |
| 207 | #expect(savedCopy.fields["revision"] as? Int == 1) |
| 208 | for key in ["remoteId", "remoteFingerprint", "postUrl", "scheduledAt", "syncedRevision"] { |
| 209 | #expect(savedCopy.fields[key] == nil) |
| 210 | } |
| 211 | #expect(workspace.records.first { $0.id == item.id }?["state"] == "published") |
| 212 | #expect(requests == requestsBeforeCopy) |
| 213 | |
| 214 | var longTitle = item |
| 215 | longTitle["title"] = String(repeating: "🪶", count: 150) |
| 216 | let shortened = NewsletterDocument.localCopy(of: longTitle) |
| 217 | #expect(shortened.title.utf16.count <= 300) |
| 218 | #expect(shortened.title.hasSuffix(" (copy)")) |
| 219 | } |
| 220 | |
| 221 | @Test func r2SignaturesMatchElectronImplementation() throws { |
| 222 | let profile = R2Profile(configuration: R2Configuration(accountId: String(repeating: "a", count: 32), |
| 223 | bucket: "media-fixture", jurisdiction: "eu"), |
| 224 | accessKeyId: "TESTKEY123", secretAccessKey: "SYNTHETICONLY") |
| 225 | let signer = R2Signer(profile: profile) |
| 226 | let date = try Date("2026-01-02T03:04:05Z", strategy: .iso8601) |
| 227 | let key = "inkspring-instagram/media/example.jpg" |
| 228 | let request = try signer.signedRequest(method: "PUT", key: key, hash: R2Signer.sha(Data("Example media".utf8)), now: date) |
| 229 | #expect(request.value(forHTTPHeaderField: "Authorization")?.hasSuffix("Signature=aed37dbf5ff83847587eb5547170e5c738938ce7b2d528ace1f18c7bde3b027e") == true) |
| 230 | let url = try signer.link(key, now: date) |
| 231 | #expect(url.absoluteString.hasSuffix("X-Amz-Signature=6b1b17150260e27772a3a13a71d01919bb10de0c646b50a35b949c65f23be4f0")) |
| 232 | #expect(throws: WorkspaceError.self) { try signer.link("inkspring-instagram/../other", now: date) } |
| 233 | } |
| 234 | |
| 235 | @Test @MainActor func newsletterGenerationUsesSelectedSourcesAndRejectsConcurrentEdits() async throws { |
| 236 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 237 | defer { try? FileManager.default.removeItem(at: folder) } |
| 238 | let workspace = Workspace(directory: folder) |
| 239 | let projectID = workspace.projectID |
| 240 | let selected = try workspace.saveResearchReference(["title": "Selected evidence", "text": "A useful source."], projectID: projectID) |
| 241 | _ = try workspace.saveResearchReference(["title": "Unselected evidence", "text": "Keep this local."], projectID: projectID) |
| 242 | var draft = WorkspaceRecord.new("newsletter", projectID: projectID) |
| 243 | draft["body"] = "Existing editor text." |
| 244 | let draftID = draft.id |
| 245 | var requestCount = 0 |
| 246 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, input in |
| 247 | requestCount += 1 |
| 248 | let sources = try #require(input["sources"] as? [[String: String]]) |
| 249 | #expect(sources.compactMap { $0["title"] } == ["Selected evidence"]) |
| 250 | let draft = try #require(input["currentDraft"] as? [String: String]) |
| 251 | #expect(draft["body"] == "Existing editor text." || draft["body"] == "A fresh **newsletter**.") |
| 252 | if requestCount == 2, var editing = workspace.records.first(where: { $0.id == draftID }) { |
| 253 | editing["body"] = "An edit from another window." |
| 254 | try workspace.save(editing) |
| 255 | } |
| 256 | return ["title": "Fixture newsletter", "subtitle": "A test issue", "body": "A fresh **newsletter**."] |
| 257 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 258 | let studio = ContentStudio(workspace: workspace, model: model) |
| 259 | let generated = try await studio.writeNewsletter(draft, brief: "Write a draft.", sourceIDs: [selected.id]) |
| 260 | #expect(generated["state"] == "draft") |
| 261 | #expect(generated.fields["sendEmail"] as? Bool == true) |
| 262 | #expect(generated.fields["revision"] as? Int == 1) |
| 263 | #expect(workspace.records.first { $0.id == draft.id }?["body"] == "A fresh **newsletter**.") |
| 264 | |
| 265 | await #expect(throws: WorkspaceError.self) { |
| 266 | _ = try await studio.writeNewsletter(generated, brief: "Revise the draft.", sourceIDs: [selected.id]) |
| 267 | } |
| 268 | #expect(workspace.records.first { $0.id == draft.id }?["body"] == "An edit from another window.") |
| 269 | await #expect(throws: WorkspaceError.self) { |
| 270 | _ = try await studio.writeNewsletter(generated, brief: "Retry with the old version.", sourceIDs: [selected.id]) |
| 271 | } |
| 272 | #expect(requestCount == 2) |
| 273 | } |
| 274 | |
| 275 | @Test @MainActor func newsletterMarkdownImportKeepsCodeIndentation() { |
| 276 | let draft = NewsletterDocument.importMarkdown("\u{feff}# Title\r\n\r\n let item = 1\r\n", filename: "Fixture") |
| 277 | #expect(draft.title == "Title") |
| 278 | #expect(draft.body == " let item = 1\n") |
| 279 | let noHeading = NewsletterDocument.importMarkdown("## Section\nBody", filename: "Fixture") |
| 280 | #expect(noHeading.title == "Fixture") |
| 281 | #expect(noHeading.body == "## Section\nBody") |
| 282 | } |