Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / Substack.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import UniformTypeIdentifiers |
| 5 | |
| 6 | struct SubstackPublication: Codable, Equatable, Identifiable { |
| 7 | let id: String |
| 8 | let name: String |
| 9 | let origin: String |
| 10 | let userId: String |
| 11 | let role: String |
| 12 | |
| 13 | var fields: [String: String] { ["id": id, "name": name, "origin": origin, "userId": userId, "role": role] } |
| 14 | |
| 15 | func identifies(_ other: Self?) -> Bool { |
| 16 | guard let other else { return false } |
| 17 | return id == other.id && userId == other.userId && origin == other.origin |
| 18 | } |
| 19 | |
| 20 | static func decode(_ value: Any?) -> Self? { |
| 21 | guard let value, let data = try? JSONSerialization.data(withJSONObject: value, options: .fragmentsAllowed), |
| 22 | let publication = try? JSONDecoder().decode(Self.self, from: data), |
| 23 | let url = URL(string: publication.origin), SubstackAddresses.publicationOrigin(url) else { return nil } |
| 24 | return publication |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | private enum SubstackAddresses { |
| 29 | static func publicationOrigin(_ url: URL) -> Bool { |
| 30 | url.scheme == "https" && url.user == nil && url.password == nil && url.port == nil && |
| 31 | url.path.isEmpty && url.query == nil && url.fragment == nil && |
| 32 | url.host()?.range(of: #"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.substack\.com$"#, options: .regularExpression) != nil |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | struct SubstackReview: Identifiable { |
| 37 | let id = UUID() |
| 38 | let newsletterID: String |
| 39 | let revision: Int |
| 40 | let fingerprint: String |
| 41 | let publication: SubstackPublication |
| 42 | let title: String |
| 43 | let audience: String |
| 44 | let sendEmail: Bool |
| 45 | let scheduledAt: Date? |
| 46 | let expires: Date |
| 47 | } |
| 48 | |
| 49 | @MainActor |
| 50 | struct Substack { |
| 51 | typealias Transport = @MainActor (String, URL, [String: Any]?) async throws -> [String: Any] |
| 52 | let workspace: Workspace |
| 53 | private let transport: Transport |
| 54 | private let now: () -> Date |
| 55 | private static let roles = ["owner", "admin", "editor", "contributor"] |
| 56 | |
| 57 | init(workspace: Workspace, now: @escaping () -> Date = { .now }, transport: Transport? = nil) { |
| 58 | self.workspace = workspace |
| 59 | self.now = now |
| 60 | self.transport = transport ?? { method, url, payload in |
| 61 | try await workspace.substackSession.request(method, url, payload) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | var selected: SubstackPublication? { SubstackPublication.decode(workspace.settings["substackPublication"]) } |
| 66 | var accountName: String { (workspace.settings["substackAccount"] as? [String: Any])?["name"] as? String ?? "" } |
| 67 | var publications: [SubstackPublication] { |
| 68 | let account = workspace.settings["substackAccount"] as? [String: Any] |
| 69 | return (account?["publications"] as? [[String: Any]] ?? []).compactMap(SubstackPublication.decode) |
| 70 | } |
| 71 | |
| 72 | func checkConnection() async throws { |
| 73 | let account = workspace.settings["substackAccount"] as? [String: Any] |
| 74 | let expectedUser = try Self.remoteID(account?["userId"]) |
| 75 | let expectedPublication = selected |
| 76 | let profile = try await profile() |
| 77 | guard try Self.remoteID(profile["id"]) == expectedUser else { |
| 78 | throw WorkspaceError("Substack is signed into a different account. Sign in again to confirm which account to use.") |
| 79 | } |
| 80 | let accessible = try Self.publications(profile) |
| 81 | guard !accessible.isEmpty, |
| 82 | expectedPublication == nil || accessible.contains(where: { $0.identifies(expectedPublication) }) else { |
| 83 | throw WorkspaceError("Substack could not verify access to this publication. Sign in again and check your publication permissions.") |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | func connect() async throws { |
| 88 | try await run { |
| 89 | let profile = try await profile() |
| 90 | let publications = try Self.publications(profile) |
| 91 | guard !publications.isEmpty else { throw WorkspaceError("This account has no Substack publications you can edit.") } |
| 92 | let previous = selected |
| 93 | let name = profile["name"] as? String ?? profile["handle"] as? String ?? "Substack author" |
| 94 | try workspace.withChanges { |
| 95 | try workspace.set("substackAccount", to: ["name": String(name.prefix(200)), "userId": publications[0].userId, |
| 96 | "publications": publications.map(\.fields)]) |
| 97 | let match = publications.first { $0.identifies(previous) } |
| 98 | try workspace.set("substackPublication", to: match?.fields as Any? ?? NSNull()) |
| 99 | } |
| 100 | workspace.substackReviews.removeAll() |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | func select(_ id: String) throws { |
| 105 | guard !workspace.substackBusy else { throw WorkspaceError("Wait for the current Substack action.") } |
| 106 | let lease = try workspace.claimPublication() |
| 107 | defer { withExtendedLifetime(lease) {} } |
| 108 | try workspace.withChanges { |
| 109 | guard id.isEmpty || publications.contains(where: { $0.id == id }) else { |
| 110 | throw WorkspaceError("Choose a publication from this Substack account.") |
| 111 | } |
| 112 | let match = publications.first { $0.id == id } |
| 113 | try workspace.set("substackPublication", to: match?.fields as Any? ?? NSNull()) |
| 114 | } |
| 115 | workspace.substackReviews.removeAll() |
| 116 | } |
| 117 | |
| 118 | func disconnect() async throws { |
| 119 | try await run { |
| 120 | await workspace.substackSession.clear() |
| 121 | try workspace.withChanges { |
| 122 | try workspace.set("substackAccount", to: NSNull()) |
| 123 | try workspace.set("substackPublication", to: NSNull()) |
| 124 | } |
| 125 | workspace.substackReviews.removeAll() |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func sync(_ newsletterID: String) async throws -> WorkspaceRecord { |
| 130 | try await run { |
| 131 | var item = try record(newsletterID) |
| 132 | guard ["draft", "synced"].contains(item["state"]), |
| 133 | !item["body"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, |
| 134 | item["title"] != "Untitled newsletter" else { |
| 135 | throw WorkspaceError("Save a title and body, and check the draft’s status in Substack before syncing.") |
| 136 | } |
| 137 | var document = try NewsletterDocument.parse(item["body"]) |
| 138 | let publication = try await authorized(item) |
| 139 | guard let author = Int64(publication.userId), author <= 9_007_199_254_740_991 else { |
| 140 | throw WorkspaceError("Substack returned an unsupported author ID.") |
| 141 | } |
| 142 | let path = try draftPath(item["remoteId"]) |
| 143 | var payload: [String: Any] = [ |
| 144 | "draft_title": item["title"], "draft_subtitle": item["subtitle"], |
| 145 | "draft_bylines": [["id": author, "is_guest": false]], |
| 146 | "audience": item["audience"], "type": "newsletter", "should_send_email": Self.emails(item), |
| 147 | "section_chosen": true, "draft_section_id": NSNull(), "cover_image": NSNull() |
| 148 | ] |
| 149 | if !item["remoteId"].isEmpty { |
| 150 | let previous = try await remote(publication, item["remoteId"]) |
| 151 | guard !Self.isPublished(previous), Self.schedule(previous) == nil, |
| 152 | try Self.fingerprint(previous) == item["remoteFingerprint"] else { |
| 153 | throw WorkspaceError("The draft changed in Substack. Open its editor and review the changes.") |
| 154 | } |
| 155 | payload["last_updated_at"] = previous["draft_updated_at"] |
| 156 | } |
| 157 | if item.fields["coverImage"] is [String: Any] { |
| 158 | let coverURL = try await uploadCover(item, publication) |
| 159 | payload["cover_image"] = coverURL |
| 160 | document = NewsletterDocument.withLeadingCover(document, url: coverURL, title: item.title) |
| 161 | } |
| 162 | payload["draft_body"] = try NewsletterDocument.canonical(document) |
| 163 | let previousState = item["state"] |
| 164 | item = try workspace.patchNewsletter(item, ["state": "syncing", "error": ""]) |
| 165 | var responseArrived = false |
| 166 | do { |
| 167 | let response = try await request(item["remoteId"].isEmpty ? "POST" : "PUT", publication, path, payload) |
| 168 | responseArrived = true |
| 169 | let remoteID = try Self.remoteID(response["id"] ?? item["remoteId"]) |
| 170 | item = try workspace.patchNewsletter(item, ["remoteId": remoteID, "publication": publication.fields, |
| 171 | "editUrl": publication.origin + "/publish/post/" + remoteID]) |
| 172 | let actual = try await remote(publication, remoteID) |
| 173 | guard !Self.isPublished(actual), Self.schedule(actual) == nil, |
| 174 | actual["cover_image"] as? String == payload["cover_image"] as? String, |
| 175 | try Self.matches(item, actual, document: document) else { |
| 176 | throw WorkspaceError("The Substack draft differs from this newsletter. Check its editor.") |
| 177 | } |
| 178 | return try workspace.patchNewsletter(item, ["state": "synced", "syncedRevision": Self.revision(item), |
| 179 | "remoteFingerprint": try Self.fingerprint(actual), |
| 180 | "embeddedCoverURL": payload["cover_image"] as? String ?? "", "error": ""]) |
| 181 | } catch { |
| 182 | let uncertain = responseArrived || !item["remoteId"].isEmpty || (error as? SubstackRequestError)?.uncertain == true |
| 183 | _ = try workspace.patchNewsletter(item, ["state": uncertain ? "uncertain" : previousState, "error": error.localizedDescription]) |
| 184 | throw error |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func prepare(_ newsletterID: String, at date: Date?) async throws -> SubstackReview { |
| 190 | try await run { |
| 191 | let item = try record(newsletterID) |
| 192 | let publication = try await authorized(item) |
| 193 | try Self.canSend(item, publication) |
| 194 | try validate(date) |
| 195 | let post = try await remote(publication, item["remoteId"]) |
| 196 | try Self.verify(item, post, fingerprint: item["remoteFingerprint"]) |
| 197 | let review = SubstackReview(newsletterID: item.id, revision: Self.revision(item), fingerprint: item["remoteFingerprint"], |
| 198 | publication: publication, title: item.title, audience: item["audience"], |
| 199 | sendEmail: Self.emails(item), scheduledAt: date, expires: now().addingTimeInterval(600)) |
| 200 | workspace.substackReviews[item.id] = review.id |
| 201 | return review |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func commit(_ review: SubstackReview) async throws -> WorkspaceRecord { |
| 206 | try await run { |
| 207 | guard workspace.substackReviews[review.newsletterID] == review.id else { |
| 208 | throw WorkspaceError("Review this newsletter again before sending.") |
| 209 | } |
| 210 | workspace.substackReviews.removeValue(forKey: review.newsletterID) |
| 211 | var item = try record(review.newsletterID) |
| 212 | guard review.expires > now(), Self.revision(item) == review.revision, review.publication.identifies(selected) else { |
| 213 | throw WorkspaceError("Review this newsletter again before sending.") |
| 214 | } |
| 215 | let publication = try await authorized(item) |
| 216 | try Self.canSend(item, publication) |
| 217 | let post = try await remote(publication, item["remoteId"]) |
| 218 | try Self.verify(item, post, fingerprint: review.fingerprint) |
| 219 | try validate(review.scheduledAt) |
| 220 | let path = try draftPath(item["remoteId"]) |
| 221 | let at = review.scheduledAt.map(workspaceTimestamp) ?? "" |
| 222 | let check = try await request("GET", publication, path + "/prepublish" + (at.isEmpty ? "" : "?publish_date=" + at)) |
| 223 | guard let errors = check["errors"] as? [Any], errors.isEmpty else { |
| 224 | throw WorkspaceError("Check the pre-publish requirements in Substack before sending.") |
| 225 | } |
| 226 | guard review.expires > now() else { throw WorkspaceError("The review expired. Review this newsletter again.") } |
| 227 | try validate(review.scheduledAt) |
| 228 | item = try workspace.patchNewsletter(item, ["state": "releasing", "requestedAction": at.isEmpty ? "publish" : "schedule", |
| 229 | "requestedAt": at, "error": ""]) |
| 230 | do { |
| 231 | if at.isEmpty { |
| 232 | _ = try await request("POST", publication, path + "/publish", ["send": Self.emails(item), "share_automatically": false]) |
| 233 | } else { |
| 234 | _ = try await request("POST", publication, path + "/scheduled_release", |
| 235 | ["trigger_at": at, "post_audience": item["audience"], "email_audience": item["audience"]]) |
| 236 | } |
| 237 | let result = try await remote(publication, item["remoteId"]) |
| 238 | guard Self.isPublished(result) || (review.scheduledAt != nil && Self.schedule(result) == review.scheduledAt) else { |
| 239 | throw WorkspaceError("Substack hasn’t confirmed the send. Check its editor before trying again.") |
| 240 | } |
| 241 | return try recordRemote(item, result, publication) |
| 242 | } catch { |
| 243 | _ = try workspace.patchNewsletter(item, ["state": "uncertain", "error": error.localizedDescription]) |
| 244 | throw error |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | func refresh(_ newsletterID: String) async throws -> WorkspaceRecord { |
| 250 | try await run { |
| 251 | let item = try record(newsletterID) |
| 252 | let publication = try await authorized(item) |
| 253 | guard !item["remoteId"].isEmpty else { throw WorkspaceError("No draft ID was confirmed. Check the drafts in Substack.") } |
| 254 | let post = try await remote(publication, item["remoteId"]) |
| 255 | if Self.isPublished(post) || Self.schedule(post) != nil |
| 256 | || (item["state"] == "uncertain" && item["requestedAction"] == "cancel") { |
| 257 | return try recordRemote(item, post, publication) |
| 258 | } |
| 259 | if item["state"] == "scheduled", item["requestedAction"] == "schedule", |
| 260 | let date = scheduleDate(item["scheduledAt"]), (0..<600).contains(now().timeIntervalSince(date)) { |
| 261 | return item |
| 262 | } |
| 263 | if ["uncertain", "scheduled"].contains(item["state"]) { |
| 264 | return try workspace.patchNewsletter(item, ["state": "uncertain", "error": "Substack reports a draft. Check its editor and confirm the outcome."]) |
| 265 | } |
| 266 | return item |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | func cancel(_ newsletterID: String) async throws -> WorkspaceRecord { |
| 271 | try await run { |
| 272 | var item = try record(newsletterID) |
| 273 | let publication = try await authorized(item) |
| 274 | guard publication.role != "contributor", item["state"] == "scheduled" else { |
| 275 | throw WorkspaceError("Refresh the scheduled newsletter and check your Substack permissions.") |
| 276 | } |
| 277 | let post = try await remote(publication, item["remoteId"]) |
| 278 | guard !Self.isPublished(post), Self.schedule(post) != nil else { |
| 279 | throw WorkspaceError("Substack does not report a cancellable schedule. Refresh its status.") |
| 280 | } |
| 281 | let path = try draftPath(item["remoteId"]) |
| 282 | item = try workspace.patchNewsletter(item, ["state": "releasing", "requestedAction": "cancel", "error": ""]) |
| 283 | do { |
| 284 | do { |
| 285 | _ = try await request("DELETE", publication, path + "/scheduled_release") |
| 286 | } catch let error as SubstackRequestError where error.uncertain { |
| 287 | // The draft readback below can confirm cancellation even if the response was unreadable. |
| 288 | } |
| 289 | let result = try await remote(publication, item["remoteId"]) |
| 290 | guard !Self.isPublished(result), Self.schedule(result) == nil else { |
| 291 | throw WorkspaceError("Substack hasn’t confirmed cancellation. Check its editor.") |
| 292 | } |
| 293 | return try recordRemote(item, result, publication) |
| 294 | } catch { |
| 295 | _ = try workspace.patchNewsletter(item, ["state": "uncertain", "error": error.localizedDescription]) |
| 296 | throw error |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | func acknowledge(_ newsletterID: String) async throws -> WorkspaceRecord { |
| 302 | try await run { |
| 303 | let item = try record(newsletterID) |
| 304 | guard item["state"] == "uncertain" else { throw WorkspaceError("Only an unconfirmed attempt needs this check.") } |
| 305 | if !item["remoteId"].isEmpty { |
| 306 | let publication = try await authorized(item) |
| 307 | let result = try await remote(publication, item["remoteId"]) |
| 308 | if Self.isPublished(result) || Self.schedule(result) != nil { return try recordRemote(item, result, publication) } |
| 309 | return try workspace.patchNewsletter(item, ["state": "synced", "syncedRevision": 0, |
| 310 | "remoteFingerprint": try Self.fingerprint(result), "error": ""]) |
| 311 | } |
| 312 | return try workspace.patchNewsletter(item, ["state": "draft", "syncedRevision": 0, "error": ""]) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | private func run<T>(_ action: () async throws -> T) async throws -> T { |
| 317 | guard !workspace.substackBusy else { throw WorkspaceError("Wait for the current Substack action.") } |
| 318 | let lease = try workspace.claimPublication() |
| 319 | workspace.substackBusy = true |
| 320 | defer { |
| 321 | workspace.substackBusy = false |
| 322 | withExtendedLifetime(lease) {} |
| 323 | } |
| 324 | try workspace.reload() |
| 325 | return try await action() |
| 326 | } |
| 327 | |
| 328 | private func profile() async throws -> [String: Any] { |
| 329 | try await transport("GET", URL(string: "https://substack.com/api/v1/user/profile/self")!, nil) |
| 330 | } |
| 331 | |
| 332 | private func authorized(_ item: WorkspaceRecord) async throws -> SubstackPublication { |
| 333 | guard let selected else { throw WorkspaceError("Choose a publication in Connections.") } |
| 334 | if item.fields["publication"] is [String: Any], !selected.identifies(SubstackPublication.decode(item.fields["publication"])) { |
| 335 | throw WorkspaceError("Choose this newsletter’s original publication in Connections.") |
| 336 | } |
| 337 | let publications = try Self.publications(await profile()) |
| 338 | guard let current = publications.first(where: { $0.identifies(selected) }) else { |
| 339 | throw WorkspaceError("Reconnect Substack and check your account’s publication permissions.") |
| 340 | } |
| 341 | return current |
| 342 | } |
| 343 | |
| 344 | private static func publications(_ profile: [String: Any]) throws -> [SubstackPublication] { |
| 345 | let userID = try remoteID(profile["id"]) |
| 346 | return try (profile["publicationUsers"] as? [[String: Any]] ?? []).compactMap { row in |
| 347 | guard let role = row["role"] as? String, roles.contains(role), |
| 348 | let publication = row["publication"] as? [String: Any], let domain = publication["subdomain"] as? String, |
| 349 | let url = URL(string: "https://" + domain.lowercased() + ".substack.com"), |
| 350 | SubstackAddresses.publicationOrigin(url) else { return nil } |
| 351 | let name = String((publication["name"] as? String ?? domain).prefix(200)) |
| 352 | return SubstackPublication(id: try remoteID(publication["id"]), name: name, origin: url.absoluteString, userId: userID, role: role) |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | private func record(_ id: String) throws -> WorkspaceRecord { |
| 357 | guard let item = workspace.records.first(where: { $0.kind == "newsletter" && $0.id == id }) else { |
| 358 | throw WorkspaceError("This newsletter is no longer available.") |
| 359 | } |
| 360 | return item |
| 361 | } |
| 362 | |
| 363 | private func draftPath(_ id: String) throws -> String { |
| 364 | "/api/v1/drafts" + (id.isEmpty ? "" : "/" + (try Self.remoteID(id))) |
| 365 | } |
| 366 | |
| 367 | private func request(_ method: String, _ publication: SubstackPublication, _ path: String, |
| 368 | _ payload: [String: Any]? = nil) async throws -> [String: Any] { |
| 369 | guard let url = URL(string: publication.origin + path), SubstackSession.host(url) != nil else { |
| 370 | throw WorkspaceError("The Substack publication address is invalid.") |
| 371 | } |
| 372 | return try await transport(method, url, payload) |
| 373 | } |
| 374 | |
| 375 | private func remote(_ publication: SubstackPublication, _ id: String) async throws -> [String: Any] { |
| 376 | let id = try Self.remoteID(id) |
| 377 | let post = try await request("GET", publication, draftPath(id)) |
| 378 | guard try Self.remoteID(post["id"]) == id else { throw WorkspaceError("Substack returned a different draft.") } |
| 379 | return post |
| 380 | } |
| 381 | |
| 382 | private func uploadCover(_ item: WorkspaceRecord, _ publication: SubstackPublication) async throws -> String { |
| 383 | guard let file = workspace.mediaURL(item) else { throw WorkspaceError("The newsletter cover image is unavailable.") } |
| 384 | let values = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) |
| 385 | guard values.isRegularFile == true, values.isSymbolicLink != true, (1...30_000_000).contains(values.fileSize ?? 0), |
| 386 | let source = CGImageSourceCreateWithURL(file as CFURL, nil), let type = CGImageSourceGetType(source), |
| 387 | let mime = UTType(type as String)?.preferredMIMEType, ["image/jpeg", "image/png", "image/webp"].contains(mime) else { |
| 388 | throw WorkspaceError("Use a PNG, JPEG or WebP newsletter cover up to 30 MB.") |
| 389 | } |
| 390 | let bytes = try Data(contentsOf: file) |
| 391 | let result = try await request("POST", publication, "/api/v1/image", ["image": "data:" + mime + ";base64," + bytes.base64EncodedString()]) |
| 392 | guard let raw = result["url"] as? String, let url = URL(string: raw), url.scheme == "https", |
| 393 | url.user == nil, url.password == nil, url.port == nil, let host = url.host(), |
| 394 | host.hasSuffix(".substackcdn.com") || (host.hasPrefix("substack-post-media.") && host.hasSuffix(".amazonaws.com")) else { |
| 395 | throw WorkspaceError("Substack did not return a valid cover image address.") |
| 396 | } |
| 397 | return url.absoluteString |
| 398 | } |
| 399 | |
| 400 | private func recordRemote(_ item: WorkspaceRecord, _ post: [String: Any], _ publication: SubstackPublication) throws -> WorkspaceRecord { |
| 401 | let scheduledAt = Self.schedule(post) |
| 402 | let published = Self.isPublished(post) |
| 403 | let same = (try? Self.matches(item, post)) == true |
| 404 | let slug = post["slug"] as? String ?? "" |
| 405 | let postURL = published && slug.range(of: #"^[a-zA-Z0-9][a-zA-Z0-9-]*$"#, options: .regularExpression) != nil |
| 406 | ? publication.origin + "/p/" + slug : "" |
| 407 | return try workspace.patchNewsletter(item, [ |
| 408 | "state": published ? "published" : scheduledAt == nil ? "synced" : "scheduled", |
| 409 | "scheduledAt": scheduledAt.map(workspaceTimestamp) ?? "", |
| 410 | "publishedAt": published ? post["post_date"] as? String ?? "" : "", |
| 411 | "postUrl": postURL, |
| 412 | "remoteFingerprint": same ? try Self.fingerprint(post) : item["remoteFingerprint"], |
| 413 | "error": same ? "" : "The Substack content differs from this local copy. Open its editor to review." |
| 414 | ]) |
| 415 | } |
| 416 | |
| 417 | private func validate(_ date: Date?) throws { |
| 418 | guard let date else { return } |
| 419 | let current = now() |
| 420 | let limit = Calendar(identifier: .gregorian).date(byAdding: .month, value: 3, to: current) ?? current |
| 421 | guard date >= current.addingTimeInterval(60), date <= limit, date == PostScheduling.startOfMinute(date) else { |
| 422 | throw WorkspaceError("Choose a time at least one minute from now and within the next three months.") |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | private static func canSend(_ item: WorkspaceRecord, _ publication: SubstackPublication) throws { |
| 427 | guard publication.role != "contributor" else { throw WorkspaceError("This role can save drafts. Ask a publication editor to send.") } |
| 428 | guard !needsSync(item) else { |
| 429 | throw WorkspaceError("Save the latest newsletter to Substack before reviewing the send.") |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | static func needsSync(_ item: WorkspaceRecord) -> Bool { |
| 434 | item["state"] != "synced" || item["remoteId"].isEmpty || item.fields["syncedRevision"] as? Int != revision(item) |
| 435 | || (item.fields["coverImage"] is [String: Any] && item["embeddedCoverURL"].isEmpty) |
| 436 | } |
| 437 | |
| 438 | private static func verify(_ item: WorkspaceRecord, _ post: [String: Any], fingerprint: String) throws { |
| 439 | guard !isPublished(post), schedule(post) == nil, try matches(item, post), try Self.fingerprint(post) == fingerprint else { |
| 440 | throw WorkspaceError("The draft changed in Substack. Refresh its status and review it again.") |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | private static func remoteID(_ value: Any?) throws -> String { |
| 445 | let id = value as? String ?? (value as? NSNumber)?.stringValue ?? "" |
| 446 | guard id.range(of: #"^[0-9]{1,24}$"#, options: .regularExpression) != nil else { |
| 447 | throw WorkspaceError("Substack returned an invalid record ID.") |
| 448 | } |
| 449 | return id |
| 450 | } |
| 451 | |
| 452 | static func editorURL(_ item: WorkspaceRecord) -> URL? { |
| 453 | guard let publication = SubstackPublication.decode(item.fields["publication"]), let id = try? remoteID(item["remoteId"]) else { return nil } |
| 454 | return URL(string: publication.origin + "/publish/post/" + id) |
| 455 | } |
| 456 | |
| 457 | static func audienceLabel(_ audience: String) -> String { |
| 458 | ["only_paid": "Paid subscribers", "founding": "Founding members"][audience] ?? "Everyone" |
| 459 | } |
| 460 | |
| 461 | static func emails(_ item: WorkspaceRecord) -> Bool { item.fields["sendEmail"] as? Bool ?? false } |
| 462 | private static func revision(_ item: WorkspaceRecord) -> Int { item.fields["revision"] as? Int ?? 0 } |
| 463 | private static func isPublished(_ post: [String: Any]) -> Bool { post["is_published"] as? Bool == true } |
| 464 | |
| 465 | private static func schedule(_ post: [String: Any]) -> Date? { |
| 466 | let rows = post["postSchedules"] as? [[String: Any]] |
| 467 | guard let raw = post["trigger_at"] as? String ?? rows?.first?["trigger_at"] as? String else { return nil } |
| 468 | return (try? Date(raw, strategy: .iso8601)) ?? (try? Date(raw, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true))) |
| 469 | } |
| 470 | |
| 471 | private static func body(_ post: [String: Any]) throws -> Any { |
| 472 | guard let value = post["draft_body"] else { throw WorkspaceError("Substack returned an unreadable draft.") } |
| 473 | if let text = value as? String { return try JSONSerialization.jsonObject(with: Data(text.utf8)) } |
| 474 | return value |
| 475 | } |
| 476 | |
| 477 | private static func matches(_ item: WorkspaceRecord, _ post: [String: Any], document: [String: Any]? = nil) throws -> Bool { |
| 478 | guard post["draft_title"] as? String == item.title, (post["draft_subtitle"] as? String ?? "") == item["subtitle"], |
| 479 | post["audience"] as? String == item["audience"], post["should_send_email"] as? Bool == emails(item) else { return false } |
| 480 | var expected = try document ?? NewsletterDocument.parse(item["body"]) |
| 481 | if document == nil, !item["embeddedCoverURL"].isEmpty { |
| 482 | expected = NewsletterDocument.withLeadingCover(expected, url: item["embeddedCoverURL"], title: item.title) |
| 483 | } |
| 484 | return try NewsletterDocument.canonical(body(post)) == NewsletterDocument.canonical(expected) |
| 485 | } |
| 486 | |
| 487 | static func fingerprint(_ post: [String: Any]) throws -> String { |
| 488 | let values: [Any] = [post["draft_title"] ?? NSNull(), post["draft_subtitle"] as? String ?? "", |
| 489 | try body(post), post["audience"] ?? NSNull(), post["should_send_email"] ?? NSNull(), |
| 490 | post["cover_image"] ?? NSNull(), post["draft_section_id"] ?? NSNull()] |
| 491 | return SHA256.hash(data: Data(try NewsletterDocument.canonical(values).utf8)).map { String(format: "%02x", $0) }.joined() |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | extension Workspace { |
| 496 | func refreshDueSubstackNewsletters(now: Date = .now) async { |
| 497 | guard !substackBusy, Substack(workspace: self).selected != nil else { return } |
| 498 | let due = records.filter { item in |
| 499 | guard item.kind == "newsletter", ["scheduled", "uncertain"].contains(item["state"]), |
| 500 | item["requestedAction"] != "cancel", let date = scheduleDate(item["scheduledAt"]) else { return false } |
| 501 | return (0..<86_400).contains(now.timeIntervalSince(date)) |
| 502 | } |
| 503 | for item in due.prefix(4) { |
| 504 | if Task.isCancelled { return } |
| 505 | _ = try? await Substack(workspace: self).refresh(item.id) |
| 506 | } |
| 507 | } |
| 508 | } |