Branchwell

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

Raw 8.5 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import Foundation
2
3public struct CompanionPost: Codable, Equatable, Identifiable, Sendable {
4 public enum State: String, Codable, Sendable {
5 case queued, review, cancelled, sending
6 }
7
8 public let id: String
9 public let revision: String
10 public let title: String
11 public let project: String
12 public let channel: String
13 public let scheduledAt: Date
14 public let lastUpdatedAt: Date?
15 public var state: State
16 public let canCancel: Bool
17
18 public init(id: String, revision: String, title: String, project: String, channel: String,
19 scheduledAt: Date, state: State, canCancel: Bool, lastUpdatedAt: Date? = nil) {
20 self.id = id
21 self.revision = revision
22 self.title = title
23 self.project = project
24 self.channel = channel
25 self.scheduledAt = scheduledAt
26 self.lastUpdatedAt = lastUpdatedAt
27 self.state = state
28 self.canCancel = canCancel
29 }
30}
31
32public struct CompanionPublication: Codable, Equatable, Identifiable, Sendable {
33 public let id: String
34 public let title: String
35 public let project: String
36 public let channel: String
37 public let publishedAt: Date
38 public let lastUpdatedAt: Date?
39 public let links: [URL]
40 public let incomplete: Bool
41
42 public init(id: String, title: String, project: String, channel: String, publishedAt: Date, links: [URL],
43 incomplete: Bool = false, lastUpdatedAt: Date? = nil) {
44 self.id = id
45 self.title = title
46 self.project = project
47 self.channel = channel
48 self.publishedAt = publishedAt
49 self.lastUpdatedAt = lastUpdatedAt
50 self.links = links
51 self.incomplete = incomplete
52 }
53
54 public var channelName: String {
55 ["x": "X", "linkedin": "LinkedIn", "reddit": "Reddit", "instagram": "Instagram",
56 "tiktok": "TikTok", "substack": "Substack"][channel] ?? channel.capitalized
57 }
58
59 public static func postURL(_ address: String) -> URL? {
60 guard address.utf8.count <= 2_000, let url = URL(string: address), url.scheme == "https",
61 let host = url.host(), !host.isEmpty, url.user == nil, url.password == nil, url.port == nil else { return nil }
62 return url
63 }
64}
65
66public struct CompanionSchedule: Codable, Equatable, Sendable {
67 static let maxEncodedSize = 512_000
68 public let workspaceID: UUID
69 public var sharing: Bool
70 public var updatedAt: Date
71 public var posts: [CompanionPost]
72 public var published: [CompanionPublication]?
73 public private(set) var hasOlderPublications: Bool?
74
75 public init(workspaceID: UUID, sharing: Bool = true, updatedAt: Date = .now, posts: [CompanionPost],
76 published: [CompanionPublication]? = nil) {
77 self.workspaceID = workspaceID
78 self.sharing = sharing
79 self.updatedAt = updatedAt
80 self.posts = posts
81 self.published = published
82 }
83
84 public mutating func setPublished(_ entries: [CompanionPublication]) throws {
85 published = entries
86 hasOlderPublications = false
87 let encoder = JSONEncoder()
88 guard try encoder.encode(self).count >= Self.maxEncodedSize else { return }
89 // Keep the schedule writable even when the history exceeds the snapshot budget.
90 var lower = 0
91 var upper = entries.count
92 hasOlderPublications = true
93 while lower < upper {
94 let count = (lower + upper + 1) / 2
95 published = Array(entries.prefix(count))
96 if try encoder.encode(self).count < Self.maxEncodedSize {
97 lower = count
98 } else {
99 upper = count - 1
100 }
101 }
102 published = Array(entries.prefix(lower))
103 }
104
105 public mutating func cancel(_ post: CompanionPost) throws {
106 guard sharing else { throw CompanionScheduleError.missing }
107 guard let index = posts.firstIndex(where: { $0.id == post.id && $0.revision == post.revision }),
108 posts[index].canCancel else { throw CompanionScheduleError.changed }
109 switch posts[index].state {
110 case .cancelled: return
111 case .queued, .review: posts[index].state = .cancelled
112 case .sending: throw CompanionScheduleError.sending
113 }
114 }
115
116 public mutating func claim(_ post: CompanionPost) throws {
117 guard sharing else { throw CompanionScheduleError.missing }
118 if let index = posts.firstIndex(where: { $0.id == post.id && $0.revision == post.revision }) {
119 guard posts[index].state != .cancelled else { throw CompanionScheduleError.cancelled }
120 guard posts[index].state != .sending else { throw CompanionScheduleError.sending }
121 posts[index].state = .sending
122 } else {
123 posts.removeAll { $0.id == post.id }
124 var claimed = post
125 claimed.state = .sending
126 posts.append(claimed)
127 }
128 }
129
130 public mutating func mirror(_ local: [CompanionPost], now: Date = .now, recoverAbandonedSends: Bool = false) {
131 let previous = Dictionary(posts.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
132 posts = local.map { post in
133 guard let current = previous[post.id], current.revision == post.revision,
134 current.state == .cancelled || current.state == .sending && !recoverAbandonedSends else { return post }
135 return current
136 }
137 updatedAt = now
138 }
139
140 public func transferred(to newWorkspace: UUID, posts local: [CompanionPost], now: Date = .now) throws -> CompanionSchedule {
141 guard newWorkspace != workspaceID else { throw CompanionScheduleError.changed }
142 guard !posts.contains(where: { $0.state == .sending }) else { throw CompanionScheduleError.sending }
143 var replacement = CompanionSchedule(workspaceID: newWorkspace, sharing: true, updatedAt: now, posts: posts)
144 replacement.mirror(local, now: now)
145 return replacement
146 }
147}
148
149public enum CompanionScheduleError: LocalizedError, Equatable {
150 case changed, cancelled, sending, missing, anotherMac, accountChanged, cloudUnavailable, cloudTemporarilyUnavailable, oversized
151
152 public var errorDescription: String? {
153 switch self {
154 case .changed: "This schedule changed. Refresh it and try again."
155 case .cancelled: "This post was cancelled from the iPhone."
156 case .sending: "Inkspring on Mac has already started sending this post."
157 case .missing: "Enable iPhone schedule sync in Inkspring on your Mac."
158 case .anotherMac: "A different Inkspring workspace manages the schedule on this Apple Account."
159 case .accountChanged: "Switch back to the Apple Account that set up iPhone schedule sync."
160 case .cloudUnavailable: "Sign in to iCloud and check that Inkspring can use iCloud on this device."
161 case .cloudTemporarilyUnavailable: "iCloud is temporarily unavailable. Check again when it reconnects."
162 case .oversized: "There are too many upcoming posts to sync."
163 }
164 }
165}
166
167struct CompanionScheduleViewState {
168 enum Operation { case refresh, cancel }
169
170 private(set) var schedule: CompanionSchedule?
171 private(set) var account: String?
172 private(set) var error: String?
173 private var operation: Operation?
174 private var request: UUID?
175 private var loaded = false
176
177 var busy: Bool { request != nil }
178 var loading: Bool { !loaded || operation == .refresh }
179 var canCancel: Bool { schedule != nil && account != nil && error == nil && !busy }
180
181 mutating func begin(_ operation: Operation) -> UUID? {
182 guard !busy, operation != .cancel || canCancel else { return nil }
183 let token = UUID()
184 self.operation = operation
185 request = token
186 return token
187 }
188
189 func isCurrent(_ token: UUID) -> Bool { request == token }
190
191 mutating func confirmAccount(_ newAccount: String, for token: UUID) -> Bool {
192 guard isCurrent(token) else { return false }
193 if account != newAccount { schedule = nil }
194 account = newAccount
195 return true
196 }
197
198 mutating func complete(_ snapshot: CompanionSchedule?, for token: UUID) {
199 guard isCurrent(token) else { return }
200 schedule = snapshot?.sharing == true ? snapshot : nil
201 error = nil
202 finish()
203 }
204
205 mutating func fail(_ message: String, keepSchedule: Bool, for token: UUID) {
206 guard isCurrent(token) else { return }
207 if !keepSchedule {
208 schedule = nil
209 account = nil
210 }
211 error = message
212 finish()
213 }
214
215 private mutating func finish() {
216 loaded = true
217 request = nil
218 operation = nil
219 }
220}