Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / PostVideoTests.swift
| 1 | import Foundation |
| 2 | import InkspringSchedule |
| 3 | import Testing |
| 4 | @testable import Inkspring |
| 5 | |
| 6 | @Test(arguments: [SocialPlatform.x, .linkedin], [true, false]) |
| 7 | @MainActor func scheduledVideoPostsRequireAProcessedAttachment(platform: SocialPlatform, succeeds: Bool) async throws { |
| 8 | let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 9 | defer { try? FileManager.default.removeItem(at: root) } |
| 10 | let workspace = Workspace(directory: root) |
| 11 | let file = root.appending(path: "fixture.mp4") |
| 12 | let bytes = Data((0..<16).map(UInt8.init)) |
| 13 | try bytes.write(to: file) |
| 14 | var media = WorkspaceRecord.new("local-video") |
| 15 | media["name"] = file.lastPathComponent |
| 16 | media["path"] = file.path |
| 17 | media["hash"] = try fileDigest(file).hash |
| 18 | media["type"] = "video/mp4" |
| 19 | media.fields["size"] = bytes.count |
| 20 | media.fields["duration"] = 98.3 |
| 21 | media = try workspace.save(media) |
| 22 | let account = ManagedSocialAccount( |
| 23 | session: ManagedSocialSession(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 24 | expiresAt: 2_000_000_000_000, scopes: "tweet.write media.write w_member_social"), |
| 25 | id: "test", name: "Fixture", username: "fixture") |
| 26 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 27 | draft["platform"] = platform.rawValue |
| 28 | draft["format"] = platform == .x ? "thread" : "post" |
| 29 | draft["content"] = "Here is the video." |
| 30 | if platform == .x { |
| 31 | var article = WorkspaceRecord.new("article", projectID: workspace.projectID) |
| 32 | article["title"] = "Fixture article" |
| 33 | article["body"] = "The full story." |
| 34 | article = try workspace.save(article) |
| 35 | let reference = try #require(article.referenceID) |
| 36 | draft["content"] = ["Here is the video.", XReplyArticle.attach(reference, to: "A follow-up.")] |
| 37 | .joined(separator: XThreadText.separator) |
| 38 | draft.fields["videoThumbnail"] = ["file": "legacy-x-cover.png"] |
| 39 | } else { |
| 40 | draft["content"] += "\n\nhttps://newsletter.example.com/p/fixture" |
| 41 | } |
| 42 | draft.setDraftMedia(["id": media.id], as: .video) |
| 43 | if platform == .linkedin { |
| 44 | let image = root.appending(path: "thumbnail.png") |
| 45 | let png = try #require(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR1sAAAAASUVORK5CYII=")) |
| 46 | try png.write(to: image) |
| 47 | draft.fields["videoThumbnail"] = try workspace.attachImage(image) |
| 48 | } |
| 49 | draft = try workspace.save(draft) |
| 50 | if platform == .x { |
| 51 | #expect(workspace.videoThumbnailURL(draft) == nil) |
| 52 | } |
| 53 | let slot = PostScheduling.fiveMinutesFromNow() |
| 54 | draft = try workspace.scheduleDraft(draft, at: slot, linkedInAccount: account, customTime: true) |
| 55 | try workspace.set("autoPost", to: true) |
| 56 | |
| 57 | var chunks: [Data] = [] |
| 58 | var posts = 0 |
| 59 | var articleRequests = 0 |
| 60 | var statusChecked = false |
| 61 | var thumbnailUploaded = false |
| 62 | var thumbnailConfirmed = false |
| 63 | let videoURN = "urn:li:video:fixture" |
| 64 | let owner = "urn:li:person:test" |
| 65 | let transport = SocialTransport { request in |
| 66 | let url = try #require(request.url) |
| 67 | let method = try #require(request.httpMethod) |
| 68 | let json = request.httpBody.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } |
| 69 | var payload: [String: Any] = [:] |
| 70 | var headers: [String: String] = [:] |
| 71 | switch (url.path, method, url.query()) { |
| 72 | case ("/2/media/upload/initialize", "POST", _): |
| 73 | #expect(json?["total_bytes"] as? Int == bytes.count) |
| 74 | #expect(json?["media_category"] as? String == "tweet_video") |
| 75 | payload = ["data": ["id": "123"]] |
| 76 | case ("/2/media/upload/123/append", "POST", _): |
| 77 | #expect(json?["segment_index"] as? Int == 0) |
| 78 | let encoded = try #require(json?["media"] as? String) |
| 79 | chunks.append(try #require(Data(base64Encoded: encoded))) |
| 80 | case ("/2/media/upload/123/finalize", "POST", _): |
| 81 | #expect(chunks == [bytes]) |
| 82 | payload = ["data": ["id": "123", "processing_info": ["state": "pending", "check_after_secs": 1]]] |
| 83 | case ("/2/media/upload", "GET", "media_id=123"): |
| 84 | statusChecked = true |
| 85 | payload = ["data": ["id": "123", "processing_info": ["state": succeeds ? "succeeded" : "failed"]]] |
| 86 | case ("/2/articles/draft", "POST", _): |
| 87 | #expect(succeeds && statusChecked) |
| 88 | articleRequests += 1 |
| 89 | payload = ["data": ["id": "321"]] |
| 90 | case ("/2/articles/321/publish", "POST", _): |
| 91 | #expect(succeeds && statusChecked) |
| 92 | articleRequests += 1 |
| 93 | payload = ["data": ["post_id": "789"]] |
| 94 | case ("/rest/videos", "POST", "action=initializeUpload"): |
| 95 | let initRequest = try #require(json?["initializeUploadRequest"] as? [String: Any]) |
| 96 | #expect(initRequest["owner"] as? String == owner) |
| 97 | #expect(initRequest["fileSizeBytes"] as? Int == bytes.count) |
| 98 | #expect(initRequest["uploadThumbnail"] as? Bool == true) |
| 99 | payload = ["value": ["video": videoURN, "uploadToken": "", "uploadInstructions": [ |
| 100 | ["firstByte": 0, "lastByte": 7, "uploadUrl": "https://www.linkedin.com/dms-uploads/one"], |
| 101 | ["firstByte": 8, "lastByte": 31, "uploadUrl": "https://www.linkedin.com/dms-uploads/two"] |
| 102 | ], "thumbnailUploadUrl": "https://www.linkedin.com/dms-uploads/fixture-thumbnail"]] |
| 103 | case ("/dms-uploads/fixture-thumbnail", "PUT", _): |
| 104 | #expect(request.value(forHTTPHeaderField: "Authorization") == nil) |
| 105 | #expect(request.value(forHTTPHeaderField: "media-type-family") == "STILLIMAGE") |
| 106 | #expect(request.httpBody?.starts(with: [0xFF, 0xD8]) == true) |
| 107 | thumbnailUploaded = true |
| 108 | case ("/dms-uploads/one", "PUT", _), ("/dms-uploads/two", "PUT", _): |
| 109 | #expect(request.value(forHTTPHeaderField: "Authorization") == nil) |
| 110 | chunks.append(try #require(request.httpBody)) |
| 111 | headers["ETag"] = "\"part-\(chunks.count)\"" |
| 112 | case ("/rest/videos", "POST", "action=finalizeUpload"): |
| 113 | #expect(thumbnailUploaded) |
| 114 | #expect(chunks.reduce(into: Data()) { $0.append($1) } == bytes) |
| 115 | let finalize = try #require(json?["finalizeUploadRequest"] as? [String: Any]) |
| 116 | #expect(finalize["uploadedPartIds"] as? [String] == ["part-1", "part-2"]) |
| 117 | case ("/rest/videos/urn:li:video:fixture", "GET", _): |
| 118 | let wasChecked = statusChecked |
| 119 | statusChecked = true |
| 120 | payload = ["id": videoURN, "owner": owner, "status": succeeds ? "AVAILABLE" : "PROCESSING_FAILED"] |
| 121 | if succeeds, wasChecked { |
| 122 | payload["thumbnail"] = "https://media.licdn.com/fixture/customthumbnail" |
| 123 | thumbnailConfirmed = true |
| 124 | } |
| 125 | case ("/2/tweets", "POST", _): |
| 126 | #expect(succeeds && statusChecked) |
| 127 | if posts == 0 { |
| 128 | let media = json?["media"] as? [String: [String]] |
| 129 | #expect(media?["media_ids"] == ["123"]) |
| 130 | } else { |
| 131 | #expect(json?["media"] == nil) |
| 132 | #expect((json?["reply"] as? [String: String])?["in_reply_to_tweet_id"] == "456") |
| 133 | #expect((json?["text"] as? String)?.hasSuffix("https://x.com/i/web/status/789") == true) |
| 134 | } |
| 135 | posts += 1 |
| 136 | payload = ["data": ["id": posts == 1 ? "456" : "457"]] |
| 137 | case ("/rest/posts", "POST", _): |
| 138 | #expect(succeeds && statusChecked && thumbnailUploaded && thumbnailConfirmed) |
| 139 | let content = json?["content"] as? [String: [String: String]] |
| 140 | #expect(content?["media"]?["id"] == videoURN) |
| 141 | #expect(content?["article"] == nil) |
| 142 | #expect(json?["commentary"] as? String == "Here is the video.\n\nhttps://newsletter.example.com/p/fixture") |
| 143 | posts += 1 |
| 144 | headers["x-restli-id"] = "urn:li:share:456" |
| 145 | default: throw WorkspaceError("Unexpected video fixture request.") |
| 146 | } |
| 147 | return (try JSONSerialization.data(withJSONObject: payload), |
| 148 | try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headers))) |
| 149 | } |
| 150 | let publisher = SocialPublisher(workspace: workspace, transport: transport, authorize: { _ in account }) |
| 151 | await workspace.runDuePosts(publisher: publisher, now: slot.addingTimeInterval(-1)) |
| 152 | #expect(chunks.isEmpty) |
| 153 | await workspace.runDuePosts(publisher: publisher, now: slot) |
| 154 | await workspace.runDuePosts(publisher: publisher, now: slot.addingTimeInterval(10)) |
| 155 | #expect(statusChecked) |
| 156 | #expect(workspace.drafts.first { $0.id == draft.id }?.scheduleStatus == (succeeds ? "posted" : "failed")) |
| 157 | let receipt = workspace.records.first { $0.kind == "publication" && $0["draftId"] == draft.id } |
| 158 | if succeeds { |
| 159 | #expect(posts == (platform == .x ? 2 : 1)) |
| 160 | #expect(articleRequests == (platform == .x ? 2 : 0)) |
| 161 | #expect(receipt?["status"] == "published") |
| 162 | let steps = receipt?.fields["steps"] as? [[String: String]] |
| 163 | #expect(steps?.first?["videoId"] == (platform == .x ? "123" : videoURN)) |
| 164 | } else { |
| 165 | #expect(posts == 0) |
| 166 | #expect(articleRequests == 0) |
| 167 | #expect(receipt?["status"] == (platform == .x ? nil : "failed")) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | @Test(arguments: [true, false]) |
| 172 | @MainActor func instagramReelWaitsForTheUploadedVideo(succeeds: Bool) async throws { |
| 173 | let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 174 | defer { try? FileManager.default.removeItem(at: root) } |
| 175 | let workspace = Workspace(directory: root) |
| 176 | let file = root.appending(path: "reel.mp4") |
| 177 | let bytes = Data("video fixture".utf8) |
| 178 | try bytes.write(to: file) |
| 179 | var video = WorkspaceRecord.new("local-video") |
| 180 | video["name"] = file.lastPathComponent |
| 181 | video["path"] = file.path |
| 182 | video["hash"] = try fileDigest(file).hash |
| 183 | video["type"] = "video/mp4" |
| 184 | video.fields["size"] = bytes.count |
| 185 | video.fields["duration"] = 98.3 |
| 186 | video = try workspace.save(video) |
| 187 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 188 | draft["platform"] = "instagram" |
| 189 | draft["format"] = "video" |
| 190 | draft["content"] = "Here is the Reel." |
| 191 | draft.setDraftMedia(["id": video.id], as: .video) |
| 192 | draft = try workspace.save(draft) |
| 193 | |
| 194 | let account = ManagedSocialAccount( |
| 195 | session: .init(accessToken: "fixture", refreshToken: nil, managedTicket: nil, expiresAt: 2_000_000_000_000, scopes: nil), |
| 196 | id: "123", name: "Fixture", username: "fixture") |
| 197 | let profile = R2Profile(configuration: .init(accountId: String(repeating: "a", count: 32), bucket: "media-fixture", jurisdiction: ""), |
| 198 | accessKeyId: "TESTKEY", secretAccessKey: "SYNTHETIC") |
| 199 | var uploaded = false |
| 200 | var published = false |
| 201 | let r2 = R2Client(profile: profile) { request, input in |
| 202 | let file = try #require(input) |
| 203 | let url = try #require(request.url) |
| 204 | #expect(request.httpMethod == "PUT") |
| 205 | #expect(request.value(forHTTPHeaderField: "Content-Type") == "video/mp4") |
| 206 | #expect(try Data(contentsOf: file) == bytes) |
| 207 | uploaded = true |
| 208 | return (Data(), try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil))) |
| 209 | } |
| 210 | let transport = SocialTransport { request in |
| 211 | let url = try #require(request.url) |
| 212 | let result: [String: Any] |
| 213 | switch url.path { |
| 214 | case "/v25.0/123/media": |
| 215 | #expect(uploaded) |
| 216 | let form = String(decoding: try #require(request.httpBody), as: UTF8.self).removingPercentEncoding |
| 217 | #expect(form?.contains("media_type=REELS") == true) |
| 218 | #expect(form?.contains("video_url=https://") == true) |
| 219 | #expect(form?.contains("image_url=") == false) |
| 220 | result = ["id": "456"] |
| 221 | case "/v25.0/456": |
| 222 | result = ["status_code": succeeds ? "FINISHED" : "ERROR"] |
| 223 | case "/v25.0/123/media_publish": |
| 224 | #expect(succeeds) |
| 225 | published = true |
| 226 | result = ["id": "789"] |
| 227 | case "/v25.0/789": |
| 228 | result = ["permalink": "https://www.instagram.com/reel/test/"] |
| 229 | default: |
| 230 | throw WorkspaceError("Unexpected Instagram request.") |
| 231 | } |
| 232 | return (try JSONSerialization.data(withJSONObject: result), |
| 233 | try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil))) |
| 234 | } |
| 235 | let publisher = SocialPublisher(workspace: workspace, transport: transport, authorize: { _ in account }, r2Client: { r2 }) |
| 236 | let plan = try await publisher.review(draft) |
| 237 | if succeeds { |
| 238 | let receipt = try await publisher.publish(plan) |
| 239 | #expect(receipt["status"] == "published") |
| 240 | } else { |
| 241 | await #expect(throws: WorkspaceError.self) { _ = try await publisher.publish(plan) } |
| 242 | } |
| 243 | #expect(published == succeeds) |
| 244 | } |