Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / CompanionSync.swift
| 1 | import Foundation |
| 2 | import InkspringSchedule |
| 3 | import SwiftUI |
| 4 | |
| 5 | struct CompanionTransfer: Equatable { |
| 6 | let previousWorkspace: UUID |
| 7 | let accountKey: String |
| 8 | } |
| 9 | |
| 10 | @MainActor |
| 11 | protocol CompanionScheduleAccess { |
| 12 | func accountKey() async throws -> String |
| 13 | func load(confirmedAccount: String) async throws -> CompanionSchedule? |
| 14 | func update(workspaceID: UUID, createIfMissing: Bool, expectedAccount: String, |
| 15 | _ update: (inout CompanionSchedule) throws -> Void) async throws -> CompanionSchedule |
| 16 | } |
| 17 | |
| 18 | extension CloudScheduleStore: CompanionScheduleAccess {} |
| 19 | |
| 20 | extension Workspace { |
| 21 | var companionSharing: Bool { settings["companionSharing"] as? Bool == true } |
| 22 | |
| 23 | func setCompanionSharing(_ enabled: Bool, cloud override: (any CompanionScheduleAccess)? = nil) async { |
| 24 | guard !companionLibraryBusy else { return } |
| 25 | await withCompanionSync { |
| 26 | let cloud = try override ?? companionCloud() |
| 27 | let account = try await verifiedCompanionAccount(cloud, allowSetup: enabled) |
| 28 | if enabled { |
| 29 | let id = try companionWorkspaceID(create: true) |
| 30 | if try await offerTransferIfNeeded(to: id, account: account, cloud: cloud) { return } |
| 31 | companionTransfer = nil |
| 32 | try beginCompanionSetup(account: account, pausePosting: false) |
| 33 | let posts = companionPosts() |
| 34 | let published = PublishedPostFeed.entries(in: records) |
| 35 | let schedule = try await cloud.update(workspaceID: id, createIfMissing: true, expectedAccount: account) { |
| 36 | $0.sharing = true |
| 37 | $0.mirror(posts, recoverAbandonedSends: true) |
| 38 | try $0.setPublished(published) |
| 39 | } |
| 40 | try applyCompanionCancellations(schedule) |
| 41 | try set("companionSetupPending", to: false) |
| 42 | companionLastSync = .now |
| 43 | } else { |
| 44 | let id = try companionWorkspaceID() |
| 45 | if override == nil { try await companionCloud().clearLibrary(workspaceID: id, account: account) } |
| 46 | do { |
| 47 | let schedule = try await cloud.update(workspaceID: id, createIfMissing: false, expectedAccount: account) { |
| 48 | $0.sharing = false |
| 49 | $0.posts.removeAll { $0.state != .cancelled } |
| 50 | try $0.setPublished([]) |
| 51 | } |
| 52 | try applyCompanionCancellations(schedule) |
| 53 | } catch CompanionScheduleError.missing where companionSetupPending { |
| 54 | // This account has no published schedule to close. |
| 55 | } |
| 56 | try withChanges { |
| 57 | try set("companionSharing", to: false) |
| 58 | try set("companionLibrarySharing", to: false) |
| 59 | try set("companionSetupPending", to: false) |
| 60 | try set("companionAccountKey", to: NSNull()) |
| 61 | } |
| 62 | companionTransfer = nil |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func transferCompanionSchedule(_ offer: CompanionTransfer, cloud override: (any CompanionScheduleAccess)? = nil) async { |
| 68 | guard !companionLibraryBusy else { return } |
| 69 | await withCompanionSync { |
| 70 | guard companionTransfer == offer else { throw CompanionScheduleError.changed } |
| 71 | let cloud = try override ?? companionCloud() |
| 72 | let account = try await verifiedCompanionAccount(cloud, allowSetup: true) |
| 73 | guard account == offer.accountKey else { throw CompanionScheduleError.accountChanged } |
| 74 | let id = try companionWorkspaceID(create: true) |
| 75 | if override == nil { |
| 76 | try await companionCloud().clearLibrary(workspaceID: offer.previousWorkspace, account: account) |
| 77 | } |
| 78 | try beginCompanionSetup(account: account, pausePosting: true) |
| 79 | let posts = companionPosts() |
| 80 | let published = PublishedPostFeed.entries(in: records) |
| 81 | let schedule = try await cloud.update(workspaceID: offer.previousWorkspace, createIfMissing: false, expectedAccount: account) { |
| 82 | $0 = try $0.transferred(to: id, posts: posts) |
| 83 | try $0.setPublished(published) |
| 84 | } |
| 85 | try applyCompanionCancellations(schedule) |
| 86 | try set("companionSetupPending", to: false) |
| 87 | companionTransfer = nil |
| 88 | companionLastSync = .now |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | func syncCompanion(cloud override: (any CompanionScheduleAccess)? = nil) async { |
| 93 | guard companionSharing, !companionBusy else { return } |
| 94 | await withCompanionSync { |
| 95 | let id = try companionWorkspaceID() |
| 96 | let posts = companionPosts() |
| 97 | let published = PublishedPostFeed.entries(in: records) |
| 98 | let setupPending = companionSetupPending |
| 99 | let cloud = try override ?? companionCloud() |
| 100 | let account = try companionAccountKey() |
| 101 | if setupPending { |
| 102 | if try await offerTransferIfNeeded(to: id, account: account, cloud: cloud) { return } |
| 103 | } |
| 104 | let schedule = try await cloud.update(workspaceID: id, createIfMissing: setupPending, expectedAccount: account) { schedule in |
| 105 | guard schedule.sharing || setupPending else { throw CompanionScheduleError.missing } |
| 106 | var updated = schedule |
| 107 | updated.sharing = true |
| 108 | // The publication lease rules out a local send still owning a claim. |
| 109 | updated.mirror(posts, recoverAbandonedSends: true) |
| 110 | try updated.setPublished(published) |
| 111 | if updated.sharing != schedule.sharing || updated.posts != schedule.posts || |
| 112 | updated.published != schedule.published || updated.hasOlderPublications != schedule.hasOlderPublications || |
| 113 | Date.now.timeIntervalSince(schedule.updatedAt) >= 300 { |
| 114 | schedule = updated |
| 115 | } |
| 116 | } |
| 117 | try applyCompanionCancellations(schedule) |
| 118 | if setupPending { try set("companionSetupPending", to: false) } |
| 119 | companionTransfer = nil |
| 120 | companionLastSync = .now |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// Called while holding the publication lease, before creating the local send receipt. |
| 125 | func claimCompanionPublication(_ draft: WorkspaceRecord, cloud override: (any CompanionScheduleAccess)? = nil) async throws -> CompanionPost? { |
| 126 | guard companionSharing, let post = companionPost(draft) else { return nil } |
| 127 | let id = try companionWorkspaceID() |
| 128 | let cloud = try override ?? companionCloud() |
| 129 | do { |
| 130 | let account = try companionAccountKey() |
| 131 | _ = try await cloud.update(workspaceID: id, createIfMissing: false, expectedAccount: account) { try $0.claim(post) } |
| 132 | return post |
| 133 | } catch CompanionScheduleError.cancelled { |
| 134 | try applyCompanionCancellation(post) |
| 135 | throw CompanionScheduleError.cancelled |
| 136 | } catch { |
| 137 | companionError = error.localizedDescription |
| 138 | throw CompanionScheduleError.cloudUnavailable |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | func releaseCompanionClaim(_ post: CompanionPost) async { |
| 143 | do { |
| 144 | let id = try companionWorkspaceID() |
| 145 | let account = try companionAccountKey() |
| 146 | _ = try await companionCloud().update(workspaceID: id, createIfMissing: false, expectedAccount: account) { schedule in |
| 147 | guard let index = schedule.posts.firstIndex(where: { $0.id == post.id && $0.revision == post.revision }), |
| 148 | schedule.posts[index].state == .sending else { return } |
| 149 | schedule.posts[index].state = post.state |
| 150 | } |
| 151 | } catch { |
| 152 | companionError = error.localizedDescription |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | private func withCompanionSync(_ operation: () async throws -> Void) async { |
| 157 | guard !companionBusy else { return } |
| 158 | companionBusy = true |
| 159 | defer { companionBusy = false } |
| 160 | do { |
| 161 | let lease = try claimPublication() |
| 162 | defer { withExtendedLifetime(lease) {} } |
| 163 | try reload() |
| 164 | try await operation() |
| 165 | companionError = nil |
| 166 | } catch { |
| 167 | companionError = error.localizedDescription |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | func companionCloud() throws -> CloudScheduleStore { |
| 172 | guard CloudScheduleStore.hasEntitlement else { throw CompanionScheduleError.cloudUnavailable } |
| 173 | return CloudScheduleStore() |
| 174 | } |
| 175 | |
| 176 | private var companionSetupPending: Bool { settings["companionSetupPending"] as? Bool == true } |
| 177 | |
| 178 | func companionAccountKey() throws -> String { |
| 179 | guard let account = settings["companionAccountKey"] as? String else { throw CompanionScheduleError.missing } |
| 180 | return account |
| 181 | } |
| 182 | |
| 183 | private func verifiedCompanionAccount(_ cloud: any CompanionScheduleAccess, allowSetup: Bool = false) async throws -> String { |
| 184 | let current = try await cloud.accountKey() |
| 185 | if let saved = settings["companionAccountKey"] as? String { |
| 186 | guard saved == current else { throw CompanionScheduleError.accountChanged } |
| 187 | } else if !allowSetup { |
| 188 | throw CompanionScheduleError.missing |
| 189 | } |
| 190 | return current |
| 191 | } |
| 192 | |
| 193 | private func beginCompanionSetup(account: String, pausePosting: Bool) throws { |
| 194 | try withChanges { |
| 195 | try set("companionAccountKey", to: account) |
| 196 | try set("companionSetupPending", to: true) |
| 197 | try set("companionSharing", to: true) |
| 198 | if pausePosting { try set("autoPost", to: false) } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | private func offerTransferIfNeeded(to id: UUID, account: String, cloud: any CompanionScheduleAccess) async throws -> Bool { |
| 203 | guard let remote = try await cloud.load(confirmedAccount: account), remote.workspaceID != id else { return false } |
| 204 | companionTransfer = CompanionTransfer(previousWorkspace: remote.workspaceID, accountKey: account) |
| 205 | return true |
| 206 | } |
| 207 | |
| 208 | func companionWorkspaceID(create: Bool = false) throws -> UUID { |
| 209 | if let stored = settings["companionWorkspaceID"] as? String, let id = UUID(uuidString: stored) { return id } |
| 210 | guard create else { throw CompanionScheduleError.missing } |
| 211 | let id = UUID() |
| 212 | try set("companionWorkspaceID", to: id.uuidString) |
| 213 | return id |
| 214 | } |
| 215 | |
| 216 | func companionPosts() -> [CompanionPost] { |
| 217 | records.compactMap(companionPost).sorted { $0.scheduledAt == $1.scheduledAt ? $0.id < $1.id : $0.scheduledAt < $1.scheduledAt } |
| 218 | } |
| 219 | |
| 220 | private func companionPost(_ record: WorkspaceRecord) -> CompanionPost? { |
| 221 | let scheduledAt: Date |
| 222 | let state: CompanionPost.State |
| 223 | let revision: String |
| 224 | let channel: String |
| 225 | if record.kind == "draft", ["queued", "due"].contains(record.scheduleStatus), |
| 226 | let slot = record.schedule["slotAt"] as? String, let date = scheduleDate(slot) { |
| 227 | scheduledAt = date |
| 228 | state = record.scheduleStatus == "due" ? .review : .queued |
| 229 | revision = record.schedule["companionRevision"] as? String ?? slot |
| 230 | channel = SocialPlatform(rawValue: record["platform"])?.name ?? record["platform"] |
| 231 | } else if record.kind == "newsletter", ["scheduled", "releasing", "uncertain"].contains(record["state"]), |
| 232 | let date = scheduleDate(record["scheduledAt"]) ?? scheduleDate(record["requestedAt"]) { |
| 233 | scheduledAt = date |
| 234 | state = record["state"] == "scheduled" ? .queued : .review |
| 235 | revision = record["scheduledAt"].isEmpty ? record["requestedAt"] : record["scheduledAt"] |
| 236 | channel = "Substack" |
| 237 | } else { return nil } |
| 238 | let project = projects.first { $0.id == record.projectID }?["name"] ?? "Inkspring" |
| 239 | return CompanionPost(id: record.id, revision: revision, title: String(record.title.prefix(200)), |
| 240 | project: String(project.prefix(200)), channel: channel, scheduledAt: scheduledAt, |
| 241 | state: state, canCancel: record.kind == "draft", lastUpdatedAt: scheduleDate(record["updatedAt"])) |
| 242 | } |
| 243 | |
| 244 | private func applyCompanionCancellations(_ schedule: CompanionSchedule) throws { |
| 245 | for post in schedule.posts where post.state == .cancelled { |
| 246 | try applyCompanionCancellation(post) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | private func applyCompanionCancellation(_ post: CompanionPost) throws { |
| 251 | try withChanges { |
| 252 | guard var draft = records.first(where: { $0.id == post.id && $0.kind == "draft" }), |
| 253 | companionPost(draft)?.revision == post.revision else { return } |
| 254 | var schedule = draft.schedule |
| 255 | schedule["slotAt"] = "" |
| 256 | schedule["status"] = "ready" |
| 257 | schedule["error"] = "Cancelled from a mobile device." |
| 258 | draft.fields["schedule"] = schedule |
| 259 | try save(draft) |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | struct CompanionSyncSettings: View { |
| 265 | let workspace: Workspace |
| 266 | @State private var confirming = false |
| 267 | @State private var confirmingTransfer: CompanionTransfer? |
| 268 | |
| 269 | var body: some View { |
| 270 | GroupBox { |
| 271 | VStack(alignment: .leading, spacing: 9) { |
| 272 | Text("Sync upcoming posts to Inkspring on iPhone and iPad using your private iCloud account. Titles, projects, platforms, and scheduled times appear there.") |
| 273 | .foregroundStyle(.secondary) |
| 274 | if !CloudScheduleStore.hasEntitlement { |
| 275 | Text("This build needs iCloud provisioning to connect a mobile device.").font(.caption).foregroundStyle(.secondary) |
| 276 | } else { |
| 277 | HStack { |
| 278 | if let transfer = workspace.companionTransfer { |
| 279 | Button("Use this Mac for mobile sync…") { confirmingTransfer = transfer } |
| 280 | Button("Check again") { Task { await workspace.setCompanionSharing(true) } } |
| 281 | } else if workspace.companionSharing { |
| 282 | Button("Sync now") { Task { await workspace.syncCompanion() } } |
| 283 | Button("Turn off sync…") { confirming = true } |
| 284 | } else { |
| 285 | Button("Turn on schedule sync") { Task { await workspace.setCompanionSharing(true) } } |
| 286 | } |
| 287 | if workspace.companionBusy { ProgressView().controlSize(.small) } |
| 288 | } |
| 289 | .disabled(workspace.companionBusy || workspace.companionLibraryBusy) |
| 290 | } |
| 291 | if workspace.companionSharing, let date = workspace.companionLastSync { |
| 292 | Text("Last synced \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption) |
| 293 | } |
| 294 | if workspace.companionTransfer != nil { |
| 295 | Text("Another Mac workspace manages mobile sync. Transfer it here to reconnect.") |
| 296 | .font(.caption).foregroundStyle(.secondary) |
| 297 | } |
| 298 | if let error = workspace.companionError { Text(error).font(.caption).foregroundStyle(.red) } |
| 299 | if workspace.companionSharing, workspace.companionTransfer == nil { |
| 300 | StudioRule() |
| 301 | Text("Library sync shares recent drafts, ideas, and review notes with Inkspring on your iPhone and iPad through private iCloud.") |
| 302 | .foregroundStyle(.secondary) |
| 303 | HStack { |
| 304 | if workspace.companionLibrarySharing { |
| 305 | Button("Sync library now") { Task { await workspace.syncCompanionLibrary() } } |
| 306 | } |
| 307 | Button(workspace.companionLibrarySharing ? "Turn off library sync" : "Turn on library sync") { |
| 308 | Task { await workspace.setCompanionLibrarySharing(!workspace.companionLibrarySharing) } |
| 309 | } |
| 310 | if workspace.companionLibraryBusy { ProgressView().controlSize(.small) } |
| 311 | } |
| 312 | .disabled(workspace.companionLibraryBusy || workspace.companionBusy) |
| 313 | if let error = workspace.companionLibraryError { Text(error).font(.caption).foregroundStyle(.red) } |
| 314 | } |
| 315 | } |
| 316 | .frame(maxWidth: .infinity, alignment: .leading) |
| 317 | } label: { |
| 318 | Label("iPhone and iPad", systemImage: "iphone") |
| 319 | } |
| 320 | .confirmationDialog("Turn off mobile sync?", isPresented: $confirming) { |
| 321 | Button("Turn off sync", role: .destructive) { Task { await workspace.setCompanionSharing(false) } } |
| 322 | } message: { |
| 323 | Text("This also turns off library sync and clears shared copies and pending changes from iCloud.") |
| 324 | } |
| 325 | .confirmationDialog("Move mobile sync to this Mac?", isPresented: Binding( |
| 326 | get: { confirmingTransfer != nil }, set: { if !$0 { confirmingTransfer = nil } } |
| 327 | ), presenting: confirmingTransfer) { transfer in |
| 328 | Button("Use this Mac") { Task { await workspace.transferCompanionSchedule(transfer) } } |
| 329 | } message: { _ in |
| 330 | Text("The iPhone schedule will come from this workspace. Automatic posting on this Mac will be paused so you can review the schedule.") |
| 331 | } |
| 332 | } |
| 333 | } |