Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / TikTokPublishing.swift

1import CryptoKit
2import Foundation
3import ImageIO
4import UniformTypeIdentifiers
5
6struct TikTokCreator {
7 static let privacyLabels = [
8 "PUBLIC_TO_EVERYONE": "Everyone", "MUTUAL_FOLLOW_FRIENDS": "Friends",
9 "FOLLOWER_OF_CREATOR": "Followers", "SELF_ONLY": "Only me"
10 ]
11
12 let username: String
13 let name: String
14 let privacy: [String]
15 let commentDisabled: Bool
16 let duetDisabled: Bool
17 let stitchDisabled: Bool
18 let maxDuration: Double
19 let usesManagedMedia: Bool
20}
21
22struct TikTokReviewOptions: Codable {
23 var privacy = ""
24 var title = ""
25 var caption = ""
26 var comment = false
27 var duet = false
28 var stitch = false
29 var aiGenerated = false
30 var yourBrand = false
31 var branded = false
32 var consent = false
33 var coverTimestampMS: Int?
34
35 var fingerprintFields: [String] {
36 var fields = [privacy, title, caption] + [comment, duet, stitch, aiGenerated, yourBrand, branded, consent].map { String($0) }
37 if let coverTimestampMS { fields.append(String(coverTimestampMS)) }
38 return fields
39 }
40
41 func validate(creator: TikTokCreator, video: TikTokVideo?) throws {
42 guard consent, creator.privacy.contains(privacy), !caption.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
43 caption.utf16.count <= (video == nil ? 4000 : 2200), video != nil || title.utf16.count <= 90,
44 !branded || privacy != "SELF_ONLY",
45 !comment || !creator.commentDisabled,
46 video == nil || (!duet || !creator.duetDisabled) && (!stitch || !creator.stitchDisabled) else {
47 throw WorkspaceError("Check the caption, privacy, interaction settings and consent before publishing to TikTok.")
48 }
49 if let video, creator.maxDuration <= 0 || video.duration > creator.maxDuration {
50 throw WorkspaceError("This video exceeds the duration limit for the connected TikTok account.")
51 }
52 if let coverTimestampMS, video.map({ coverTimestampMS >= 0 && Double(coverTimestampMS) / 1000 < $0.duration }) != true {
53 throw WorkspaceError("Choose a cover frame within the attached TikTok video.")
54 }
55 }
56}
57
58struct TikTokVideo: Sendable {
59 let size: Int64
60 let hash: String
61 let duration: Double
62 let type: String
63 let modified: Date?
64
65 static func coverTimestamp(for draft: WorkspaceRecord) throws -> Int? {
66 let raw = draft["tiktokCoverTime"].trimmingCharacters(in: .whitespacesAndNewlines)
67 guard !raw.isEmpty else { return nil }
68 guard let time = Double(raw), let duration = (draft.fields["video"] as? [String: Any])?["duration"] as? Double,
69 time.isFinite, time >= 0, time < duration, time <= 600 else {
70 throw WorkspaceError("Enter a cover frame in seconds within the attached TikTok video.")
71 }
72 return Int((time * 1000).rounded())
73 }
74
75 static func inspect(_ url: URL) async throws -> Self {
76 let attributes = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey, .contentModificationDateKey])
77 guard let type = VideoMetadata.types[url.pathExtension.lowercased()],
78 attributes.isRegularFile == true, attributes.isSymbolicLink != true,
79 let size = attributes.fileSize, (1...4 * 1024 * 1024 * 1024).contains(size) else {
80 throw WorkspaceError("Choose an MP4, MOV, or WebM video up to 4 GB.")
81 }
82 let metadata = try await VideoMetadata.inspect(url)
83 guard (23...60).contains(metadata.frameRate) else {
84 throw WorkspaceError("TikTok requires 23–60 frames per second.")
85 }
86 let digest = try await Task.detached(priority: .utility) { try fileDigest(url) }.value
87 let after = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey])
88 guard digest.size == size, after.fileSize == size,
89 after.contentModificationDate == attributes.contentModificationDate else {
90 throw WorkspaceError("The video changed. Attach it again.")
91 }
92 return Self(size: digest.size, hash: digest.hash, duration: metadata.duration, type: type,
93 modified: after.contentModificationDate)
94 }
95
96 var ranges: [Range<Int64>] {
97 let step = min(size, 32 * 1024 * 1024)
98 let count = Int(size / step)
99 return (0..<count).map { index in
100 let start = Int64(index) * step
101 return start..<(index == count - 1 ? size : start + step)
102 }
103 }
104}
105
106extension SocialPublisher {
107 func tikTokCreator() async throws -> TikTokCreator {
108 try await tikTokCreator(account: authorize(.tiktok))
109 }
110
111 func tikTokCreator(account: ManagedSocialAccount) async throws -> TikTokCreator {
112 let data = try await tikTokAPI("creator_info/query/", account: account, fields: [:])
113 let privacy = (data["privacy_level_options"] as? [String] ?? []).filter { TikTokCreator.privacyLabels[$0] != nil }
114 guard !privacy.isEmpty else { throw WorkspaceError("TikTok did not return publishing options for this account.") }
115 return TikTokCreator(username: data["creator_username"] as? String ?? account.username,
116 name: data["creator_nickname"] as? String ?? account.name,
117 privacy: privacy, commentDisabled: data["comment_disabled"] as? Bool == true,
118 duetDisabled: data["duet_disabled"] as? Bool == true, stitchDisabled: data["stitch_disabled"] as? Bool == true,
119 maxDuration: data["max_video_post_duration_sec"] as? Double ?? 0, usesManagedMedia: account.ownApp != true)
120 }
121
122 func tiktok(_ plan: SocialPublishPlan, account: ManagedSocialAccount,
123 receipt: inout WorkspaceRecord) async throws -> [String: String] {
124 guard let review = plan.tiktok, let creator = plan.creator else { throw WorkspaceError("Review the TikTok post first.") }
125 try review.validate(creator: creator, video: plan.video)
126 var hosted: (url: URL, key: String)?
127 var settled = true
128 do {
129 if receipt["containerId"].isEmpty {
130 var info: [String: Any] = [
131 "title": plan.video == nil ? review.title : review.caption, "privacy_level": review.privacy,
132 "disable_comment": !review.comment, "brand_content_toggle": review.branded,
133 "brand_organic_toggle": review.yourBrand
134 ]
135 if let video = plan.video, let file = plan.image {
136 info["disable_duet"] = !review.duet
137 info["disable_stitch"] = !review.stitch
138 info["is_aigc"] = review.aiGenerated
139 if let cover = review.coverTimestampMS { info["video_cover_timestamp_ms"] = cover }
140 let chunks = video.ranges
141 let opened = try FileHandle(forReadingFrom: file)
142 defer { try? opened.close() }
143 let values: [String: Any] = [
144 "post_info": info, "source_info": ["source": "FILE_UPLOAD", "video_size": video.size,
145 "chunk_size": chunks[0].count, "total_chunk_count": chunks.count]
146 ]
147 let result = try await tikTokAPI("video/init/", account: account, fields: values, publishes: true)
148 let id = try tikTokPublishID(result)
149 receipt["containerId"] = id
150 receipt.fields["containers"] = [id]
151 try workspace.updatePublication(receipt)
152 guard let raw = result["upload_url"] as? String, let url = URL(string: raw), url.scheme == "https",
153 url.host?.hasSuffix(".tiktokapis.com") == true, url.user == nil, url.password == nil, url.port == nil else {
154 throw SocialRequestError("TikTok returned an unexpected upload address. Check Publishing history.", uncertain: true)
155 }
156 settled = false
157 for chunk in chunks {
158 let current = try file.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey])
159 guard current.fileSize == Int(video.size), current.contentModificationDate == video.modified,
160 let bytes = try opened.read(upToCount: chunk.count), bytes.count == chunk.count else {
161 throw SocialRequestError("The video changed during upload. Check TikTok before retrying.", uncertain: true)
162 }
163 let (_, response) = try await transport.request(url, method: "PUT", body: bytes, headers: [
164 "Content-Type": video.type, "Content-Length": String(bytes.count),
165 "Content-Range": "bytes \(chunk.lowerBound)-\(chunk.upperBound - 1)/\(video.size)"
166 ], publishes: true, expectsJSON: false, timeout: 300)
167 guard response.statusCode == (chunk.upperBound == video.size ? 201 : 206) else {
168 throw SocialRequestError("TikTok didn’t confirm the video upload. Check Publishing history.", uncertain: true)
169 }
170 receipt.fields["uploadProgress"] = Int(chunk.upperBound * 100 / video.size)
171 try workspace.updatePublication(receipt)
172 }
173 } else {
174 var photoURL = plan.publicImage
175 if let file = plan.image, creator.usesManagedMedia {
176 hosted = try await hostTikTokPhoto(file, expectedHash: plan.imageHash, token: account.session.accessToken)
177 photoURL = hosted?.url
178 }
179 guard let photoURL else { throw WorkspaceError("Choose a photo or enter its verified public URL.") }
180 info["description"] = review.caption
181 info["auto_add_music"] = true
182 // Once init is sent, the temporary URL may still be in use even
183 // when the platform has not returned a publish ID.
184 settled = false
185 let data = try await tikTokAPI("content/init/", account: account, fields: [
186 "media_type": "PHOTO", "post_mode": "DIRECT_POST", "post_info": info,
187 "source_info": ["source": "PULL_FROM_URL", "photo_images": [photoURL.absoluteString], "photo_cover_index": 0]
188 ], publishes: true)
189 let id = try tikTokPublishID(data)
190 receipt["containerId"] = id
191 receipt.fields["containers"] = [id]
192 try workspace.updatePublication(receipt)
193 }
194 }
195 let id = receipt["containerId"]
196 for attempt in 0..<40 {
197 let data = try await tikTokAPI("status/fetch/", account: account, fields: ["publish_id": id])
198 switch data["status"] as? String {
199 case "PUBLISH_COMPLETE":
200 settled = true
201 if let hosted { await removeHostedPhoto(hosted) }
202 let ids = data["publicaly_available_post_id"] as? [Any] ?? data["publicly_available_post_id"] as? [Any] ?? []
203 let postID = ids.first as? String ?? (ids.first as? NSNumber)?.stringValue ?? ""
204 let username = creator.username.range(of: #"\A[A-Za-z0-9_.]{1,100}\z"#, options: .regularExpression) != nil
205 let numeric = postID.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil
206 let kind = plan.video == nil ? "photo" : "video"
207 let link = username && numeric ? "https://www.tiktok.com/@\(creator.username)/\(kind)/\(postID)" : ""
208 return ["id": id, "url": link, "at": WorkspaceRecord.timestamp]
209 case "FAILED":
210 settled = true
211 receipt["containerId"] = ""
212 receipt.fields["containers"] = [String]()
213 throw WorkspaceError("TikTok couldn’t publish this post. Review the media and posting settings.")
214 default:
215 if attempt < 39 { try await Task.sleep(for: .seconds(3)) }
216 }
217 }
218 throw WorkspaceError("TikTok is still processing the post. Review it again later to check the same attempt.")
219 } catch {
220 if let hosted, settled { await removeHostedPhoto(hosted) }
221 throw error
222 }
223 }
224
225 private func tikTokAPI(_ path: String, account: ManagedSocialAccount, fields: [String: Any],
226 publishes: Bool = false) async throws -> [String: Any] {
227 let url = URL(string: "https://open.tiktokapis.com/v2/post/publish/" + path)!
228 let result: [String: Any]
229 do {
230 (result, _) = try await transport.request(url, token: account.session.accessToken, method: "POST",
231 json: fields, headers: ["Content-Type": "application/json; charset=UTF-8"],
232 publishes: publishes)
233 } catch let error as SocialRequestError {
234 guard let code = error.providerCode, code != "ok" else { throw error }
235 throw SocialRequestError(tikTokFailureMessage(code), uncertain: error.uncertain, statusCode: error.statusCode,
236 providerCode: code)
237 }
238 if let error = result["error"] as? [String: Any], let code = error["code"] as? String, code != "ok" {
239 throw SocialRequestError(tikTokFailureMessage(code), providerCode: code)
240 }
241 guard let data = result["data"] as? [String: Any] else {
242 throw SocialRequestError("TikTok did not confirm the request.", uncertain: publishes)
243 }
244 return data
245 }
246
247 private func tikTokFailureMessage(_ code: String) -> String {
248 switch code {
249 case "unaudited_client_can_only_post_to_private_accounts":
250 "TikTok requires a Direct Post audit for this developer app before it can publish publicly."
251 case "access_token_invalid", "scope_not_authorized":
252 "Reconnect TikTok in Connections and allow video publishing."
253 case "privacy_level_option_mismatch":
254 "TikTok no longer offers the chosen audience. Open the review and choose an available audience."
255 case "spam_risk_too_many_posts":
256 "TikTok reports that this account reached its daily posting limit."
257 case "spam_risk_user_banned_from_posting":
258 "TikTok reports that this account is restricted from publishing."
259 case "reached_active_user_cap":
260 "TikTok reports that this developer app reached its daily limit for creators."
261 case "rate_limit_exceeded":
262 "TikTok reached its request limit. Wait before retrying."
263 case "url_ownership_unverified":
264 "TikTok requires this developer app to verify the media hosting domain."
265 default:
266 "TikTok declined the request. Check account permissions and posting options."
267 }
268 }
269
270 private func tikTokPublishID(_ data: [String: Any]) throws -> String {
271 guard let id = data["publish_id"] as? String, (1...64).contains(id.utf8.count) else {
272 throw SocialRequestError("TikTok did not return a publish ID. Check the account.", uncertain: true)
273 }
274 return id
275 }
276
277 private func hostTikTokPhoto(_ url: URL, expectedHash: String?, token: String) async throws -> (url: URL, key: String) {
278 let input = try Data(contentsOf: url)
279 guard (1...20_000_000).contains(input.count),
280 SHA256.hash(data: input).map({ String(format: "%02x", $0) }).joined() == expectedHash,
281 let source = CGImageSourceCreateWithData(input as CFData, nil),
282 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
283 kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,
284 kCGImageSourceThumbnailMaxPixelSize: 1080
285 ] as CFDictionary) else { throw WorkspaceError("Choose a photo Inkspring can read.") }
286 let bytes = NSMutableData()
287 guard let destination = CGImageDestinationCreateWithData(bytes, UTType.jpeg.identifier as CFString, 1, nil) else {
288 throw WorkspaceError("Couldn’t prepare the TikTok photo.")
289 }
290 CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.87] as CFDictionary)
291 guard CGImageDestinationFinalize(destination), (100...4_000_000).contains(bytes.length) else {
292 throw WorkspaceError("Choose a smaller TikTok photo.")
293 }
294 let (result, _) = try await transport.request(URL(string: "https://inkspring.ai/api/desktop/media")!,
295 token: token, method: "POST", body: bytes as Data,
296 headers: ["Content-Type": "image/jpeg"])
297 guard let raw = result["url"] as? String, let hosted = URL(string: raw), hosted.scheme == "https",
298 hosted.host == "inkspring.ai", hosted.user == nil, hosted.password == nil, hosted.port == nil,
299 hosted.path.hasPrefix("/tiktok-media/"), let key = result["deleteKey"] as? String, (1...200).contains(key.utf8.count) else {
300 throw WorkspaceError("The TikTok photo host returned an unexpected address.")
301 }
302 return (hosted, key)
303 }
304
305 private func removeHostedPhoto(_ hosted: (url: URL, key: String)) async {
306 _ = try? await transport.request(URL(string: "https://inkspring.ai/api/desktop/media/delete")!,
307 method: "POST", json: ["url": hosted.url.absoluteString, "deleteKey": hosted.key])
308 }
309}