Branchwell

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

1import InkspringSchedule
2import SwiftUI
3
4struct PublicationReview: View {
5 @Environment(\.studioPalette) private var palette
6 let draft: WorkspaceRecord
7 let workspace: Workspace
8 var scheduleAt: Date? = nil
9 var quickX = false
10 let completed: (WorkspaceRecord) -> Void
11 let close: () -> Void
12 @State private var plan: SocialPublishPlan?
13 @State private var xArticleReview: XArticlePostReview?
14 @State private var message: String?
15 @State private var publishing = false
16 @State private var reviewing = false
17 @State private var options = SocialPublishOptions()
18 @State private var tiktok = TikTokReviewOptions()
19 @State private var creator: TikTokCreator?
20 @State private var r2: R2Configuration?
21
22 private var needsOptions: Bool { ["instagram", "reddit", "tiktok"].contains(draft["platform"]) }
23 private var isTikTokVideo: Bool { draft["format"] == "video" }
24
25
26 var body: some View {
27 StudioEditorPage(title: scheduleAt == nil ? "Review & publish" : "Review & schedule") {
28 Button("Close", role: .cancel, action: close).disabled(publishing)
29 .keyboardShortcut(.cancelAction)
30 if publishing { ProgressView().controlSize(.small) }
31 if let plan {
32 Button(xArticleReview != nil ? "Publish together on X" :
33 scheduleAt == nil ? "Post now on \(plan.platform.name)" : "Schedule TikTok post") {
34 Task { await publish(plan) }
35 }
36 .modifier(PrimaryActionStyle())
37 .disabled(publishing || message != nil)
38 } else if needsOptions {
39 Button("Review") { Task { await review() } }
40 .modifier(PrimaryActionStyle())
41 .disabled(reviewing || draft["platform"] == "tiktok" && (creator == nil || !tiktok.consent))
42 }
43 } content: {
44 StudioScrollView {
45 VStack(alignment: .leading, spacing: 16) {
46 if let scheduleAt {
47 Label(scheduleAt.formatted(date: .abbreviated, time: .shortened), systemImage: "calendar")
48 }
49 if let plan {
50 StudioPlatformLabel(name: plan.platform.rawValue, title: "\(plan.platform.name) · \(plan.accountName)")
51 if let xArticleReview {
52 ForEach(xArticleReview.articles, id: \.articleID) { article in
53 DisclosureGroup("X article · " + article.title) {
54 NewsletterPreview(title: "", subtitle: "", markdown: article.body, cover: nil)
55 }
56 }
57 Text("Inkspring publishes the article to get its URL, then sends the post and replies with the article link.")
58 .font(.callout).foregroundStyle(palette.muted)
59 }
60 if let tiktok = plan.tiktok {
61 Text(TikTokCreator.privacyLabels[tiktok.privacy] ?? tiktok.privacy)
62 .font(.headline)
63 if tiktok.branded { Text("Branded content") }
64 }
65 if let subreddit = plan.subreddit { Text("r/" + subreddit).font(.headline) }
66 if let hosting = plan.r2 {
67 Label("R2 bucket: " + hosting.bucket, systemImage: "externaldrive")
68 }
69 if let image = plan.publicImage { Text(image.absoluteString).lineLimit(2).textSelection(.enabled) }
70 Group {
71 VStack(alignment: .leading, spacing: 12) {
72 if let tiktok = plan.tiktok, !isTikTokVideo, !tiktok.title.isEmpty {
73 Text(tiktok.title).font(.headline)
74 }
75 ForEach(Array((plan.tiktok.map { [$0.caption] } ?? plan.posts).enumerated()), id: \.offset) { _, post in
76 Text(xArticleReview == nil ? post :
77 post.replacingOccurrences(of: XPostArticleLinks.pendingURL, with: "[X article link]"))
78 .textSelection(.enabled)
79 if plan.posts.count > 1 { Divider() }
80 }
81 if let video = plan.nativeVideo {
82 Label(video.name, systemImage: "video")
83 }
84 if let cover = plan.instagramCover {
85 Label("Reel cover", systemImage: "photo")
86 AttachedMedia(url: cover)
87 }
88 if let thumbnail = plan.linkedInThumbnail {
89 Label("LinkedIn video thumbnail", systemImage: "photo")
90 AttachedMedia(url: thumbnail.url)
91 }
92 if let time = plan.tiktok?.coverTimestampMS {
93 Label("Cover frame at \(Double(time) / 1000, specifier: "%.3f") seconds", systemImage: "photo")
94 }
95 AttachedMedia(url: plan.nativeVideo?.url ?? plan.image)
96 }
97 .frame(maxWidth: .infinity, alignment: .leading)
98 }
99 } else if reviewing {
100 ProgressView("Checking the connected account…")
101 } else if needsOptions {
102 if draft["platform"] == "instagram" {
103 if draft.needsNativePostVideo {
104 Text(r2 == nil ? "Set up R2 under Settings → Storage & backups → Instagram media hosting."
105 : "Inkspring uploads the attached MP4 through your R2 bucket. Instagram processes it before publishing the Reel.")
106 .foregroundStyle(palette.muted)
107 } else if r2 != nil, workspace.mediaURL(draft) != nil {
108 Toggle("Host the attached image in my R2 bucket", isOn: $options.useR2)
109 }
110 if !options.useR2 && !draft.needsNativePostVideo {
111 TextField("Public HTTPS JPEG URL", text: $options.imageURL)
112 .studioInput()
113 }
114 } else if draft["platform"] == "tiktok" {
115 if let creator {
116 tikTokFields(creator)
117 } else if message == nil {
118 ProgressView("Loading TikTok posting options…")
119 }
120 } else {
121 TextField("Subreddit (r/example)", text: $options.subreddit)
122 .studioInput()
123 TextField("Flair ID (optional)", text: $options.flair)
124 .studioInput()
125 }
126 }
127 if let message { Text(message).foregroundStyle(.red).textSelection(.enabled) }
128 }
129 .frame(maxWidth: 920, alignment: .leading)
130 .studioPage()
131 }
132 }
133 .task {
134 if draft["platform"] == "instagram" {
135 r2 = try? R2Profile.saved()?.configuration
136 } else if draft["platform"] == "tiktok" {
137 tiktok.title = String(draft.title.prefix(90))
138 tiktok.caption = draft.body
139 do { creator = try await SocialPublisher(workspace: workspace).tikTokCreator() }
140 catch { message = error.localizedDescription }
141 } else if !needsOptions {
142 await review()
143 }
144 }
145 }
146
147 private func tikTokFields(_ creator: TikTokCreator) -> some View {
148 VStack(alignment: .leading, spacing: 10) {
149 Label(creator.name, systemImage: "person.crop.circle")
150 AttachedMedia(url: workspace.mediaURL(draft))
151 if !isTikTokVideo {
152 TextField("Photo title", text: $tiktok.title).studioInput()
153 if !creator.usesManagedMedia {
154 TextField("Image URL on your verified domain", text: $options.imageURL)
155 .studioInput()
156 }
157 }
158 TextField("Caption", text: $tiktok.caption, axis: .vertical)
159 .studioInput()
160 .lineLimit(2...5)
161 StudioLabeledChoice(title: "Who can see this post?", selection: $tiktok.privacy,
162 options: [""] + creator.privacy,
163 label: { $0.isEmpty ? "Choose privacy" : TikTokCreator.privacyLabels[$0] ?? $0 })
164 Toggle("Allow viewer replies", isOn: $tiktok.comment).disabled(creator.commentDisabled)
165 if isTikTokVideo {
166 Toggle("Allow Duet", isOn: $tiktok.duet).disabled(creator.duetDisabled)
167 Toggle("Allow Stitch", isOn: $tiktok.stitch).disabled(creator.stitchDisabled)
168 Toggle("AI-generated content", isOn: $tiktok.aiGenerated)
169 }
170 Toggle("Promotes my own brand", isOn: $tiktok.yourBrand)
171 Toggle("Branded content", isOn: $tiktok.branded)
172 Toggle("I agree to TikTok’s Music Usage Confirmation", isOn: $tiktok.consent)
173 HStack {
174 StudioExternalLink("Music Usage Confirmation", destination: URL(string: "https://www.tiktok.com/legal/page/global/music-usage-confirmation/en")!)
175 if tiktok.branded {
176 StudioExternalLink("Branded Content Policy", destination: URL(string: "https://www.tiktok.com/legal/page/global/bc-policy/en")!)
177 }
178 }
179 }
180 }
181
182 private func review() async {
183 guard !reviewing else { return }
184 reviewing = true
185 message = nil
186 defer { reviewing = false }
187 if draft["platform"] == "tiktok" { options.tiktok = tiktok }
188 let publisher = SocialPublisher(workspace: workspace)
189 do {
190 if scheduleAt == nil, draft["platform"] == "x",
191 !draft["xArticleID"].isEmpty || draft.body.contains(XReplyArticle.prefix),
192 let paired = try await publisher.reviewXArticlePost(draft) {
193 xArticleReview = paired
194 plan = paired.post
195 } else {
196 plan = try await publisher.review(draft, options: options)
197 }
198 }
199 catch { message = error.localizedDescription }
200 }
201
202 private func publish(_ plan: SocialPublishPlan) async {
203 guard !publishing else { return }
204 publishing = true
205 defer { publishing = false }
206 do {
207 if let scheduleAt {
208 let scheduled = try workspace.scheduleDraft(draft, at: scheduleAt, tiktok: plan)
209 workspace.showPostResult(scheduled)
210 completed(scheduled)
211 close()
212 return
213 }
214 let publisher = SocialPublisher(workspace: workspace)
215 let receipt: WorkspaceRecord
216 if quickX {
217 let saved = try workspace.save(draft)
218 let fresh = try await publisher.review(saved)
219 guard fresh.accountID == plan.accountID, fresh.posts == plan.posts, fresh.replyID == nil else {
220 throw WorkspaceError("The X account or post changed. Review the post before trying again.")
221 }
222 receipt = try await publisher.publish(fresh)
223 } else if let xArticleReview { receipt = try await publisher.publishXArticlePost(xArticleReview) }
224 else { receipt = try await publisher.publish(plan) }
225 workspace.showPostResult(receipt)
226 completed(receipt)
227 close()
228 } catch {
229 message = error.localizedDescription
230 }
231 }
232}