Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / CompanionLibrarySync.swift
| 1 | import Foundation |
| 2 | import InkspringSchedule |
| 3 | |
| 4 | extension Workspace { |
| 5 | var companionLibrarySharing: Bool { settings["companionLibrarySharing"] as? Bool == true } |
| 6 | |
| 7 | func setCompanionLibrarySharing(_ enabled: Bool) async { |
| 8 | await withCompanionLibrarySync { cloud, id, account in |
| 9 | if enabled { |
| 10 | let previous = try await cloud.loadLibrary(workspaceID: id, account: account) |
| 11 | try await publishCompanionLibrary(cloud, workspaceID: id, account: account, |
| 12 | previous: previous, enabling: true, completed: []) |
| 13 | } else { |
| 14 | try await cloud.clearLibrary(workspaceID: id, account: account) |
| 15 | } |
| 16 | try set("companionLibrarySharing", to: enabled) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | func syncCompanionLibrary() async { |
| 21 | guard companionLibrarySharing else { return } |
| 22 | var scheduleChanged = false |
| 23 | await withCompanionLibrarySync { cloud, id, account in |
| 24 | guard let previous = try await cloud.loadLibrary(workspaceID: id, account: account), previous.enabled else { |
| 25 | throw CompanionLibraryError.disabled |
| 26 | } |
| 27 | let ready = previous.pending.filter { |
| 28 | $0.ideaDraftPlatforms == nil && $0.mediaDraft == nil && $0.quickXAccountKey == nil && $0.ideaImagePrompt == nil |
| 29 | && (!$0.usesMacAgent || agentConnected) |
| 30 | } |
| 31 | var completed = try ready.map(applyCompanionLibraryChange) |
| 32 | if let request = previous.pending.first(where: { $0.quickXAccountKey != nil }) { |
| 33 | completed.append(await publishMobileQuickX(request)) |
| 34 | } |
| 35 | if let request = previous.pending.first(where: { $0.ideaImagePrompt != nil }) { |
| 36 | completed.append(await generateMobileIdeaImage(request)) |
| 37 | } |
| 38 | var completedMedia: CompanionLibrary.Change? |
| 39 | if let request = previous.pending.first(where: { $0.mediaDraft != nil }) { |
| 40 | do { |
| 41 | let data = try await cloud.loadLibraryMedia(request, workspaceID: id, account: account) |
| 42 | completed.append(await createMobileMediaDraft(request, data: data)) |
| 43 | completedMedia = request |
| 44 | } catch CompanionLibraryError.invalid { |
| 45 | completed.append(.init(id: request.id, error: "This attachment could not be read. Choose the file again on your device.")) |
| 46 | completedMedia = request |
| 47 | } |
| 48 | } |
| 49 | if agentConnected, let request = previous.pending.first(where: { $0.ideaDraftPlatforms != nil }) { |
| 50 | completed.append(await draftMobileIdea(request)) |
| 51 | } |
| 52 | if agentConnected { await generateMobileXDraft() } |
| 53 | await publishPendingXArticles() |
| 54 | scheduleChanged = zip(ready, completed).contains { $0.0.action == .scheduleDraft && $0.1.error == nil } |
| 55 | try await publishCompanionLibrary(cloud, workspaceID: id, account: account, |
| 56 | previous: previous, enabling: false, completed: completed) |
| 57 | if let completedMedia { |
| 58 | try await cloud.deleteLibraryMedia(completedMedia, workspaceID: id, account: account) |
| 59 | } |
| 60 | } |
| 61 | if scheduleChanged { await syncCompanion() } |
| 62 | } |
| 63 | |
| 64 | private func publishCompanionLibrary(_ cloud: CloudScheduleStore, workspaceID: UUID, account: String, |
| 65 | previous: CompanionLibrary?, enabling: Bool, |
| 66 | completed: [CompanionLibrary.Result]) async throws { |
| 67 | var snapshot = makeCompanionLibrary(workspaceID: workspaceID) |
| 68 | let data = try snapshot.separateFullText() |
| 69 | let textChanged = snapshot.fullText != previous?.fullText |
| 70 | if textChanged, let data, let version = snapshot.fullText { |
| 71 | try await cloud.stageLibraryText(data, version: version, workspaceID: workspaceID, account: account) |
| 72 | } |
| 73 | _ = try await cloud.updateLibrary(workspaceID: workspaceID, account: account, create: enabling) { library in |
| 74 | guard library.enabled || enabling else { throw CompanionLibraryError.disabled } |
| 75 | library.enabled = true |
| 76 | library.acknowledge(completed) |
| 77 | updateLibrarySnapshot(&library, from: snapshot) |
| 78 | } |
| 79 | if textChanged || companionLibraryTextCleanupPending { |
| 80 | companionLibraryTextCleanupPending = true |
| 81 | try await cloud.pruneLibraryText(keeping: snapshot.fullText, workspaceID: workspaceID, account: account) |
| 82 | companionLibraryTextCleanupPending = false |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | private func withCompanionLibrarySync( |
| 87 | _ operation: (CloudScheduleStore, UUID, String) async throws -> Void |
| 88 | ) async { |
| 89 | guard companionSharing, !companionBusy, !companionLibraryBusy else { return } |
| 90 | companionLibraryBusy = true |
| 91 | defer { companionLibraryBusy = false } |
| 92 | do { |
| 93 | try reload() |
| 94 | try await operation(companionCloud(), companionWorkspaceID(), companionAccountKey()) |
| 95 | companionLibraryError = nil |
| 96 | } catch { |
| 97 | companionLibraryError = error.localizedDescription |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | func makeCompanionLibrary(workspaceID: UUID) -> CompanionLibrary { |
| 102 | var snapshot = CompanionLibrary(workspaceID: workspaceID) |
| 103 | snapshot.supportsDraftEdits = true |
| 104 | snapshot.supportsNewsletterEdits = true |
| 105 | snapshot.supportsItemManagement = true |
| 106 | snapshot.supportsXReplyArticles = true |
| 107 | snapshot.supportsXThreads = true |
| 108 | snapshot.supportsXParagraphs = true |
| 109 | snapshot.supportsRevisionHistory = true |
| 110 | snapshot.supportsXArticlePublishing = true |
| 111 | snapshot.supportsRevisionWithdrawal = true |
| 112 | snapshot.supportsQuickXPost = true |
| 113 | snapshot.supportsLinkedInArticles = true |
| 114 | if let account = try? socialAccounts.savedAccount(.x) { |
| 115 | snapshot.xArticleAccountKey = account.connectionKey |
| 116 | snapshot.xArticleAccountName = account.username.isEmpty ? account.name : "@" + account.username |
| 117 | } |
| 118 | snapshot.supportsWritingTools = true |
| 119 | snapshot.supportsAgentFeatures = agentConnected |
| 120 | snapshot.writingAgent = StudioWritingConnection(settings: settings) == .agent |
| 121 | ? StudioChatAgent.writingAgent(settings: settings).rawValue : WritingProviders(settings: settings).writingProvider.rawValue |
| 122 | snapshot.writingProviders = companionWritingProviders |
| 123 | snapshot.supportsContentPlans = true |
| 124 | snapshot.supportsClaudeIdeaDrafts = true |
| 125 | snapshot.supportsMediaDrafts = true |
| 126 | snapshot.supportsIdeaImages = true |
| 127 | let imageProvider = WritingProviders(settings: settings).imageProvider |
| 128 | snapshot.ideaImageProvider = imageProvider.isSaved ? imageProvider.name : nil |
| 129 | snapshot.postingWindows = Dictionary(uniqueKeysWithValues: SocialPlatform.allCases.filter { $0 != .tiktok }.map { |
| 130 | ($0.rawValue, postingWindow(for: $0.rawValue)) |
| 131 | }) |
| 132 | snapshot.postingTimeZone = TimeZone.current.identifier |
| 133 | snapshot.projects = Array(projects.sorted { |
| 134 | ($0.id == projectID ? 0 : 1, $0.title, $0.id) < ($1.id == projectID ? 0 : 1, $1.title, $1.id) |
| 135 | }.prefix(100)).map { |
| 136 | .init(id: $0.id, name: String($0.title.prefix(100))) |
| 137 | } |
| 138 | let projectIDs = Set(snapshot.projects.map(\.id)) |
| 139 | let candidates = (records + trashedRecords).filter { |
| 140 | projectIDs.contains($0.projectID) && |
| 141 | ($0.kind == "idea" || $0.kind == "draft" && !["posted", "posting"].contains($0.scheduleStatus)) |
| 142 | }.sorted { ($0["updatedAt"], $0.id) > ($1["updatedAt"], $1.id) } |
| 143 | let trashIDs = Set(trashedRecords.map(\.id)) |
| 144 | let encoder = JSONEncoder() |
| 145 | var bytes = 0 |
| 146 | func preview(_ record: WorkspaceRecord) -> Data? { |
| 147 | imageURL(record).flatMap(IdeaArtwork.preview(from:)) |
| 148 | ?? videoThumbnailURL(record).flatMap(IdeaArtwork.preview(from:)) |
| 149 | } |
| 150 | for kind in [CompanionLibrary.Item.Kind.draft, .idea] { |
| 151 | for inTrash in [false, true] { |
| 152 | let rows = candidates.filter { $0.kind == kind.rawValue && trashIDs.contains($0.id) == inTrash } |
| 153 | var selected: [String: CompanionLibrary.Item] = [:] |
| 154 | var kindBytes = 0 |
| 155 | func add(_ record: WorkspaceRecord) { |
| 156 | guard selected.count < 50, selected[record.id] == nil else { return } |
| 157 | let applied = Set(record.appliedRevisionCommentIDs) |
| 158 | let comments = record.comments.suffix(4).compactMap { comment -> (text: String, date: String, state: String?)? in |
| 159 | guard let text = comment["text"] as? String else { return nil } |
| 160 | let state = (comment["revisionRequestID"] as? String).map { |
| 161 | applied.contains($0) ? "applied" : record.acceptsRevisionComments ? "pending" : "waitingForDraft" |
| 162 | } |
| 163 | return (String(text.prefix(1000)), comment["at"] as? String ?? "", state) |
| 164 | } |
| 165 | let attachment: CompanionLibrary.Item.Attachment? = |
| 166 | record.fields["video"] is [String: Any] ? .video : |
| 167 | record.fields["image"] is [String: Any] ? .image : nil |
| 168 | var item = CompanionLibrary.Item( |
| 169 | id: record.id, revision: record["updatedAt"], kind: kind, projectID: record.projectID, |
| 170 | title: record.title, body: record.body, shortened: false, |
| 171 | platform: record["platform"], status: record.scheduleStatus.isEmpty ? record["status"] : record.scheduleStatus, |
| 172 | notes: comments.map(\.text), noteDates: comments.map(\.date), attachment: attachment, |
| 173 | referenceID: record.referenceID |
| 174 | ) |
| 175 | item.planMarkdown = record.fields["planMarkdown"] as? String |
| 176 | item.previousPlanMarkdown = record.fields["previousPlanMarkdown"] as? String |
| 177 | item.isTrashed = inTrash |
| 178 | item.history = try? revisionHistory(for: record) |
| 179 | if record.kind == "draft" { |
| 180 | item.format = record["format"] |
| 181 | if record.fields["mobileGenerationPending"] as? Bool == true { |
| 182 | item.generationStatus = record["generationError"].isEmpty ? "Waiting for your Mac to generate this draft." : record["generationError"] |
| 183 | } |
| 184 | } else { |
| 185 | let writing = record.fields["mobileWritingVersions"] as? [String: String] ?? [:] |
| 186 | let links = record.draftVersions.merging(writing) { draftID, _ in draftID } |
| 187 | item.draftedIdeaPlatforms = links.keys.sorted() |
| 188 | item.draftedIdeaIDs = links.isEmpty ? nil : links |
| 189 | } |
| 190 | item.writingReply = record["notesReply"].isEmpty ? nil : record["notesReply"] |
| 191 | item.writingError = record["writingRequestError"].isEmpty ? nil : record["writingRequestError"] |
| 192 | if comments.contains(where: { $0.state != nil }) { item.noteStates = comments.map(\.state) } |
| 193 | item.revisionRequests = record.revisionRequests |
| 194 | if record.fields["manualQuote"] as? Bool == true { item.requiresMacScheduling = true } |
| 195 | guard let encoded = try? encoder.encode(item.indexEntry), kindBytes + encoded.count <= 52_000, |
| 196 | bytes + encoded.count <= 208_000 else { return } |
| 197 | item.imagePreview = preview(record) |
| 198 | selected[record.id] = item |
| 199 | kindBytes += encoded.count |
| 200 | bytes += encoded.count |
| 201 | } |
| 202 | if kind == .draft, !inTrash { |
| 203 | // Preserve a few video entries within the iCloud index budget. |
| 204 | for record in rows where record.fields["video"] is [String: Any] { |
| 205 | add(record) |
| 206 | if selected.count == 3 { break } |
| 207 | } |
| 208 | } |
| 209 | for record in rows { |
| 210 | if selected.count == 50 { break } |
| 211 | add(record) |
| 212 | } |
| 213 | snapshot.items.append(contentsOf: rows.compactMap { selected[$0.id] }) |
| 214 | snapshot.hasMore = snapshot.hasMore || selected.count < rows.count |
| 215 | } |
| 216 | } |
| 217 | snapshot.hasMore = snapshot.hasMore || snapshot.projects.count < projects.count |
| 218 | let longForm = records.filter { $0.isLongForm && projectIDs.contains($0.projectID) } |
| 219 | .sorted { ($0["updatedAt"], $0.id) > ($1["updatedAt"], $1.id) } |
| 220 | var longFormBytes = 0 |
| 221 | var indexed: [CompanionLibrary.Item] = [] |
| 222 | for record in longForm { |
| 223 | var item = CompanionLibrary.Item(id: record.id, revision: record["updatedAt"], |
| 224 | kind: CompanionLibrary.Item.Kind(rawValue: record.kind) ?? .newsletter, |
| 225 | projectID: record.projectID, title: record.title, body: record.body, |
| 226 | shortened: false, platform: ScheduleListing.channel(of: record), |
| 227 | status: record["state"], notes: record.comments.suffix(4).compactMap { $0["text"] as? String }, |
| 228 | noteDates: record.comments.suffix(4).map { $0["at"] as? String ?? "" }, referenceID: record.referenceID) |
| 229 | item.noteStates = record.comments.suffix(4).map { comment in |
| 230 | guard let id = comment["revisionRequestID"] as? String else { return nil } |
| 231 | return record.appliedRevisionCommentIDs.contains(id) ? "applied" : "pending" |
| 232 | } |
| 233 | item.revisionRequests = record.revisionRequests |
| 234 | item.writingError = record["writingRequestError"].isEmpty ? nil : record["writingRequestError"] |
| 235 | item.writingReply = record["notesReply"].isEmpty ? nil : record["notesReply"] |
| 236 | if record.kind == "article" { |
| 237 | item.publicationStatus = record["articlePublicationStatus"] |
| 238 | item.publicationURL = record["articleURL"] |
| 239 | item.publicationError = record["articlePublicationError"] |
| 240 | } |
| 241 | item.planMarkdown = record.fields["planMarkdown"] as? String |
| 242 | item.previousPlanMarkdown = record.fields["previousPlanMarkdown"] as? String |
| 243 | item.history = try? revisionHistory(for: record) |
| 244 | guard let data = try? encoder.encode(item.indexEntry), longFormBytes + data.count + 1 <= 260_000 else { continue } |
| 245 | longFormBytes += data.count + 1 |
| 246 | item.imagePreview = preview(record) |
| 247 | indexed.append(item) |
| 248 | } |
| 249 | snapshot.newsletters = indexed.filter { $0.kind == .newsletter } |
| 250 | snapshot.scripts = indexed.filter { $0.kind == .script } |
| 251 | snapshot.articles = indexed.filter { $0.kind == .article } |
| 252 | snapshot.supportsScripts = true |
| 253 | snapshot.hasMoreNewsletters = indexed.count { $0.kind == .newsletter } < longForm.count { $0.kind == "newsletter" } || |
| 254 | records.contains { $0.kind == "newsletter" && !projectIDs.contains($0.projectID) } |
| 255 | snapshot.hasMore = snapshot.hasMore || indexed.count < longForm.count |
| 256 | let indexedIDs = Set((snapshot.items + indexed).map(\.id)) |
| 257 | let scheduled = companionPosts().map(\.id) |
| 258 | let publicationIDs = PublishedPostFeed.entries(in: records).map(\.id) |
| 259 | let byID = Dictionary(records.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) |
| 260 | var remainingPreviewBytes = 4_000_000 |
| 261 | var additional: [String: Data] = [:] |
| 262 | for id in scheduled + publicationIDs where !indexedIDs.contains(id) && additional[id] == nil { |
| 263 | guard remainingPreviewBytes >= 8_000 else { break } |
| 264 | guard let record = byID[id], projectIDs.contains(record.projectID), |
| 265 | let data = preview(record), data.count <= remainingPreviewBytes else { continue } |
| 266 | additional[id] = data |
| 267 | remainingPreviewBytes -= data.count |
| 268 | } |
| 269 | snapshot.additionalImagePreviews = additional.isEmpty ? nil : additional |
| 270 | return snapshot |
| 271 | } |
| 272 | |
| 273 | private func updateLibrarySnapshot(_ library: inout CompanionLibrary, from snapshot: CompanionLibrary) { |
| 274 | guard library.supportsContentPlans != snapshot.supportsContentPlans || |
| 275 | library.supportsDraftEdits != snapshot.supportsDraftEdits || |
| 276 | library.supportsNewsletterEdits != snapshot.supportsNewsletterEdits || |
| 277 | library.supportsItemManagement != snapshot.supportsItemManagement || |
| 278 | library.supportsXReplyArticles != snapshot.supportsXReplyArticles || |
| 279 | library.supportsXThreads != snapshot.supportsXThreads || |
| 280 | library.supportsXParagraphs != snapshot.supportsXParagraphs || |
| 281 | library.supportsClaudeIdeaDrafts != snapshot.supportsClaudeIdeaDrafts || |
| 282 | library.supportsMediaDrafts != snapshot.supportsMediaDrafts || |
| 283 | library.supportsIdeaImages != snapshot.supportsIdeaImages || library.ideaImageProvider != snapshot.ideaImageProvider || |
| 284 | library.supportsRevisionHistory != snapshot.supportsRevisionHistory || |
| 285 | library.supportsXArticlePublishing != snapshot.supportsXArticlePublishing || |
| 286 | library.supportsLinkedInArticles != snapshot.supportsLinkedInArticles || |
| 287 | library.xArticleAccountKey != snapshot.xArticleAccountKey || library.xArticleAccountName != snapshot.xArticleAccountName || |
| 288 | library.supportsRevisionWithdrawal != snapshot.supportsRevisionWithdrawal || |
| 289 | library.supportsQuickXPost != snapshot.supportsQuickXPost || |
| 290 | library.supportsWritingTools != snapshot.supportsWritingTools || library.writingAgent != snapshot.writingAgent || |
| 291 | library.writingProviders != snapshot.writingProviders || |
| 292 | library.supportsAgentFeatures != snapshot.supportsAgentFeatures || |
| 293 | library.postingWindows != snapshot.postingWindows || library.postingTimeZone != snapshot.postingTimeZone || |
| 294 | library.projects != snapshot.projects || library.items != snapshot.items || |
| 295 | library.articles != snapshot.articles || library.scripts != snapshot.scripts || library.supportsScripts != snapshot.supportsScripts || |
| 296 | library.newsletters != snapshot.newsletters || library.hasMoreNewsletters != snapshot.hasMoreNewsletters || |
| 297 | library.hasMore != snapshot.hasMore || library.fullText != snapshot.fullText else { return } |
| 298 | library.projects = snapshot.projects |
| 299 | library.supportsDraftEdits = snapshot.supportsDraftEdits |
| 300 | library.supportsNewsletterEdits = snapshot.supportsNewsletterEdits |
| 301 | library.supportsItemManagement = snapshot.supportsItemManagement |
| 302 | library.supportsXReplyArticles = snapshot.supportsXReplyArticles |
| 303 | library.supportsXThreads = snapshot.supportsXThreads |
| 304 | library.supportsXParagraphs = snapshot.supportsXParagraphs |
| 305 | library.supportsClaudeIdeaDrafts = snapshot.supportsClaudeIdeaDrafts |
| 306 | library.supportsMediaDrafts = snapshot.supportsMediaDrafts |
| 307 | library.supportsIdeaImages = snapshot.supportsIdeaImages |
| 308 | library.ideaImageProvider = snapshot.ideaImageProvider |
| 309 | library.supportsRevisionHistory = snapshot.supportsRevisionHistory |
| 310 | library.supportsXArticlePublishing = snapshot.supportsXArticlePublishing |
| 311 | library.supportsLinkedInArticles = snapshot.supportsLinkedInArticles |
| 312 | library.xArticleAccountKey = snapshot.xArticleAccountKey |
| 313 | library.xArticleAccountName = snapshot.xArticleAccountName |
| 314 | library.supportsRevisionWithdrawal = snapshot.supportsRevisionWithdrawal |
| 315 | library.supportsQuickXPost = snapshot.supportsQuickXPost |
| 316 | library.supportsWritingTools = snapshot.supportsWritingTools |
| 317 | library.supportsAgentFeatures = snapshot.supportsAgentFeatures |
| 318 | library.writingAgent = snapshot.writingAgent |
| 319 | library.writingProviders = snapshot.writingProviders |
| 320 | library.supportsContentPlans = snapshot.supportsContentPlans |
| 321 | library.postingWindows = snapshot.postingWindows |
| 322 | library.postingTimeZone = snapshot.postingTimeZone |
| 323 | library.items = snapshot.items |
| 324 | library.newsletters = snapshot.newsletters |
| 325 | library.scripts = snapshot.scripts |
| 326 | library.articles = snapshot.articles |
| 327 | library.supportsScripts = snapshot.supportsScripts |
| 328 | library.hasMoreNewsletters = snapshot.hasMoreNewsletters |
| 329 | library.fullText = snapshot.fullText |
| 330 | library.hasMore = snapshot.hasMore |
| 331 | library.updatedAt = .now |
| 332 | } |
| 333 | |
| 334 | func applyCompanionLibraryChange(_ change: CompanionLibrary.Change) throws -> CompanionLibrary.Result { |
| 335 | try withChanges { |
| 336 | let savedIDs = settings["companionLibraryApplied"] as? [String] ?? [] |
| 337 | let id = change.id.uuidString.lowercased() |
| 338 | var newsletterRevisions = settings["companionNewsletterRevisions"] as? [String: String] ?? [:] |
| 339 | if savedIDs.contains(id) { return .init(id: change.id, newsletterRevision: newsletterRevisions[id]) } |
| 340 | guard change.valid, change.ideaDraftPlatforms == nil, change.mediaDraft == nil, change.quickXAccountKey == nil, |
| 341 | change.ideaImagePrompt == nil else { |
| 342 | return .init(id: change.id, error: "Invalid mobile change.") |
| 343 | } |
| 344 | if let error = try applyLibraryAction(change, id: id) { return .init(id: change.id, error: error) } |
| 345 | let retainedIDs = Array((savedIDs + [id]).suffix(160)) |
| 346 | if change.action == .editDraft || change.createsScript == true { |
| 347 | let recordID = change.createsScript == true ? id : change.itemID |
| 348 | newsletterRevisions[id] = records.first { $0.id == recordID }?["updatedAt"] |
| 349 | } |
| 350 | let retainedRevisions = newsletterRevisions.filter { retainedIDs.contains($0.key) } |
| 351 | if change.action == .editDraft || change.createsScript == true || retainedRevisions != newsletterRevisions { |
| 352 | try set("companionNewsletterRevisions", to: retainedRevisions) |
| 353 | } |
| 354 | try set("companionLibraryApplied", to: retainedIDs) |
| 355 | return .init(id: change.id, newsletterRevision: retainedRevisions[id]) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | private func applyLibraryAction(_ change: CompanionLibrary.Change, id: String) throws -> String? { |
| 360 | if let target = change.withdrawsRevision { |
| 361 | return try withdrawRevision(target, itemID: change.itemID) |
| 362 | } |
| 363 | if change.action == .saveRevision { |
| 364 | guard let snapshot = change.historySnapshot, |
| 365 | let record = (records + trashedRecords).first(where: { $0.id == change.itemID }), |
| 366 | ["draft", "newsletter", "script", "article"].contains(record.kind) else { return nil } |
| 367 | try retainRevision(snapshot, recordID: record.id) |
| 368 | return nil |
| 369 | } |
| 370 | if change.publishesXArticle == true { |
| 371 | try queueXArticlePublication(id: change.itemID, revision: change.revision, |
| 372 | accountKey: change.xArticleAccountKey ?? "", requestID: id) |
| 373 | return nil |
| 374 | } |
| 375 | if change.requestsWritingHelp == true { |
| 376 | if withdrawnRevisionIDs(for: change.itemID).contains(id) { return nil } |
| 377 | guard let record = records.first(where: { $0.id == change.itemID }), record.acceptsRevisionComments else { |
| 378 | return "Choose an editable idea or unscheduled draft for this revision request." |
| 379 | } |
| 380 | if let selection = change.writingSelection { |
| 381 | do { _ = try companionWritingModel(selection) } |
| 382 | catch { return error.localizedDescription } |
| 383 | } |
| 384 | try addComment(to: record, text: change.text, revisionRequestID: id, writingSelection: change.writingSelection, fromCompanion: true) |
| 385 | return nil |
| 386 | } |
| 387 | if change.contentOperation != nil { return try applyContentOperation(change, requestID: id) } |
| 388 | if change.generatesXDraft == true { |
| 389 | if (records + trashedRecords).contains(where: { $0.id == id }) || |
| 390 | (settings["libraryDeletedIDs"] as? [String] ?? []).contains(id) { return nil } |
| 391 | let idea = records.first { $0.id == change.itemID && $0.kind == "idea" } |
| 392 | let projectID = idea?.projectID ?? change.itemID |
| 393 | guard projects.contains(where: { $0.id == projectID }), |
| 394 | let format = change.xFormat, XPostStyle(rawValue: format) != nil else { |
| 395 | return "Choose an existing project and an X post type." |
| 396 | } |
| 397 | if let idea, idea["updatedAt"] != change.revision { return "This idea changed. Reopen it before generating." } |
| 398 | var draft = WorkspaceRecord.new("draft", projectID: projectID) |
| 399 | draft["id"] = id |
| 400 | draft["title"] = change.title |
| 401 | draft["brief"] = change.text |
| 402 | draft["platform"] = "x" |
| 403 | draft["format"] = format |
| 404 | draft["ideaId"] = idea?.id ?? "" |
| 405 | draft.fields["mobileGenerationPending"] = true |
| 406 | if let selection = change.writingSelection { |
| 407 | do { _ = try companionWritingModel(selection) } |
| 408 | catch { return error.localizedDescription } |
| 409 | draft["mobileWritingProvider"] = selection.provider |
| 410 | draft["mobileWritingModel"] = selection.model ?? "" |
| 411 | } |
| 412 | try save(draft) |
| 413 | return nil |
| 414 | } |
| 415 | if change.isLongFormEdit { |
| 416 | guard var newsletter = records.first(where: { $0.kind == (change.editsScript == true ? change.writingKind ?? "script" : "newsletter") && $0.id == change.itemID }) else { |
| 417 | return "This newsletter is no longer available." |
| 418 | } |
| 419 | guard ["draft", "synced"].contains(newsletter["state"]) else { |
| 420 | return "This newsletter’s current publishing status prevents editing." |
| 421 | } |
| 422 | if change.restoresRevision == true { |
| 423 | guard newsletter["updatedAt"] == change.revision else { return "This newsletter changed. Open its latest version before restoring." } |
| 424 | newsletter["title"] = change.title |
| 425 | if let subtitle = change.subtitle { newsletter["subtitle"] = subtitle } |
| 426 | } |
| 427 | var body = change.text |
| 428 | if let base = change.baseNewsletterText { |
| 429 | guard let merged = NewsletterMerge.merge(base: base, mac: newsletter.body, mobile: change.text) else { |
| 430 | return "Both devices edited the same part of this newsletter. Your mobile edit is still saved on this device." |
| 431 | } |
| 432 | body = merged |
| 433 | } else if newsletter["updatedAt"] != change.revision && newsletter.body != change.text { |
| 434 | return "This newsletter changed on your Mac before the edit could sync. Your mobile edit is still saved on this device." |
| 435 | } |
| 436 | if change.isLongFormEdit, let baseTitle = change.baseScriptTitle, |
| 437 | baseTitle != change.title, newsletter.title != baseTitle, newsletter.title != change.title { |
| 438 | return "Both devices changed the script title. Your mobile version is still saved on this device." |
| 439 | } |
| 440 | let changesTitle = change.isLongFormEdit && !change.title.isEmpty && |
| 441 | (change.baseScriptTitle == nil || change.baseScriptTitle != change.title) |
| 442 | if newsletter.body != body || change.restoresRevision == true || changesTitle && change.title != newsletter.title { |
| 443 | if changesTitle { newsletter["title"] = change.title } |
| 444 | newsletter["body"] = body |
| 445 | try save(newsletter) |
| 446 | } |
| 447 | return nil |
| 448 | } |
| 449 | if change.createsScript == true { |
| 450 | guard projects.contains(where: { $0.id == change.itemID }) else { return "This project no longer exists on your Mac." } |
| 451 | let linkedInArticle = change.writingKind == "linkedin-article" |
| 452 | let recordKind = linkedInArticle ? "article" : change.writingKind ?? "script" |
| 453 | if records.contains(where: { $0.id == id && $0.kind == recordKind }) { return nil } |
| 454 | var script = WorkspaceRecord.new(recordKind, projectID: change.itemID) |
| 455 | script["id"] = id |
| 456 | script["title"] = change.title |
| 457 | script["body"] = change.text |
| 458 | if linkedInArticle { |
| 459 | script["platform"] = "linkedin" |
| 460 | script.fields["writingOnly"] = true |
| 461 | } |
| 462 | try save(script) |
| 463 | return nil |
| 464 | } |
| 465 | if change.action == .addIdea { |
| 466 | guard projects.contains(where: { $0.id == change.itemID }) else { return "This project no longer exists on your Mac." } |
| 467 | if records.contains(where: { $0.id == id && $0.kind == "idea" }) { return nil } |
| 468 | var idea = WorkspaceRecord.new("idea", projectID: change.itemID) |
| 469 | idea["id"] = id |
| 470 | idea["topic"] = change.title |
| 471 | idea["text"] = change.text |
| 472 | idea["origin"] = "Mobile" |
| 473 | idea.fields["planMarkdown"] = change.initialPlan |
| 474 | try save(idea) |
| 475 | return nil |
| 476 | } |
| 477 | let active = records.first { $0.id == change.itemID && ["draft", "idea"].contains($0.kind) } |
| 478 | let trashed = trashedRecords.first { $0.id == change.itemID && ["draft", "idea"].contains($0.kind) } |
| 479 | let movesToTrash = change.action == .trashItem || change.action == .skipIdea |
| 480 | if movesToTrash, trashed != nil { return nil } |
| 481 | if change.action == .deleteItem, trashed == nil { |
| 482 | if active != nil { return "Move this item to Trash again before deleting it." } |
| 483 | if (settings["libraryDeletedIDs"] as? [String] ?? []).contains(change.itemID) { return nil } |
| 484 | } |
| 485 | let needsTrash = [.restoreItem, .restoreIdea, .deleteItem].contains(change.action) |
| 486 | guard var record = needsTrash ? trashed : active else { |
| 487 | return "This item is no longer available." |
| 488 | } |
| 489 | guard change.action == .note || record["updatedAt"] == change.revision else { |
| 490 | return "This item changed since you opened it." |
| 491 | } |
| 492 | switch change.action { |
| 493 | case .saveRevision: break |
| 494 | case .scheduleDraft: |
| 495 | guard record.kind == "draft", let hour = change.postingHour, |
| 496 | let platform = SocialPlatform(rawValue: record["platform"]), |
| 497 | platform != .tiktok, record.fields["manualQuote"] as? Bool != true else { |
| 498 | return "Finish scheduling this post on your Mac." |
| 499 | } |
| 500 | guard !["queued", "due", "posting", "posted", "uncertain"].contains(record.scheduleStatus) else { |
| 501 | return "Check the post’s current status in Schedule before scheduling it again." |
| 502 | } |
| 503 | do { |
| 504 | let slot = try preferredPostingDate(for: platform.rawValue, hour: hour, minute: postingMinute(for: platform.rawValue)) |
| 505 | _ = try scheduleDraft(record, at: slot) |
| 506 | } catch { return error.localizedDescription } |
| 507 | case .trashItem: |
| 508 | do { try trashLibraryItem(record) } catch { return error.localizedDescription } |
| 509 | case .restoreItem: |
| 510 | do { try restoreLibraryItem(record) } catch { return error.localizedDescription } |
| 511 | case .deleteItem: |
| 512 | do { try deleteLibraryItem(record) } catch { return error.localizedDescription } |
| 513 | case .editIdea: |
| 514 | guard record.kind == "idea", ["draft", "skipped"].contains(record["status"]) else { |
| 515 | return "This idea already has drafts. Edit those posts instead." |
| 516 | } |
| 517 | record["topic"] = change.title |
| 518 | record["text"] = change.text |
| 519 | try save(record) |
| 520 | case .note: |
| 521 | if record.comments.contains(where: { $0["revisionRequestID"] as? String == id }) { return nil } |
| 522 | guard record.comments.count < 100 else { return "This item has reached its limit of 100 requests." } |
| 523 | try addComment(to: record, text: change.text, revisionRequestID: record.kind == "draft" ? id : nil, fromCompanion: true) |
| 524 | case .skipIdea, .restoreIdea: |
| 525 | let skipping = change.action == .skipIdea |
| 526 | guard record.kind == "idea", record["status"] == (skipping ? "draft" : "skipped") else { |
| 527 | return "This idea has already changed status." |
| 528 | } |
| 529 | if skipping { |
| 530 | do { try trashLibraryItem(record) } catch { return error.localizedDescription } |
| 531 | return nil |
| 532 | } |
| 533 | do { try restoreLibraryItem(record) } catch { return error.localizedDescription } |
| 534 | case .editDraft: |
| 535 | guard record.kind == "draft", !["posting", "posted", "uncertain"].contains(record.scheduleStatus) else { |
| 536 | return "This draft can’t be edited while it’s publishing or published." |
| 537 | } |
| 538 | record["title"] = change.title |
| 539 | record["content"] = change.text |
| 540 | if let format = change.xFormat { |
| 541 | guard record["platform"] == "x", record.fields["manualQuote"] as? Bool != true else { |
| 542 | return "Change this post’s format on your Mac." |
| 543 | } |
| 544 | record["format"] = format |
| 545 | } |
| 546 | try save(record) |
| 547 | case .addIdea: |
| 548 | break |
| 549 | } |
| 550 | return nil |
| 551 | } |
| 552 | |
| 553 | func createMobileMediaDraft(_ change: CompanionLibrary.Change, data: Data) async -> CompanionLibrary.Result { |
| 554 | do { |
| 555 | try reload() |
| 556 | let draftID = change.id.uuidString.lowercased() |
| 557 | if (records + trashedRecords).contains(where: { $0.id == draftID }) || |
| 558 | (settings["libraryDeletedIDs"] as? [String] ?? []).contains(draftID) { return .init(id: change.id) } |
| 559 | guard change.valid, let media = change.mediaDraft, data.count == media.byteCount, |
| 560 | CompanionLibrary.TextVersion(data: data) == media.version, |
| 561 | projects.contains(where: { $0.id == change.itemID }) else { |
| 562 | throw WorkspaceError("Choose an existing project and a supported attachment.") |
| 563 | } |
| 564 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 565 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, |
| 566 | attributes: [.posixPermissions: 0o700]) |
| 567 | defer { try? FileManager.default.removeItem(at: folder) } |
| 568 | let file = folder.appending(path: media.fileName) |
| 569 | try data.write(to: file, options: .atomic) |
| 570 | var draft = WorkspaceRecord.new("draft", projectID: change.itemID) |
| 571 | draft["id"] = draftID |
| 572 | draft["title"] = "\(platformName(media.platform)) \(media.isVideo ? "video" : "post")" |
| 573 | draft["platform"] = media.platform |
| 574 | draft["format"] = media.isVideo ? "video" : "image" |
| 575 | draft["content"] = change.text |
| 576 | if let ideaID = media.ideaID { |
| 577 | guard records.contains(where: { $0.id == ideaID && $0.kind == "idea" && $0.projectID == change.itemID }) else { |
| 578 | throw WorkspaceError("Open the saved idea in this project before starting a media draft.") |
| 579 | } |
| 580 | draft["ideaId"] = ideaID |
| 581 | } |
| 582 | if media.isVideo { draft.setDraftMedia(try await attachVideo(file), as: .video) } |
| 583 | else { draft.setDraftMedia(try attachImage(file), as: .image) } |
| 584 | try save(draft) |
| 585 | return .init(id: change.id) |
| 586 | } catch { |
| 587 | return .init(id: change.id, error: error.localizedDescription) |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | func publishMobileQuickX(_ change: CompanionLibrary.Change, publisher: SocialPublisher? = nil) async -> CompanionLibrary.Result { |
| 592 | let id = change.id.uuidString.lowercased() |
| 593 | func success(_ receipt: WorkspaceRecord) -> CompanionLibrary.Result { |
| 594 | let url = (receipt.fields["steps"] as? [[String: Any]])?.first?["url"] as? String |
| 595 | return .init(id: change.id, publicationURL: url) |
| 596 | } |
| 597 | do { |
| 598 | try reload() |
| 599 | guard change.valid, let key = change.quickXAccountKey, projects.contains(where: { $0.id == change.itemID }) else { |
| 600 | throw WorkspaceError("Choose a project and write one X post of up to 280 characters.") |
| 601 | } |
| 602 | if let receipt = records.first(where: { $0.kind == "publication" && $0["draftId"] == id && $0["status"] == "published" }) { |
| 603 | return success(receipt) |
| 604 | } |
| 605 | let client = publisher ?? SocialPublisher(workspace: self) |
| 606 | let account = try await client.authorize(.x) |
| 607 | guard account.connectionKey == key else { |
| 608 | throw WorkspaceError("The X account changed. Open Quick X post and review the account again.") |
| 609 | } |
| 610 | let draft: WorkspaceRecord |
| 611 | if let existing = records.first(where: { $0.id == id }) { |
| 612 | guard existing.kind == "draft", existing["format"] == "post", existing["platform"] == "x", |
| 613 | existing.projectID == change.itemID, existing.body == change.text else { |
| 614 | throw WorkspaceError("The saved X post changed. Review the draft on your Mac.") |
| 615 | } |
| 616 | draft = existing |
| 617 | } else { |
| 618 | guard !trashedRecords.contains(where: { $0.id == id }), |
| 619 | !(settings["libraryDeletedIDs"] as? [String] ?? []).contains(id) else { |
| 620 | throw WorkspaceError("This X draft was removed. Check Published before trying again.") |
| 621 | } |
| 622 | var record = WorkspaceRecord.new("draft", projectID: change.itemID) |
| 623 | record["id"] = id |
| 624 | record["title"] = "Quick X post" |
| 625 | record["content"] = change.text |
| 626 | draft = try save(record) |
| 627 | } |
| 628 | let plan = try await client.review(draft) |
| 629 | guard plan.accountID == account.id, plan.posts == [change.text], plan.replyID == nil else { |
| 630 | throw WorkspaceError("The X account or post changed. Review the saved draft before publishing.") |
| 631 | } |
| 632 | return success(try await client.publish(plan)) |
| 633 | } catch { |
| 634 | return .init(id: change.id, error: error.localizedDescription) |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | func generateMobileIdeaImage(_ change: CompanionLibrary.Change, model: ContentStudio.Model? = nil) async -> CompanionLibrary.Result { |
| 639 | do { |
| 640 | try reload() |
| 641 | guard change.valid, let prompt = change.ideaImagePrompt else { throw CompanionLibraryError.invalid } |
| 642 | let requestID = change.id.uuidString.lowercased() |
| 643 | if (records + trashedRecords).contains(where: { |
| 644 | $0.id == change.itemID && ($0.fields["mobileIdeaImageRequests"] as? [String])?.contains(requestID) == true |
| 645 | }) { return .init(id: change.id) } |
| 646 | guard let idea = records.first(where: { $0.id == change.itemID && $0.kind == "idea" && $0["status"] == "draft" }), |
| 647 | idea["updatedAt"] == change.revision else { |
| 648 | throw WorkspaceError("This idea changed on your Mac. Reopen it before trying again.") |
| 649 | } |
| 650 | _ = try await ContentStudio(workspace: self, model: model).makeIdeaImage(for: idea, prompt: prompt, requestID: requestID) |
| 651 | return .init(id: change.id) |
| 652 | } catch { return .init(id: change.id, error: error.localizedDescription) } |
| 653 | } |
| 654 | |
| 655 | func draftMobileIdea(_ change: CompanionLibrary.Change, model: ContentStudio.Model? = nil) async -> CompanionLibrary.Result { |
| 656 | do { |
| 657 | try reload() |
| 658 | guard change.valid, let platforms = change.ideaDraftPlatforms else { |
| 659 | throw WorkspaceError("Invalid post idea request.") |
| 660 | } |
| 661 | let requestID = change.id.uuidString.lowercased() |
| 662 | if (records + trashedRecords).contains(where: { |
| 663 | $0.id == change.itemID && ($0.fields["mobileIdeaDraftRequests"] as? [String])?.contains(requestID) == true |
| 664 | }) { return .init(id: change.id) } |
| 665 | guard let idea = records.first(where: { $0.id == change.itemID && $0.kind == "idea" && $0["status"] == "draft" }), |
| 666 | idea["updatedAt"] == change.revision else { |
| 667 | throw WorkspaceError("This idea changed on your Mac. Reopen it before trying again.") |
| 668 | } |
| 669 | guard agentConnected || (agentAccessEnabled && model != nil) else { |
| 670 | throw WorkspaceError("Enable agent access in Inkspring → Settings → AI agents on your Mac, then try again.") |
| 671 | } |
| 672 | let selection = change.writingSelection ?? .init(provider: StudioChatAgent.claude.rawValue, model: nil) |
| 673 | let writer = try model ?? companionWritingModel(selection) |
| 674 | _ = try await ContentStudio(workspace: self, model: writer) |
| 675 | .pick(idea, platforms: platforms, mobileRequestID: requestID) |
| 676 | return .init(id: change.id) |
| 677 | } catch { |
| 678 | return .init(id: change.id, error: error.localizedDescription) |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | func generateMobileXDraft(model: ContentStudio.Model? = nil) async { |
| 683 | guard !runningMobileXGeneration else { return } |
| 684 | runningMobileXGeneration = true |
| 685 | defer { runningMobileXGeneration = false } |
| 686 | do { |
| 687 | try reload() |
| 688 | guard let draft = records.first(where: { |
| 689 | $0.kind == "draft" && $0.fields["mobileGenerationPending"] as? Bool == true && $0["generationError"].isEmpty |
| 690 | && (model != nil || agentConnected) |
| 691 | }) else { return } |
| 692 | do { |
| 693 | let provider = draft["mobileWritingProvider"] |
| 694 | let modelID = draft["mobileWritingModel"] |
| 695 | let selected = try model ?? (provider.isEmpty ? nil : companionWritingModel( |
| 696 | .init(provider: provider, model: modelID.isEmpty ? nil : modelID))) |
| 697 | _ = try await ContentStudio(workspace: self, model: selected).compose(draft, withImage: false) |
| 698 | } catch { |
| 699 | try reload() |
| 700 | if var current = records.first(where: { $0.id == draft.id && $0["updatedAt"] == draft["updatedAt"] }) { |
| 701 | current["generationError"] = "Your Mac couldn’t generate this draft. \(error.localizedDescription)" |
| 702 | try save(current) |
| 703 | } |
| 704 | } |
| 705 | } catch { companionLibraryError = error.localizedDescription } |
| 706 | } |
| 707 | |
| 708 | private var companionWritingProviders: [CompanionLibrary.WritingProvider] { |
| 709 | let selected = StudioChatAgent.writingAgent(settings: settings) |
| 710 | let usesAgent = StudioWritingConnection(settings: settings) == .agent |
| 711 | let agents: [StudioChatAgent] = usesAgent && selected == .gemini ? [.gemini, .claude, .codex] : [.claude, .codex] |
| 712 | var choices: [CompanionLibrary.WritingProvider] = agents.compactMap { agent in |
| 713 | let available = agentConnected && agent.executable != nil |
| 714 | guard available || (usesAgent && agent == selected) else { return nil } |
| 715 | return .init(id: agent.rawValue, name: agent.title, defaultModel: agent.preferredWritingModel(settings: settings), |
| 716 | models: agent.writingModels, isAvailable: available) |
| 717 | } |
| 718 | if let api = companionAPIWritingProvider { |
| 719 | choices.append(api) |
| 720 | } |
| 721 | return choices |
| 722 | } |
| 723 | |
| 724 | private var companionAPIWritingProvider: CompanionLibrary.WritingProvider? { |
| 725 | guard StudioWritingConnection(settings: settings) == .api else { return nil } |
| 726 | let providers = WritingProviders(settings: settings) |
| 727 | let provider = providers.writingProvider |
| 728 | let defaultModel = providers.writingModel |
| 729 | var models = ProviderCatalog.bundled?.writingModels(for: provider) |
| 730 | .map { CompanionLibrary.WritingModel(id: $0.id, name: $0.name) } ?? [] |
| 731 | if !defaultModel.isEmpty, !models.contains(where: { $0.id == defaultModel }) { |
| 732 | models.append(.init(id: defaultModel, name: defaultModel)) |
| 733 | } |
| 734 | return .init(id: provider.rawValue, name: "\(provider.name) API", defaultModel: defaultModel, models: models, |
| 735 | isAvailable: agentConnected && provider.isSaved) |
| 736 | } |
| 737 | |
| 738 | func companionWritingModel(_ selection: CompanionLibrary.WritingSelection) throws -> ContentStudio.Model { |
| 739 | guard agentConnected else { |
| 740 | throw WorkspaceError("Connect a writing agent in Inkspring on your Mac to use mobile writing tools.") |
| 741 | } |
| 742 | if let api = companionAPIWritingProvider, selection.provider == api.id { |
| 743 | let model = selection.model.map { ProviderKey(rawValue: api.id)?.currentModelID($0) ?? $0 } |
| 744 | if let model, !api.models.contains(where: { $0.id == model }) { |
| 745 | throw WorkspaceError("Choose a model from \(api.name)’s current list and try again.") |
| 746 | } |
| 747 | return ContentStudio.Model(WritingProviders(settings: settings, modelOverride: model)) |
| 748 | } |
| 749 | guard let agent = StudioChatAgent(rawValue: selection.provider) else { |
| 750 | throw WorkspaceError("Choose a writing provider from your Mac’s current list.") |
| 751 | } |
| 752 | guard agent.executable != nil else { |
| 753 | throw WorkspaceError("Install and sign in to \(agent.title) on your Mac, then try again.") |
| 754 | } |
| 755 | if let model = selection.model, !agent.writingModels.contains(where: { $0.id == model }) { |
| 756 | throw WorkspaceError("Choose a model from \(agent.title)’s current list and try again.") |
| 757 | } |
| 758 | return agent.writingModel(workspace: self, providers: WritingProviders(settings: settings), selectedModel: selection.model) |
| 759 | } |
| 760 | } |