Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / PostVideo.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import UniformTypeIdentifiers |
| 5 | |
| 6 | extension WorkspaceRecord { |
| 7 | var needsNativePostVideo: Bool { |
| 8 | ["x", "linkedin", "instagram"].contains(self["platform"]) && (fields["video"] != nil || self["format"] == "video") |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | struct PostVideo: Equatable { |
| 13 | let url: URL |
| 14 | let name: String |
| 15 | let size: Int64 |
| 16 | let hash: String |
| 17 | |
| 18 | static func forDraft(_ draft: WorkspaceRecord, in records: [WorkspaceRecord]) throws -> Self? { |
| 19 | guard draft.needsNativePostVideo else { return nil } |
| 20 | let attachment = draft.fields["video"] as? [String: Any] |
| 21 | guard let id = attachment?["id"] as? String, |
| 22 | let file = records.first(where: { $0.kind == "local-video" && $0.id == id }), |
| 23 | !file["path"].isEmpty else { |
| 24 | throw WorkspaceError("Attach the video file before scheduling or publishing this post.") |
| 25 | } |
| 26 | let url = URL(fileURLWithPath: file["path"]) |
| 27 | let values = try? url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .isSymbolicLinkKey]) |
| 28 | guard let size = file.fields["size"] as? Int, size > 0, values?.fileSize == size, |
| 29 | values?.isRegularFile == true, values?.isSymbolicLink != true, |
| 30 | file["hash"].range(of: #"\A[a-f0-9]{64}\z"#, options: .regularExpression) != nil else { |
| 31 | throw WorkspaceError("The attached video is missing or has changed. Attach it again before publishing.") |
| 32 | } |
| 33 | guard file["type"] == "video/mp4", url.pathExtension.lowercased() == "mp4" else { |
| 34 | throw WorkspaceError("Attach an H.264 MP4.") |
| 35 | } |
| 36 | if draft["platform"] == "x" { |
| 37 | guard let duration = file.fields["duration"] as? Double, duration <= 140, size <= 512_000_000 else { |
| 38 | throw WorkspaceError("Choose an X video up to 2 minutes 20 seconds and 512 MB.") |
| 39 | } |
| 40 | } |
| 41 | if draft["platform"] == "instagram" { |
| 42 | guard let duration = file.fields["duration"] as? Double, (3...600).contains(duration), size <= 1_000_000_000 else { |
| 43 | throw WorkspaceError("Choose an Instagram Reel from 3 seconds to 10 minutes and up to 1 GB.") |
| 44 | } |
| 45 | } |
| 46 | return Self(url: url, name: file["name"], size: Int64(size), hash: file["hash"]) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | struct LinkedInVideoThumbnail { |
| 51 | let url: URL |
| 52 | let hash: String |
| 53 | let jpeg: Data |
| 54 | |
| 55 | init(url: URL) throws { |
| 56 | let attributes = try? url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .isSymbolicLinkKey]) |
| 57 | guard attributes?.isRegularFile == true, attributes?.isSymbolicLink != true, |
| 58 | (1...30_000_000).contains(attributes?.fileSize ?? 0), |
| 59 | let original = try? Data(contentsOf: url), (1...30_000_000).contains(original.count), |
| 60 | let source = CGImageSourceCreateWithData(original as CFData, nil), |
| 61 | let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ |
| 62 | kCGImageSourceCreateThumbnailFromImageAlways: true, |
| 63 | kCGImageSourceCreateThumbnailWithTransform: true, |
| 64 | kCGImageSourceThumbnailMaxPixelSize: 1920 |
| 65 | ] as CFDictionary) else { |
| 66 | throw WorkspaceError("The LinkedIn video thumbnail couldn’t be read. Attach it again before publishing.") |
| 67 | } |
| 68 | let output = NSMutableData() |
| 69 | guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { |
| 70 | throw WorkspaceError("Couldn’t prepare the LinkedIn video thumbnail.") |
| 71 | } |
| 72 | CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.9] as CFDictionary) |
| 73 | guard CGImageDestinationFinalize(destination) else { |
| 74 | throw WorkspaceError("Couldn’t prepare the LinkedIn video thumbnail.") |
| 75 | } |
| 76 | self.url = url |
| 77 | hash = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined() |
| 78 | jpeg = output as Data |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | @MainActor |
| 83 | struct PostVideoUpload { |
| 84 | let transport: SocialTransport |
| 85 | |
| 86 | func toX(_ video: PostVideo, token: String) async throws -> String { |
| 87 | let base = URL(string: "https://api.x.com/2/media/upload")! |
| 88 | let (value, _) = try await transport.request(base.appending(path: "initialize"), token: token, method: "POST", |
| 89 | json: ["total_bytes": video.size, "media_type": "video/mp4", "media_category": "tweet_video"]) |
| 90 | guard let id = (value["data"] as? [String: Any])?["id"] as? String, |
| 91 | id.range(of: #"\A[0-9]{1,19}\z"#, options: .regularExpression) != nil else { |
| 92 | throw WorkspaceError("X didn’t confirm a video upload ID.") |
| 93 | } |
| 94 | let reader = try VideoReader(video) |
| 95 | let upload = base.appending(path: id) |
| 96 | let chunkSize: Int64 = 3 * 1024 * 1024 |
| 97 | for (index, offset) in stride(from: 0, to: video.size, by: Int(chunkSize)).enumerated() { |
| 98 | try Task.checkCancellation() |
| 99 | let bytes = try reader.read(Int(min(chunkSize, video.size - offset))) |
| 100 | let (acknowledgment, _) = try await transport.request(upload.appending(path: "append"), token: token, method: "POST", |
| 101 | json: ["segment_index": index, "media": bytes.base64EncodedString()], timeout: 120) |
| 102 | guard (acknowledgment["errors"] as? [Any])?.isEmpty != false else { |
| 103 | throw WorkspaceError("X rejected part of the video upload.") |
| 104 | } |
| 105 | } |
| 106 | try reader.verify() |
| 107 | let (finalized, _) = try await transport.request(upload.appending(path: "finalize"), token: token, method: "POST") |
| 108 | let statusURL = base.appending(queryItems: [URLQueryItem(name: "media_id", value: id)]) |
| 109 | var data = finalized["data"] as? [String: Any] |
| 110 | let deadline = Date.now.addingTimeInterval(240) |
| 111 | repeat { |
| 112 | guard data?["id"] as? String == id else { throw WorkspaceError("X couldn’t confirm the uploaded video.") } |
| 113 | let processing = data?["processing_info"] as? [String: Any] |
| 114 | switch processing?["state"] as? String { |
| 115 | case "succeeded": return id |
| 116 | case "failed": throw WorkspaceError("X rejected the video during processing.") |
| 117 | case nil where (data?["video"] as? [String: Any])?["video_type"] as? String == "video/mp4": return id |
| 118 | default: break |
| 119 | } |
| 120 | let delay = min(60, max(1, processing?["check_after_secs"] as? Int ?? 2)) |
| 121 | try await Task.sleep(for: .seconds(delay)) |
| 122 | let (status, _) = try await transport.request(statusURL, token: token) |
| 123 | data = status["data"] as? [String: Any] |
| 124 | } while Date.now < deadline |
| 125 | throw WorkspaceError("X is still processing the video. Review the post and try again.") |
| 126 | } |
| 127 | |
| 128 | func toLinkedIn(_ video: PostVideo, thumbnail: LinkedInVideoThumbnail?, owner: String, token: String) async throws -> String { |
| 129 | let base = URL(string: "https://api.linkedin.com/rest/videos")! |
| 130 | let headers = LinkedInPages.headers |
| 131 | let initialize = base.appending(queryItems: [URLQueryItem(name: "action", value: "initializeUpload")]) |
| 132 | let (document, _) = try await transport.request(initialize, token: token, method: "POST", |
| 133 | json: ["initializeUploadRequest": ["owner": owner, "fileSizeBytes": video.size, |
| 134 | "uploadCaptions": false, "uploadThumbnail": thumbnail != nil]], headers: headers) |
| 135 | guard let value = document["value"] as? [String: Any], let urn = value["video"] as? String, |
| 136 | urn.range(of: #"\Aurn:li:video:[A-Za-z0-9_-]{1,200}\z"#, options: .regularExpression) != nil, |
| 137 | let uploadToken = value["uploadToken"] as? String, |
| 138 | let instructions = value["uploadInstructions"] as? [[String: Any]], !instructions.isEmpty else { |
| 139 | throw WorkspaceError("LinkedIn didn’t confirm the video upload instructions.") |
| 140 | } |
| 141 | let thumbnailURL: URL? |
| 142 | if thumbnail != nil { |
| 143 | guard let address = value["thumbnailUploadUrl"] as? String, let url = URL(string: address), |
| 144 | url.scheme == "https", url.user == nil, url.password == nil, url.port == nil, |
| 145 | ["www.linkedin.com", "www.linkedin-ei.com"].contains(url.host ?? ""), |
| 146 | url.path.hasPrefix("/dms-uploads/") || url.path.hasPrefix("/dms-mpf-uploads/") else { |
| 147 | throw WorkspaceError("LinkedIn didn’t return an upload URL for the selected thumbnail.") |
| 148 | } |
| 149 | thumbnailURL = url |
| 150 | } else { |
| 151 | thumbnailURL = nil |
| 152 | } |
| 153 | let reader = try VideoReader(video) |
| 154 | var offset: Int64 = 0 |
| 155 | var parts: [String] = [] |
| 156 | for instruction in instructions { |
| 157 | try Task.checkCancellation() |
| 158 | guard let first = instruction["firstByte"] as? Int64, first == offset, first < video.size, |
| 159 | let last = instruction["lastByte"] as? Int64, last >= first, last - first < 8 * 1024 * 1024, |
| 160 | let address = instruction["uploadUrl"] as? String, let url = URL(string: address), |
| 161 | url.host == "www.linkedin.com", url.port == nil, url.path.hasPrefix("/dms-uploads/") else { |
| 162 | throw WorkspaceError("LinkedIn returned invalid video upload instructions.") |
| 163 | } |
| 164 | let end = min(last, video.size - 1) |
| 165 | let bytes = try reader.read(Int(end - first + 1)) |
| 166 | let (_, response) = try await transport.request(url, method: "PUT", body: bytes, |
| 167 | headers: ["Content-Type": "application/octet-stream"], expectsJSON: false, timeout: 120) |
| 168 | guard let tag = response.value(forHTTPHeaderField: "ETag")?.trimmingCharacters(in: CharacterSet(charactersIn: "\"")), |
| 169 | !tag.isEmpty else { |
| 170 | throw WorkspaceError("LinkedIn couldn’t confirm a video upload part.") |
| 171 | } |
| 172 | parts.append(tag) |
| 173 | offset = end + 1 |
| 174 | } |
| 175 | try reader.verify() |
| 176 | if let thumbnail, let thumbnailURL { |
| 177 | do { |
| 178 | _ = try await transport.request(thumbnailURL, method: "PUT", body: thumbnail.jpeg, |
| 179 | headers: ["Content-Type": "application/octet-stream", "media-type-family": "STILLIMAGE"], |
| 180 | expectsJSON: false, timeout: 120) |
| 181 | } catch { |
| 182 | throw WorkspaceError("Couldn’t upload the LinkedIn video thumbnail. \(error.localizedDescription)") |
| 183 | } |
| 184 | } |
| 185 | let finalize = base.appending(queryItems: [URLQueryItem(name: "action", value: "finalizeUpload")]) |
| 186 | _ = try await transport.request(finalize, token: token, method: "POST", |
| 187 | json: ["finalizeUploadRequest": ["video": urn, "uploadToken": uploadToken, "uploadedPartIds": parts]], headers: headers) |
| 188 | let encoded = urn.replacingOccurrences(of: ":", with: "%3A") |
| 189 | let statusURL = URL(string: base.absoluteString + "/" + encoded)! |
| 190 | let deadline = Date.now.addingTimeInterval(240) |
| 191 | repeat { |
| 192 | let (status, _) = try await transport.request(statusURL, token: token, headers: headers) |
| 193 | guard status["id"] as? String == urn, status["owner"] as? String == owner else { |
| 194 | throw WorkspaceError("LinkedIn couldn’t confirm the uploaded video and its owner.") |
| 195 | } |
| 196 | switch status["status"] as? String { |
| 197 | case "AVAILABLE": |
| 198 | if thumbnail == nil { return urn } |
| 199 | // For an upload that requested a thumbnail, LinkedIn only reports it after processing. |
| 200 | if let address = status["thumbnail"] as? String, let image = URL(string: address), |
| 201 | image.scheme == "https", image.host != nil { return urn } |
| 202 | try await Task.sleep(for: .seconds(3)) |
| 203 | case "PROCESSING_FAILED": throw WorkspaceError("LinkedIn rejected the video during processing.") |
| 204 | case "PROCESSING", "WAITING_UPLOAD": try await Task.sleep(for: .seconds(3)) |
| 205 | default: throw WorkspaceError("LinkedIn returned an unknown video status.") |
| 206 | } |
| 207 | } while Date.now < deadline |
| 208 | if thumbnail != nil { |
| 209 | throw WorkspaceError("LinkedIn hasn’t confirmed the video and custom thumbnail. Review the draft again before posting.") |
| 210 | } |
| 211 | throw WorkspaceError("LinkedIn is still processing the video. Review the post and try again.") |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | private final class VideoReader { |
| 216 | private let video: PostVideo |
| 217 | private let handle: FileHandle |
| 218 | private var digest = SHA256() |
| 219 | private var size: Int64 = 0 |
| 220 | |
| 221 | init(_ video: PostVideo) throws { |
| 222 | self.video = video |
| 223 | handle = try FileHandle(forReadingFrom: video.url) |
| 224 | } |
| 225 | |
| 226 | deinit { try? handle.close() } |
| 227 | |
| 228 | func read(_ count: Int) throws -> Data { |
| 229 | guard let bytes = try handle.read(upToCount: count), bytes.count == count else { |
| 230 | throw WorkspaceError("The video changed during upload. Attach it again before publishing.") |
| 231 | } |
| 232 | size += Int64(bytes.count) |
| 233 | digest.update(data: bytes) |
| 234 | return bytes |
| 235 | } |
| 236 | |
| 237 | func verify() throws { |
| 238 | let hash = digest.finalize().map { String(format: "%02x", $0) }.joined() |
| 239 | guard size == video.size, hash == video.hash, try handle.read(upToCount: 1)?.isEmpty != false else { |
| 240 | throw WorkspaceError("The video changed during upload. Attach it again before publishing.") |
| 241 | } |
| 242 | } |
| 243 | } |