Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / SocialPublishing.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import Darwin |
| 4 | import InkspringSchedule |
| 5 | |
| 6 | struct SocialPublishOptions { |
| 7 | var imageURL = "" |
| 8 | var subreddit = "" |
| 9 | var flair = "" |
| 10 | var tiktok: TikTokReviewOptions? |
| 11 | var creator: TikTokCreator? |
| 12 | var video: TikTokVideo? |
| 13 | var nativeVideo: PostVideo? |
| 14 | var instagramCover: URL? |
| 15 | var linkedInThumbnailURL: URL? |
| 16 | var linkedInDestination: LinkedInDestination? |
| 17 | var useR2 = false |
| 18 | var r2: R2Configuration? |
| 19 | } |
| 20 | |
| 21 | struct XPostArticleLinks { |
| 22 | static let pendingURL = "https://x.com/i/web/status/0" |
| 23 | let opening: WorkspaceRecord? |
| 24 | let replies: [Int: WorkspaceRecord] |
| 25 | |
| 26 | var articles: [WorkspaceRecord] { |
| 27 | var seen: Set<String> = [] |
| 28 | return ([opening].compactMap { $0 } + replies.sorted { $0.key < $1.key }.map(\.value)) |
| 29 | .filter { seen.insert($0.id).inserted } |
| 30 | } |
| 31 | |
| 32 | init(draft: WorkspaceRecord, posts: [String], records: [WorkspaceRecord]) throws { |
| 33 | let available = records.filter { $0.isXArticle && $0.projectID == draft.projectID } |
| 34 | let explicitlyLinked: WorkspaceRecord? |
| 35 | if draft["xArticleID"].isEmpty { |
| 36 | explicitlyLinked = nil |
| 37 | } else { |
| 38 | guard let article = available.first(where: { $0.id == draft["xArticleID"] }) else { |
| 39 | throw WorkspaceError("Choose an available X article for the opening post.") |
| 40 | } |
| 41 | explicitlyLinked = article |
| 42 | } |
| 43 | var links: [Int: WorkspaceRecord] = [:] |
| 44 | for (index, post) in posts.enumerated() where post.contains(XReplyArticle.prefix) { |
| 45 | let link = XReplyArticle(post) |
| 46 | guard index > 0, let reference = link.reference, !link.copy.contains(XReplyArticle.prefix), |
| 47 | let article = available.first(where: { $0.referenceID == reference }) else { |
| 48 | throw WorkspaceError("Choose an available X article for this reply.") |
| 49 | } |
| 50 | links[index] = article |
| 51 | } |
| 52 | let replyArticleIDs = Set(links.values.map(\.id)) |
| 53 | opening = explicitlyLinked ?? (replyArticleIDs.count == 1 ? links.values.first : nil) |
| 54 | replies = links |
| 55 | } |
| 56 | |
| 57 | func resolve(_ posts: [String], pending: Set<String>) throws -> [String] { |
| 58 | try posts.enumerated().map { index, post in |
| 59 | guard let article = index == 0 ? opening : replies[index] else { return post } |
| 60 | let url = pending.contains(article.id) ? Self.pendingURL : article["articleURL"] |
| 61 | guard pending.contains(article.id) || article["state"] == "published" && |
| 62 | url.range(of: #"\Ahttps://x\.com/i/web/status/[0-9]+\z"#, options: .regularExpression) != nil else { |
| 63 | throw WorkspaceError("Publish the X article “\(article.title)” before sending its link.") |
| 64 | } |
| 65 | let copy = index == 0 ? post : XReplyArticle(post).copy |
| 66 | return copy.isEmpty ? url : copy + "\n" + url |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | struct XArticlePostReview { |
| 72 | let post: SocialPublishPlan |
| 73 | let articles: [XArticlePublishPlan] |
| 74 | let accountKey: String |
| 75 | } |
| 76 | |
| 77 | struct SocialPublishPlan { |
| 78 | static let supported = Set(SocialPlatform.allCases) |
| 79 | |
| 80 | let platform: SocialPlatform |
| 81 | let draftID: String |
| 82 | let revision: String |
| 83 | let title: String |
| 84 | let accountID: String |
| 85 | let accountName: String |
| 86 | let posts: [String] |
| 87 | let replyID: String? |
| 88 | let image: URL? |
| 89 | let imageHash: String? |
| 90 | let linkedInDestination: LinkedInDestination? |
| 91 | var linkedInAuthor: String? { linkedInDestination?.urn } |
| 92 | let publicImage: URL? |
| 93 | let subreddit: String? |
| 94 | let flair: String? |
| 95 | let tiktok: TikTokReviewOptions? |
| 96 | let creator: TikTokCreator? |
| 97 | let video: TikTokVideo? |
| 98 | let nativeVideo: PostVideo? |
| 99 | let instagramCover: URL? |
| 100 | let instagramCoverHash: String? |
| 101 | let linkedInThumbnail: LinkedInVideoThumbnail? |
| 102 | let r2: R2Configuration? |
| 103 | |
| 104 | var fingerprint: String { |
| 105 | var parts = [platform.rawValue, draftID, accountID, title, replyID ?? ""] |
| 106 | parts += [imageHash ?? "", linkedInAuthor ?? "", publicImage?.absoluteString ?? "", subreddit ?? "", flair ?? ""] |
| 107 | parts += posts + (tiktok?.fingerprintFields ?? []) + (r2?.identity ?? []) |
| 108 | if let nativeVideo { parts.append(nativeVideo.hash) } |
| 109 | if let instagramCoverHash { parts.append(instagramCoverHash) } |
| 110 | if let linkedInThumbnail { parts.append(linkedInThumbnail.hash) } |
| 111 | let data = (try? JSONEncoder().encode(parts)) ?? Data() |
| 112 | return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() |
| 113 | } |
| 114 | |
| 115 | init(draft: WorkspaceRecord, account: ManagedSocialAccount, imageURL: URL?, options: SocialPublishOptions = .init(), |
| 116 | articles: [WorkspaceRecord] = [], pendingXArticleIDs: Set<String> = []) throws { |
| 117 | guard draft.fields["manualQuote"] as? Bool != true else { |
| 118 | throw WorkspaceError("Open this quote draft in X to publish it.") |
| 119 | } |
| 120 | let text = draft.body.trimmingCharacters(in: .whitespacesAndNewlines) |
| 121 | guard !text.isEmpty else { throw WorkspaceError("Write the post before publishing.") } |
| 122 | guard let platform = SocialPlatform(rawValue: draft["platform"]), Self.supported.contains(platform) else { |
| 123 | throw WorkspaceError("Direct publishing for this platform is still being ported.") |
| 124 | } |
| 125 | if text.contains(XReplyArticle.prefix), !(platform == .x && ["thread", "followup"].contains(draft["format"])) { |
| 126 | throw WorkspaceError("Use an X follow-up reply for the linked article.") |
| 127 | } |
| 128 | self.platform = platform |
| 129 | draftID = draft.id |
| 130 | revision = draft["updatedAt"] |
| 131 | title = draft.title |
| 132 | accountID = account.id |
| 133 | accountName = options.linkedInDestination?.name ?? (account.username.isEmpty ? account.name : account.username) |
| 134 | let scopes = (account.session.scopes ?? "").split { $0.isWhitespace || $0 == "," } |
| 135 | tiktok = options.tiktok |
| 136 | creator = options.creator |
| 137 | video = options.video |
| 138 | nativeVideo = options.nativeVideo |
| 139 | if draft.needsNativePostVideo && nativeVideo == nil { |
| 140 | throw WorkspaceError("Attach the video file before publishing this post.") |
| 141 | } |
| 142 | if platform == .instagram, nativeVideo != nil, draft.fields["videoThumbnail"] != nil { |
| 143 | guard let cover = options.instagramCover, |
| 144 | let attributes = try? cover.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]), |
| 145 | attributes.isRegularFile == true, attributes.isSymbolicLink != true else { |
| 146 | throw WorkspaceError("The Instagram Reel cover is unavailable. Attach it again before publishing.") |
| 147 | } |
| 148 | instagramCover = cover |
| 149 | instagramCoverHash = try fileDigest(cover, limit: 20_000_000).hash |
| 150 | } else { |
| 151 | instagramCover = nil |
| 152 | instagramCoverHash = nil |
| 153 | } |
| 154 | if platform == .linkedin, nativeVideo != nil, draft.fields["videoThumbnail"] != nil { |
| 155 | guard let url = options.linkedInThumbnailURL else { |
| 156 | throw WorkspaceError("The LinkedIn video thumbnail is unavailable. Attach it again before publishing.") |
| 157 | } |
| 158 | linkedInThumbnail = try LinkedInVideoThumbnail(url: url) |
| 159 | } else { |
| 160 | linkedInThumbnail = nil |
| 161 | } |
| 162 | r2 = platform == .instagram && options.useR2 ? options.r2 : nil |
| 163 | publicImage = (platform == .instagram && nativeVideo == nil && !options.useR2) || (platform == .tiktok && !options.imageURL.isEmpty) |
| 164 | ? try Self.publicImageURL(options.imageURL) : nil |
| 165 | let redditName = options.subreddit.trimmingCharacters(in: .whitespacesAndNewlines) |
| 166 | .replacingOccurrences(of: #"\Ar/"#, with: "", options: .regularExpression) |
| 167 | subreddit = platform == .reddit ? redditName : nil |
| 168 | flair = platform == .reddit && !options.flair.isEmpty ? options.flair : nil |
| 169 | if platform == .x { |
| 170 | guard ["post", "followup", "thread", "image", "video", "reply"].contains(draft["format"]) else { |
| 171 | throw WorkspaceError("Choose an X post, thread or reply.") |
| 172 | } |
| 173 | let parts = ["followup", "thread"].contains(draft["format"]) ? XThreadText.posts(in: text) : [text] |
| 174 | let links = try XPostArticleLinks(draft: draft, posts: parts, records: articles) |
| 175 | posts = try links.resolve(parts, pending: pendingXArticleIDs) |
| 176 | let limit = draft.fields["longPost"] as? Bool == true ? 25_000 : 280 |
| 177 | if links.opening != nil, let opening = posts.first, Self.xWeight(opening) > limit { |
| 178 | throw WorkspaceError("Shorten the opening X post to make room for its linked article.") |
| 179 | } |
| 180 | if draft["format"] == "followup", posts.count != 2 { |
| 181 | throw WorkspaceError("A post with reply needs an opening post and one follow-up.") |
| 182 | } |
| 183 | guard (1...XThreadText.limit).contains(posts.count), posts.enumerated().allSatisfy({ index, post in |
| 184 | Self.xWeight(post) <= (index == 0 ? limit : 280) |
| 185 | }) else { |
| 186 | throw WorkspaceError("Use up to 25 thread posts and keep each post within the X character limit.") |
| 187 | } |
| 188 | if draft["format"] == "reply" { |
| 189 | let target = (draft.fields["replyTo"] as? [String: Any])?["url"] as? String ?? "" |
| 190 | let pattern = #"\Ahttps://(?:www\.|mobile\.)?(?:x|twitter)\.com/(?:[A-Za-z0-9_]{1,15}|i(?:/web)?)/status(?:es)?/([0-9]{1,25})(?:[/?#]|\z)"# |
| 191 | guard let match = target.range(of: pattern, options: .regularExpression) else { |
| 192 | throw WorkspaceError("Add the X post link before publishing a reply.") |
| 193 | } |
| 194 | replyID = target[match].split(whereSeparator: { "/?#".contains($0) }).last.map(String.init) |
| 195 | } else { |
| 196 | replyID = nil |
| 197 | } |
| 198 | if nativeVideo != nil && !scopes.isEmpty && !scopes.contains("media.write") { |
| 199 | throw WorkspaceError("Reconnect X with permission to upload video.") |
| 200 | } |
| 201 | if draft["format"] == "image" && nativeVideo == nil && imageURL == nil { |
| 202 | throw WorkspaceError("Attach an image before publishing.") |
| 203 | } |
| 204 | if nativeVideo == nil, ["post", "image", "reply", "followup", "thread"].contains(draft["format"]), let imageURL { |
| 205 | guard scopes.isEmpty || scopes.contains("media.write") else { |
| 206 | throw WorkspaceError("Reconnect X with permission to upload images.") |
| 207 | } |
| 208 | let resource = try imageURL.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) |
| 209 | guard resource.isRegularFile == true, resource.isSymbolicLink != true else { |
| 210 | throw WorkspaceError("The attached image is unavailable.") |
| 211 | } |
| 212 | image = imageURL |
| 213 | imageHash = try fileDigest(imageURL, limit: 20_000_000).hash |
| 214 | } else { |
| 215 | image = nil |
| 216 | imageHash = nil |
| 217 | } |
| 218 | linkedInDestination = nil |
| 219 | } else if platform == .linkedin { |
| 220 | let destination = options.linkedInDestination ?? LinkedInDestination.personal(account) |
| 221 | let raw = draft.fields["linkedinDestination"] as? [String: Any] |
| 222 | let saved = LinkedInDestination(fields: raw) |
| 223 | guard (raw == nil || saved?.urn == destination.urn), |
| 224 | destination.memberId == account.id else { |
| 225 | throw WorkspaceError("This draft targets a different LinkedIn account. Choose the destination again.") |
| 226 | } |
| 227 | if destination.kind == "personal", !scopes.isEmpty, !scopes.contains("w_member_social") { |
| 228 | throw WorkspaceError("Reconnect LinkedIn with permission to publish to your profile.") |
| 229 | } |
| 230 | if destination.kind == "organization", !LinkedInPages.available(account) { |
| 231 | throw WorkspaceError("Reconnect LinkedIn with company-page publishing access.") |
| 232 | } |
| 233 | linkedInDestination = destination |
| 234 | guard ["post", "video"].contains(draft["format"]), text.unicodeScalars.count <= 3000, |
| 235 | account.id.range(of: #"\A[A-Za-z0-9_-]{1,200}\z"#, options: .regularExpression) != nil else { |
| 236 | throw WorkspaceError("Keep the LinkedIn post within 3,000 characters.") |
| 237 | } |
| 238 | posts = [text] |
| 239 | replyID = nil |
| 240 | if nativeVideo == nil, draft.fields["image"] != nil { |
| 241 | guard let imageURL else { throw WorkspaceError("The LinkedIn image is unavailable. Attach it again before publishing.") } |
| 242 | image = imageURL |
| 243 | imageHash = try fileDigest(imageURL, limit: 20_000_000).hash |
| 244 | } else { |
| 245 | image = nil |
| 246 | imageHash = nil |
| 247 | } |
| 248 | } else { |
| 249 | replyID = nil |
| 250 | linkedInDestination = nil |
| 251 | posts = [text] |
| 252 | if platform == .instagram { |
| 253 | guard ["image", "post", "video"].contains(draft["format"]), text.unicodeScalars.count <= 2200, |
| 254 | account.id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil else { |
| 255 | throw WorkspaceError("Use one Instagram image or video and a caption of up to 2,200 characters.") |
| 256 | } |
| 257 | if nativeVideo != nil { |
| 258 | guard r2 != nil else { throw WorkspaceError("Set up R2 in Settings → Storage & backups → Instagram media hosting to publish a Reel.") } |
| 259 | image = nil |
| 260 | imageHash = nil |
| 261 | } else if options.useR2 { |
| 262 | guard r2 != nil, let imageURL else { throw WorkspaceError("Set up R2 and attach an image before publishing.") } |
| 263 | image = imageURL |
| 264 | imageHash = try fileDigest(imageURL, limit: 20_000_000).hash |
| 265 | } else { |
| 266 | image = nil |
| 267 | imageHash = nil |
| 268 | } |
| 269 | } else if platform == .tiktok { |
| 270 | guard let tiktok, let creator else { throw WorkspaceError("Review the TikTok account and posting options.") } |
| 271 | try tiktok.validate(creator: creator, video: video) |
| 272 | if draft["format"] == "video", let video, let imageURL { |
| 273 | image = imageURL |
| 274 | imageHash = video.hash |
| 275 | } else if draft["format"] == "image" { |
| 276 | if creator.usesManagedMedia, let imageURL { |
| 277 | image = imageURL |
| 278 | imageHash = try fileDigest(imageURL, limit: 20_000_000).hash |
| 279 | } else if !creator.usesManagedMedia, publicImage != nil { |
| 280 | image = nil |
| 281 | imageHash = nil |
| 282 | } else { |
| 283 | throw WorkspaceError("Choose a photo or enter its verified public URL.") |
| 284 | } |
| 285 | } else { |
| 286 | throw WorkspaceError("Attach a photo or video before publishing to TikTok.") |
| 287 | } |
| 288 | } else { |
| 289 | guard ["post", "image"].contains(draft["format"]), draft.title.unicodeScalars.count <= 300, |
| 290 | redditName.range(of: #"\A[A-Za-z0-9_]{2,50}\z"#, options: .regularExpression) != nil, |
| 291 | flair == nil || flair?.range(of: #"\A[A-Za-z0-9-]{1,100}\z"#, options: .regularExpression) != nil else { |
| 292 | throw WorkspaceError("Enter a subreddit, a title of up to 300 characters, and a valid flair ID if required.") |
| 293 | } |
| 294 | if draft["format"] == "image" { |
| 295 | guard let imageURL else { throw WorkspaceError("Attach an image before publishing.") } |
| 296 | image = imageURL |
| 297 | imageHash = try fileDigest(imageURL, limit: 20_000_000).hash |
| 298 | } else { |
| 299 | image = nil |
| 300 | imageHash = nil |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | private static func publicImageURL(_ text: String) throws -> URL { |
| 307 | let text = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 308 | guard text.utf8.count <= 3000, let url = URL(string: text), url.scheme == "https", |
| 309 | url.user == nil, url.password == nil, let host = url.host(), host.contains("."), |
| 310 | host.range(of: #"(^|\.)(localhost|local|internal|test|invalid)\.?\z"#, options: [.regularExpression, .caseInsensitive]) == nil else { |
| 311 | throw WorkspaceError("Enter a public HTTPS JPEG URL that Instagram can fetch.") |
| 312 | } |
| 313 | var address = in_addr() |
| 314 | guard inet_aton(host, &address) == 0, !host.contains(":") else { |
| 315 | throw WorkspaceError("Use a public domain name for the Instagram image.") |
| 316 | } |
| 317 | return url |
| 318 | } |
| 319 | |
| 320 | static func xWeight(_ text: String) -> Int { |
| 321 | XThreadText.weight(text) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | @MainActor |
| 326 | struct SocialPublisher { |
| 327 | typealias Authorization = @MainActor (SocialPlatform) async throws -> ManagedSocialAccount |
| 328 | let workspace: Workspace |
| 329 | let transport: SocialTransport |
| 330 | let authorize: Authorization |
| 331 | let r2Client: @MainActor () throws -> R2Client? |
| 332 | |
| 333 | init(workspace: Workspace, transport: SocialTransport = SocialTransport(), authorize: Authorization? = nil, |
| 334 | r2Client: @escaping @MainActor () throws -> R2Client? = { try R2Profile.saved().map { R2Client(profile: $0) } }) { |
| 335 | self.workspace = workspace |
| 336 | self.transport = transport |
| 337 | self.authorize = authorize ?? { try await workspace.socialAccounts.authorized($0) } |
| 338 | self.r2Client = r2Client |
| 339 | } |
| 340 | |
| 341 | func review(_ draft: WorkspaceRecord, options: SocialPublishOptions = .init()) async throws -> SocialPublishPlan { |
| 342 | guard let platform = SocialPlatform(rawValue: draft["platform"]), SocialPublishPlan.supported.contains(platform) else { |
| 343 | throw WorkspaceError("Direct publishing for this platform is still being ported.") |
| 344 | } |
| 345 | let account = try await authorize(platform) |
| 346 | return try await prepare(draft, account: account, options: options) |
| 347 | } |
| 348 | |
| 349 | func reviewXArticlePost(_ draft: WorkspaceRecord) async throws -> XArticlePostReview? { |
| 350 | guard draft["platform"] == "x" else { return nil } |
| 351 | let account = try await authorize(.x) |
| 352 | return try await reviewXArticlePost(draft, account: account) |
| 353 | } |
| 354 | |
| 355 | private func reviewXArticlePost(_ draft: WorkspaceRecord, account: ManagedSocialAccount) async throws -> XArticlePostReview? { |
| 356 | try workspace.reload() |
| 357 | guard let current = workspace.drafts.first(where: { $0.id == draft.id }), current["updatedAt"] == draft["updatedAt"] else { |
| 358 | throw WorkspaceError("The post changed. Open the review again.") |
| 359 | } |
| 360 | let parts = ["followup", "thread"].contains(current["format"]) ? XThreadText.posts(in: current.body) : [current.body] |
| 361 | let links = try XPostArticleLinks(draft: current, posts: parts, records: workspace.records) |
| 362 | let pending = links.articles.filter { $0["state"] != "published" } |
| 363 | guard !pending.isEmpty else { return nil } |
| 364 | guard !["posting", "posted", "uncertain"].contains(current.scheduleStatus), !workspace.records.contains(where: { |
| 365 | $0.kind == "publication" && $0["draftId"] == current.id && ["publishing", "published", "uncertain"].contains($0["status"]) |
| 366 | }) else { throw WorkspaceError("Check the existing X publishing attempt before retrying.") } |
| 367 | let articles = try pending.map { try XArticlePublishPlan(article: $0, account: account) } |
| 368 | let plan = try await prepare(current, account: account, options: .init(), pendingXArticleIDs: Set(pending.map(\.id))) |
| 369 | return XArticlePostReview(post: plan, articles: articles, accountKey: account.connectionKey) |
| 370 | } |
| 371 | |
| 372 | func publishXArticlePost(_ reviewed: XArticlePostReview, automatic: Bool = false) async throws -> WorkspaceRecord { |
| 373 | let account = try await authorize(.x) |
| 374 | let lease = try workspace.claimPublication() |
| 375 | defer { withExtendedLifetime(lease) {} } |
| 376 | try workspace.reload() |
| 377 | guard let draft = workspace.drafts.first(where: { $0.id == reviewed.post.draftID }), |
| 378 | draft["updatedAt"] == reviewed.post.revision, account.connectionKey == reviewed.accountKey, |
| 379 | let current = try await reviewXArticlePost(draft, account: account), |
| 380 | current.post.fingerprint == reviewed.post.fingerprint, |
| 381 | current.articles.map(\.revision) == reviewed.articles.map(\.revision), |
| 382 | current.articles.map(\.fingerprint) == reviewed.articles.map(\.fingerprint) else { |
| 383 | throw WorkspaceError("The post, article or X account changed. Open the review again.") |
| 384 | } |
| 385 | let publisher = XArticlePublisher(workspace: workspace, transport: transport, authorize: { try await authorize(.x) }) |
| 386 | let readyVideoID: String? |
| 387 | if let video = current.post.nativeVideo { |
| 388 | readyVideoID = try await PostVideoUpload(transport: transport).toX(video, token: account.session.accessToken) |
| 389 | } else { |
| 390 | readyVideoID = nil |
| 391 | } |
| 392 | var published: [String] = [] |
| 393 | do { |
| 394 | for article in reviewed.articles { |
| 395 | try workspace.reload() |
| 396 | guard let latest = workspace.drafts.first(where: { $0.id == draft.id }), latest["updatedAt"] == reviewed.post.revision else { |
| 397 | throw WorkspaceError("The post changed. Review it again.") |
| 398 | } |
| 399 | if automatic, workspace.settings["autoPost"] as? Bool != true || latest.scheduleStatus != "queued" { |
| 400 | throw WorkspaceError("Automatic posting is paused or this post was unscheduled.") |
| 401 | } |
| 402 | _ = try await publisher.publish(article, using: lease) |
| 403 | published.append(article.title) |
| 404 | } |
| 405 | let plan = try await prepare(draft, account: account, options: .init()) |
| 406 | return try await publish(plan, automatic: automatic, using: lease, readyVideoID: readyVideoID) |
| 407 | } catch { |
| 408 | if !published.isEmpty { |
| 409 | throw WorkspaceError("Published on X: \(published.joined(separator: ", ")). The remaining items need attention. \(error.localizedDescription)") |
| 410 | } |
| 411 | throw error |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | private func prepare(_ draft: WorkspaceRecord, account: ManagedSocialAccount, |
| 416 | options: SocialPublishOptions, pendingXArticleIDs: Set<String> = []) async throws -> SocialPublishPlan { |
| 417 | var options = options |
| 418 | options.nativeVideo = try PostVideo.forDraft(draft, in: workspace.records) |
| 419 | if draft["platform"] == "instagram", options.nativeVideo != nil { |
| 420 | options.instagramCover = workspace.videoThumbnailURL(draft) |
| 421 | } else if draft["platform"] == "linkedin", options.nativeVideo != nil { |
| 422 | options.linkedInThumbnailURL = workspace.videoThumbnailURL(draft) |
| 423 | } |
| 424 | let url = draft["format"] == "video" ? workspace.videoURL(draft) : workspace.imageURL(draft) |
| 425 | if draft["platform"] == "instagram", options.useR2 || options.nativeVideo != nil { |
| 426 | options.useR2 = true |
| 427 | options.r2 = try r2Client()?.profile.configuration |
| 428 | } |
| 429 | if draft["platform"] == "linkedin", |
| 430 | let destination = LinkedInDestination(fields: draft.fields["linkedinDestination"] as? [String: Any]) { |
| 431 | guard account.id == destination.memberId else { |
| 432 | throw WorkspaceError("The LinkedIn account changed. Choose the destination and review again.") |
| 433 | } |
| 434 | if destination.kind == "organization" { |
| 435 | let pages = try await LinkedInPages.refresh(account, transport: transport) |
| 436 | guard let page = pages.first(where: { $0.urn == destination.urn && $0.memberId == destination.memberId }) else { |
| 437 | throw WorkspaceError("LinkedIn no longer confirms access to this company page.") |
| 438 | } |
| 439 | options.linkedInDestination = page |
| 440 | } else { |
| 441 | options.linkedInDestination = LinkedInDestination.personal(account) |
| 442 | } |
| 443 | } |
| 444 | if draft["platform"] == "tiktok" { |
| 445 | options.creator = try await tikTokCreator(account: account) |
| 446 | if draft["format"] == "video", let url { options.video = try await TikTokVideo.inspect(url) } |
| 447 | if draft["format"] == "video" { options.tiktok?.coverTimestampMS = try TikTokVideo.coverTimestamp(for: draft) } |
| 448 | } |
| 449 | return try SocialPublishPlan(draft: draft, account: account, imageURL: url, options: options, |
| 450 | articles: workspace.records, pendingXArticleIDs: pendingXArticleIDs) |
| 451 | } |
| 452 | |
| 453 | func publish(_ reviewed: SocialPublishPlan, automatic: Bool = false, fromAgent: Bool = false, |
| 454 | using existingLease: PublicationLease? = nil, readyVideoID: String? = nil) async throws -> WorkspaceRecord { |
| 455 | let account = try await authorize(reviewed.platform) |
| 456 | try workspace.reload() |
| 457 | guard let draft = workspace.records.first(where: { $0.id == reviewed.draftID && $0.kind == "draft" }), |
| 458 | draft["updatedAt"] == reviewed.revision else { |
| 459 | throw WorkspaceError("The draft changed. Open the review again.") |
| 460 | } |
| 461 | let options = SocialPublishOptions(imageURL: reviewed.publicImage?.absoluteString ?? "", |
| 462 | subreddit: reviewed.subreddit ?? "", flair: reviewed.flair ?? "", tiktok: reviewed.tiktok, |
| 463 | useR2: reviewed.r2 != nil) |
| 464 | let plan = try await prepare(draft, account: account, options: options) |
| 465 | guard plan.fingerprint == reviewed.fingerprint else { |
| 466 | throw WorkspaceError("The account or attachment changed. Open the review again.") |
| 467 | } |
| 468 | let lease = try existingLease ?? workspace.claimPublication() |
| 469 | defer { withExtendedLifetime(lease) {} } |
| 470 | try workspace.reload() |
| 471 | guard let current = workspace.records.first(where: { $0.id == draft.id && $0.kind == "draft" }), |
| 472 | current["updatedAt"] == plan.revision else { |
| 473 | throw WorkspaceError("The draft changed. Open the review again.") |
| 474 | } |
| 475 | let companionClaim = try await workspace.claimCompanionPublication(current) |
| 476 | var receipt: WorkspaceRecord |
| 477 | do { |
| 478 | receipt = try workspace.beginPublication(plan, automatic: automatic, fromAgent: fromAgent) |
| 479 | } catch { |
| 480 | if let companionClaim { await workspace.releaseCompanionClaim(companionClaim) } |
| 481 | throw error |
| 482 | } |
| 483 | var steps = receipt.fields["steps"] as? [[String: Any]] ?? [] |
| 484 | do { |
| 485 | let videoID: String? |
| 486 | if let video = plan.nativeVideo, [.x, .linkedin].contains(plan.platform), steps.isEmpty { |
| 487 | let uploader = PostVideoUpload(transport: transport) |
| 488 | if plan.platform == .x { |
| 489 | if let readyVideoID { |
| 490 | videoID = readyVideoID |
| 491 | } else { |
| 492 | videoID = try await uploader.toX(video, token: account.session.accessToken) |
| 493 | } |
| 494 | } else { |
| 495 | guard let owner = plan.linkedInAuthor else { throw WorkspaceError("Choose a LinkedIn destination.") } |
| 496 | videoID = try await uploader.toLinkedIn(video, thumbnail: plan.linkedInThumbnail, |
| 497 | owner: owner, token: account.session.accessToken) |
| 498 | } |
| 499 | if automatic { |
| 500 | try workspace.reload() |
| 501 | guard workspace.settings["autoPost"] as? Bool == true else { |
| 502 | throw WorkspaceError("Automatic posting was paused during the video upload.") |
| 503 | } |
| 504 | } |
| 505 | } else { |
| 506 | videoID = nil |
| 507 | } |
| 508 | switch plan.platform { |
| 509 | case .x: |
| 510 | for index in steps.count..<plan.posts.count { |
| 511 | let previous = index == 0 ? plan.replyID : steps[index - 1]["id"] as? String |
| 512 | var payload: [String: Any] = ["text": plan.posts[index]] |
| 513 | if let previous { payload["reply"] = ["in_reply_to_tweet_id": previous] } |
| 514 | if index == 0 { |
| 515 | if let videoID { |
| 516 | payload["media"] = ["media_ids": [videoID]] |
| 517 | } else if let image = plan.image { |
| 518 | let uploaded = try await uploadXImage(image, expectedHash: plan.imageHash, token: account.session.accessToken) |
| 519 | payload["media"] = ["media_ids": [uploaded]] |
| 520 | } |
| 521 | } |
| 522 | let (value, _) = try await transport.request(URL(string: "https://api.x.com/2/tweets")!, |
| 523 | token: account.session.accessToken, method: "POST", json: payload, publishes: true) |
| 524 | guard let id = (value["data"] as? [String: Any])?["id"] as? String, |
| 525 | id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil else { |
| 526 | throw SocialRequestError("X didn’t confirm a post ID. Check the account before retrying.", uncertain: true) |
| 527 | } |
| 528 | var step = ["id": id, "url": "https://x.com/i/web/status/" + id, "at": WorkspaceRecord.timestamp] |
| 529 | if index == 0, let videoID { step["videoId"] = videoID } |
| 530 | steps.append(step) |
| 531 | receipt.fields["steps"] = steps |
| 532 | try workspace.updatePublication(receipt) |
| 533 | } |
| 534 | case .linkedin: |
| 535 | guard let author = plan.linkedInAuthor else { throw WorkspaceError("Choose a LinkedIn destination.") } |
| 536 | var payload: [String: Any] = [ |
| 537 | "author": author, "commentary": plan.posts[0], "visibility": "PUBLIC", |
| 538 | "distribution": ["feedDistribution": "MAIN_FEED", "targetEntities": [String](), "thirdPartyDistributionChannels": [String]()], |
| 539 | "lifecycleState": "PUBLISHED", "isReshareDisabledByAuthor": false |
| 540 | ] |
| 541 | if let videoID { |
| 542 | payload["content"] = ["media": ["id": videoID]] |
| 543 | } else if let image = plan.image { |
| 544 | let imageID = try await uploadLinkedInImage(image, expectedHash: plan.imageHash, owner: author, |
| 545 | token: account.session.accessToken) |
| 546 | if automatic { |
| 547 | try workspace.reload() |
| 548 | guard workspace.settings["autoPost"] as? Bool == true else { |
| 549 | throw WorkspaceError("Automatic posting was paused during the image upload.") |
| 550 | } |
| 551 | } |
| 552 | payload["content"] = ["media": ["id": imageID]] |
| 553 | } |
| 554 | let (_, response) = try await transport.request(URL(string: "https://api.linkedin.com/rest/posts")!, |
| 555 | token: account.session.accessToken, method: "POST", json: payload, |
| 556 | headers: LinkedInPages.headers, publishes: true) |
| 557 | guard let id = response.value(forHTTPHeaderField: "x-restli-id"), |
| 558 | id.range(of: #"\Aurn:li:(share|ugcPost):[0-9]+\z"#, options: .regularExpression) != nil else { |
| 559 | throw SocialRequestError("LinkedIn didn’t confirm a post ID. Check the account before retrying.", uncertain: true) |
| 560 | } |
| 561 | var step = ["id": id, "url": "https://www.linkedin.com/feed/update/" + id + "/", "at": WorkspaceRecord.timestamp] |
| 562 | if let videoID { step["videoId"] = videoID } |
| 563 | if let thumbnail = plan.linkedInThumbnail { step["thumbnailHash"] = thumbnail.hash } |
| 564 | steps.append(step) |
| 565 | receipt.fields["steps"] = steps |
| 566 | case .instagram: |
| 567 | steps = [try await instagram(plan, account: account, receipt: &receipt)] |
| 568 | receipt.fields["steps"] = steps |
| 569 | case .reddit: |
| 570 | steps = [try await reddit(plan, account: account)] |
| 571 | receipt.fields["steps"] = steps |
| 572 | case .tiktok: |
| 573 | steps = [try await tiktok(plan, account: account, receipt: &receipt)] |
| 574 | receipt.fields["steps"] = steps |
| 575 | } |
| 576 | receipt["status"] = "published" |
| 577 | receipt["publishedAt"] = WorkspaceRecord.timestamp |
| 578 | try workspace.updatePublication(receipt) |
| 579 | return receipt |
| 580 | } catch { |
| 581 | let uncertain = (error as? SocialRequestError)?.uncertain ?? !(error is WorkspaceError) |
| 582 | receipt["status"] = uncertain ? "uncertain" : steps.isEmpty ? "failed" : "partial" |
| 583 | receipt["error"] = error.localizedDescription |
| 584 | try? workspace.updatePublication(receipt) |
| 585 | throw error |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | private func instagram(_ plan: SocialPublishPlan, account: ManagedSocialAccount, receipt: inout WorkspaceRecord) async throws -> [String: String] { |
| 590 | let base = URL(string: "https://graph.instagram.com/v25.0/")! |
| 591 | let token = account.session.accessToken |
| 592 | let accountURL = base.appending(path: account.id) |
| 593 | var container = receipt["containerId"] |
| 594 | if container.isEmpty { |
| 595 | var values = ["caption": plan.posts[0]] |
| 596 | if let video = plan.nativeVideo { |
| 597 | guard let config = plan.r2, let client = try r2Client(), client.profile.configuration == config else { |
| 598 | throw WorkspaceError("The Instagram media bucket changed. Review the Reel again.") |
| 599 | } |
| 600 | let media = try await client.upload(video.url, expectedHash: video.hash) |
| 601 | try workspace.saveR2Media(media, config: config) |
| 602 | values["video_url"] = try client.link(media.key).absoluteString |
| 603 | values["media_type"] = "REELS" |
| 604 | if let cover = plan.instagramCover, let hash = plan.instagramCoverHash { |
| 605 | let art = try await client.uploadInstagram(cover, hash: hash) |
| 606 | try workspace.saveR2Media(art, config: config) |
| 607 | values["cover_url"] = try client.link(art.key).absoluteString |
| 608 | } |
| 609 | } else if let config = plan.r2 { |
| 610 | guard let client = try r2Client(), client.profile.configuration == config, |
| 611 | let local = plan.image, let hash = plan.imageHash else { |
| 612 | throw WorkspaceError("The R2 connection or image changed. Review the post again.") |
| 613 | } |
| 614 | let media = try await client.uploadInstagram(local, hash: hash) |
| 615 | try workspace.saveR2Media(media, config: config) |
| 616 | values["image_url"] = try client.link(media.key).absoluteString |
| 617 | } else if let url = plan.publicImage { |
| 618 | values["image_url"] = url.absoluteString |
| 619 | } else { |
| 620 | throw WorkspaceError("Enter an Instagram image URL.") |
| 621 | } |
| 622 | let (value, _) = try await transport.form(accountURL.appending(path: "media"), token: token, values: values) |
| 623 | guard let id = value["id"] as? String, validNumericID(id) else { |
| 624 | throw WorkspaceError("Instagram didn’t return a media container.") |
| 625 | } |
| 626 | container = id |
| 627 | receipt["containerId"] = id |
| 628 | receipt.fields["containers"] = [id] |
| 629 | try workspace.updatePublication(receipt) |
| 630 | } |
| 631 | guard validNumericID(container) else { throw WorkspaceError("The saved Instagram container is invalid.") } |
| 632 | let statusURL = base.appending(path: container).appending(queryItems: [URLQueryItem(name: "fields", value: "status_code")]) |
| 633 | var ready = false |
| 634 | for attempt in 0..<30 { |
| 635 | let (value, _) = try await transport.request(statusURL, token: token) |
| 636 | switch value["status_code"] as? String { |
| 637 | case "FINISHED": ready = true |
| 638 | case "PUBLISHED": |
| 639 | throw SocialRequestError("Instagram reports this container already went out. Check the account.", uncertain: true) |
| 640 | case "ERROR", "EXPIRED": |
| 641 | receipt["containerId"] = "" |
| 642 | receipt.fields["containers"] = [String]() |
| 643 | throw WorkspaceError(plan.nativeVideo == nil ? "Instagram couldn’t process this image. Check the public JPEG URL." |
| 644 | : "Instagram couldn’t process the Reel. Check the MP4 and R2 media hosting.") |
| 645 | default: |
| 646 | if attempt < 29 { try await Task.sleep(for: .seconds(2)) } |
| 647 | } |
| 648 | if ready { break } |
| 649 | } |
| 650 | guard ready else { throw WorkspaceError("Instagram is still processing the media. Review and try again later.") } |
| 651 | let (value, _) = try await transport.form(accountURL.appending(path: "media_publish"), token: token, |
| 652 | values: ["creation_id": container], publishes: true) |
| 653 | guard let id = value["id"] as? String, validNumericID(id) else { |
| 654 | throw SocialRequestError("Instagram didn’t confirm a published post ID. Check the account.", uncertain: true) |
| 655 | } |
| 656 | var step = ["id": id, "url": "", "at": WorkspaceRecord.timestamp] |
| 657 | receipt.fields["steps"] = [step] |
| 658 | try workspace.updatePublication(receipt) |
| 659 | let permalinkURL = base.appending(path: id).appending(queryItems: [URLQueryItem(name: "fields", value: "permalink")]) |
| 660 | if let (details, _) = try? await transport.request(permalinkURL, token: token), |
| 661 | let raw = details["permalink"] as? String, let url = URL(string: raw), url.scheme == "https", |
| 662 | ["instagram.com", "www.instagram.com"].contains(url.host ?? ""), url.user == nil, url.password == nil { |
| 663 | step["url"] = url.absoluteString |
| 664 | } |
| 665 | return step |
| 666 | } |
| 667 | |
| 668 | private func reddit(_ plan: SocialPublishPlan, account: ManagedSocialAccount) async throws -> [String: String] { |
| 669 | guard let subreddit = plan.subreddit else { throw WorkspaceError("Choose a subreddit.") } |
| 670 | var values = ["api_type": "json", "kind": "self", "sr": subreddit, "title": plan.title, |
| 671 | "text": plan.posts[0], "resubmit": "false"] |
| 672 | if let flair = plan.flair { values["flair_id"] = flair } |
| 673 | if let image = plan.image { |
| 674 | values["url"] = try await redditUpload(image, hash: plan.imageHash, account: account).absoluteString |
| 675 | values["kind"] = "image" |
| 676 | values["validate_on_submit"] = "true" |
| 677 | } |
| 678 | let (value, _) = try await transport.form(URL(string: "https://oauth.reddit.com/api/submit")!, |
| 679 | token: account.session.accessToken, values: values, |
| 680 | headers: Self.redditHeaders, publishes: true) |
| 681 | let result = value["json"] as? [String: Any] ?? [:] |
| 682 | if let errors = result["errors"] as? [Any], !errors.isEmpty { |
| 683 | throw WorkspaceError("Reddit rejected the submission. Check the subreddit’s rules, flair, and posting limits.") |
| 684 | } |
| 685 | let data = result["data"] as? [String: Any] ?? [:] |
| 686 | if let url = data["url"] as? String { |
| 687 | let step = try redditReceipt(url) |
| 688 | guard step["id"] == data["name"] as? String else { |
| 689 | throw SocialRequestError("Reddit returned conflicting post details. Check the account.", uncertain: true) |
| 690 | } |
| 691 | return step |
| 692 | } |
| 693 | if plan.image != nil, let address = data["websocket_url"] as? String { |
| 694 | return try await redditImageReceipt(address) |
| 695 | } |
| 696 | throw SocialRequestError("Reddit didn’t confirm a submission. Check the subreddit.", uncertain: true) |
| 697 | } |
| 698 | |
| 699 | private static let redditHeaders = ["User-Agent": "desktop:com.protomota.inkspring:v1.0 (Inkspring; https://inkspring.ai)"] |
| 700 | |
| 701 | private func redditUpload(_ url: URL, hash: String?, account: ManagedSocialAccount) async throws -> URL { |
| 702 | let (data, type) = try imageBytes(url, expectedHash: hash, limit: 20_000_000) |
| 703 | let name = type == "image/png" ? "image.png" : "image.jpg" |
| 704 | let (value, _) = try await transport.form(URL(string: "https://oauth.reddit.com/api/media/asset.json")!, |
| 705 | token: account.session.accessToken, |
| 706 | values: ["filepath": name, "mimetype": type], headers: Self.redditHeaders) |
| 707 | let lease = value["args"] as? [String: Any] ?? [:] |
| 708 | guard let raw = lease["action"] as? String, let upload = URL(string: raw.hasPrefix("//") ? "https:" + raw : raw), |
| 709 | upload.scheme == "https", upload.user == nil, upload.password == nil, upload.port == nil, |
| 710 | let host = upload.host, host.range(of: #"\Areddit-uploaded-media\.s3(?:[.-][a-z0-9-]+)?\.amazonaws\.com\z"#, |
| 711 | options: .regularExpression) != nil, |
| 712 | let fields = lease["fields"] as? [[String: String]], fields.count <= 30 else { |
| 713 | throw WorkspaceError("Reddit returned an unsupported image upload destination.") |
| 714 | } |
| 715 | let boundary = "Inkspring" + UUID().uuidString |
| 716 | var form = Data() |
| 717 | var key: String? |
| 718 | for field in fields { |
| 719 | guard let name = field["name"], let value = field["value"], name != "file", |
| 720 | name.range(of: #"\A[A-Za-z0-9_.-]{1,80}\z"#, options: .regularExpression) != nil else { |
| 721 | throw WorkspaceError("Reddit returned an invalid upload form.") |
| 722 | } |
| 723 | if name == "key" { key = value } |
| 724 | form.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8)) |
| 725 | } |
| 726 | guard let key, key.range(of: #"\A[A-Za-z0-9_./-]+\z"#, options: .regularExpression) != nil, |
| 727 | !key.split(separator: "/").contains("..") else { |
| 728 | throw WorkspaceError("Reddit didn’t return a valid media key.") |
| 729 | } |
| 730 | form.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\(name)\"\r\nContent-Type: \(type)\r\n\r\n".utf8)) |
| 731 | form.append(data) |
| 732 | form.append(Data("\r\n--\(boundary)--\r\n".utf8)) |
| 733 | _ = try await transport.request(upload, method: "POST", body: form, |
| 734 | headers: ["Content-Type": "multipart/form-data; boundary=" + boundary], expectsJSON: false) |
| 735 | return URL(string: "https://" + host + "/")!.appending(path: key) |
| 736 | } |
| 737 | |
| 738 | private func redditImageReceipt(_ address: String) async throws -> [String: String] { |
| 739 | guard let url = URL(string: address), url.scheme == "wss", url.host?.hasSuffix(".wss.redditmedia.com") == true, |
| 740 | url.user == nil, url.password == nil, url.port == nil || url.port == 443 else { |
| 741 | throw SocialRequestError("Reddit returned an unexpected confirmation address.", uncertain: true) |
| 742 | } |
| 743 | let config = URLSessionConfiguration.ephemeral |
| 744 | config.timeoutIntervalForResource = 45 |
| 745 | let session = URLSession(configuration: config, delegate: NoHTTPRedirects(), delegateQueue: nil) |
| 746 | let socket = session.webSocketTask(with: url) |
| 747 | socket.maximumMessageSize = 100_000 |
| 748 | socket.resume() |
| 749 | let timeout = Task { |
| 750 | try? await Task.sleep(for: .seconds(45)) |
| 751 | if !Task.isCancelled { socket.cancel(with: .goingAway, reason: nil) } |
| 752 | } |
| 753 | defer { timeout.cancel(); socket.cancel(); session.invalidateAndCancel() } |
| 754 | while true { |
| 755 | guard let message = try? await socket.receive(), case let .string(json) = message, |
| 756 | let value = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any] else { |
| 757 | throw SocialRequestError("Reddit hasn’t confirmed the image post. Check the account.", uncertain: true) |
| 758 | } |
| 759 | if value["type"] as? String == "failed" { throw WorkspaceError("Reddit couldn’t process this image post.") } |
| 760 | if let redirect = (value["payload"] as? [String: Any])?["redirect"] as? String { return try redditReceipt(redirect) } |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | private func redditReceipt(_ text: String) throws -> [String: String] { |
| 765 | guard let url = URL(string: text), url.scheme == "https", ["reddit.com", "www.reddit.com"].contains(url.host ?? ""), |
| 766 | url.user == nil, url.password == nil, url.port == nil, |
| 767 | let match = url.path.range(of: #"/comments/[a-z0-9]+(?:/|\z)"#, options: .regularExpression), |
| 768 | let id = url.path[match].split(separator: "/").last else { |
| 769 | throw SocialRequestError("Reddit didn’t confirm a valid post address. Check the account.", uncertain: true) |
| 770 | } |
| 771 | return ["id": "t3_" + id, "url": url.absoluteString, "at": WorkspaceRecord.timestamp] |
| 772 | } |
| 773 | |
| 774 | private func validNumericID(_ id: String) -> Bool { |
| 775 | id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil |
| 776 | } |
| 777 | |
| 778 | private func imageBytes(_ url: URL, expectedHash: String?, limit: Int) throws -> (Data, String) { |
| 779 | let resource = try url.resourceValues(forKeys: [.fileSizeKey, .isSymbolicLinkKey, .isRegularFileKey]) |
| 780 | guard resource.isRegularFile == true, resource.isSymbolicLink != true, (1...limit).contains(resource.fileSize ?? 0) else { |
| 781 | throw WorkspaceError("Choose a PNG or JPEG within the platform’s file size limit.") |
| 782 | } |
| 783 | let data = try Data(contentsOf: url) |
| 784 | guard data.count <= limit, SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == expectedHash else { |
| 785 | throw WorkspaceError("The image changed. Review the attachment again.") |
| 786 | } |
| 787 | if data.starts(with: [0x89, 0x50, 0x4e, 0x47]) { return (data, "image/png") } |
| 788 | if data.starts(with: [0xff, 0xd8]) { return (data, "image/jpeg") } |
| 789 | throw WorkspaceError("Choose a PNG or JPEG image.") |
| 790 | } |
| 791 | |
| 792 | private func uploadXImage(_ url: URL, expectedHash: String?, token: String) async throws -> String { |
| 793 | let (input, type) = try imageBytes(url, expectedHash: expectedHash, limit: 5_000_000) |
| 794 | let boundary = "Inkspring" + UUID().uuidString |
| 795 | var multipart = Data() |
| 796 | for (key, value) in [("media_category", "tweet_image"), ("media_type", type)] { |
| 797 | multipart.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)\r\n".utf8)) |
| 798 | } |
| 799 | multipart.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"media\"; filename=\"attachment\"\r\nContent-Type: \(type)\r\n\r\n".utf8)) |
| 800 | multipart.append(input) |
| 801 | multipart.append(Data("\r\n--\(boundary)--\r\n".utf8)) |
| 802 | let (value, _) = try await transport.request(URL(string: "https://api.x.com/2/media/upload")!, |
| 803 | token: token, method: "POST", body: multipart, |
| 804 | headers: ["Content-Type": "multipart/form-data; boundary=" + boundary]) |
| 805 | guard let id = (value["data"] as? [String: Any])?["id"] as? String ?? value["media_id_string"] as? String, |
| 806 | id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil else { |
| 807 | throw WorkspaceError("X didn’t return an uploaded image ID.") |
| 808 | } |
| 809 | return id |
| 810 | } |
| 811 | |
| 812 | private func uploadLinkedInImage(_ file: URL, expectedHash: String?, owner: String, token: String) async throws -> String { |
| 813 | let (bytes, type) = try imageBytes(file, expectedHash: expectedHash, limit: 20_000_000) |
| 814 | let endpoint = URL(string: "https://api.linkedin.com/rest/images?action=initializeUpload")! |
| 815 | let (document, _) = try await transport.request(endpoint, token: token, method: "POST", |
| 816 | json: ["initializeUploadRequest": ["owner": owner]], headers: LinkedInPages.headers) |
| 817 | guard let value = document["value"] as? [String: Any], let id = value["image"] as? String, |
| 818 | id.range(of: #"\Aurn:li:image:[A-Za-z0-9_-]{1,200}\z"#, options: .regularExpression) != nil, |
| 819 | let address = value["uploadUrl"] as? String, let url = URL(string: address), |
| 820 | url.scheme == "https", url.user == nil, url.password == nil, url.port == nil, |
| 821 | url.host == "www.linkedin.com", url.path.hasPrefix("/dms-uploads/") else { |
| 822 | throw WorkspaceError("LinkedIn didn’t return valid image upload instructions.") |
| 823 | } |
| 824 | _ = try await transport.request(url, token: token, method: "PUT", body: bytes, |
| 825 | headers: ["Content-Type": type], expectsJSON: false, timeout: 120) |
| 826 | return id |
| 827 | } |
| 828 | } |