Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / PostScheduling.swift
| 1 | import Foundation |
| 2 | import InkspringSchedule |
| 3 | |
| 4 | struct ScheduleListing { |
| 5 | enum Section: String, CaseIterable, Identifiable { |
| 6 | case ready = "Ready to schedule" |
| 7 | case scheduled = "Scheduled" |
| 8 | case history = "Published" |
| 9 | |
| 10 | var id: Self { self } |
| 11 | } |
| 12 | |
| 13 | private let sections: [Section: [WorkspaceRecord]] |
| 14 | |
| 15 | init(records: [WorkspaceRecord], projectID: String? = nil, channel: String? = nil) { |
| 16 | let matching = records.filter { item in |
| 17 | (item.kind == "draft" || item.kind == "newsletter") && |
| 18 | (projectID == nil || item.projectID == projectID) && |
| 19 | (channel == nil || Self.channel(of: item) == channel) |
| 20 | } |
| 21 | let grouped = Dictionary(grouping: matching) { Self.section(for: $0) } |
| 22 | sections = Dictionary(uniqueKeysWithValues: Section.allCases.map { section in |
| 23 | let sorted = (grouped[section] ?? []).sorted { first, second in |
| 24 | let fallback: Date = section == .scheduled ? .distantFuture : .distantPast |
| 25 | let left = Self.date(for: first, in: section) ?? fallback |
| 26 | let right = Self.date(for: second, in: section) ?? fallback |
| 27 | if left == right { return first.id < second.id } |
| 28 | return section == .scheduled ? left < right : left > right |
| 29 | } |
| 30 | return (section, sorted) |
| 31 | }) |
| 32 | } |
| 33 | |
| 34 | subscript(section: Section) -> [WorkspaceRecord] { sections[section] ?? [] } |
| 35 | |
| 36 | static func channel(of item: WorkspaceRecord) -> String { |
| 37 | item.kind == "newsletter" ? "substack" : item["platform"] |
| 38 | } |
| 39 | |
| 40 | static func section(for item: WorkspaceRecord) -> Section? { |
| 41 | if item.kind == "newsletter" { |
| 42 | switch item["state"] { |
| 43 | case "scheduled", "releasing": return .scheduled |
| 44 | case "uncertain": return item["scheduledAt"].isEmpty ? .history : .scheduled |
| 45 | case "published": return .history |
| 46 | case "draft", "synced", "syncing": return .ready |
| 47 | default: return nil |
| 48 | } |
| 49 | } |
| 50 | guard item.kind == "draft" else { return nil } |
| 51 | switch item.scheduleStatus { |
| 52 | case "queued", "due": return .scheduled |
| 53 | case "posting": return (item.schedule["slotAt"] as? String).flatMap(scheduleDate) == nil ? nil : .scheduled |
| 54 | case "posted", "skipped": return .history |
| 55 | case "ready", "failed", "removed", "manual": return .ready |
| 56 | default: return nil |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | static func date(for item: WorkspaceRecord, in section: Section) -> Date? { |
| 61 | if item.kind == "newsletter" { |
| 62 | if section == .scheduled { return scheduleDate(item["scheduledAt"]) ?? scheduleDate(item["requestedAt"]) } |
| 63 | return scheduleDate(item["publishedAt"]) ?? scheduleDate(item["updatedAt"]) |
| 64 | } |
| 65 | if section == .scheduled { return (item.schedule["slotAt"] as? String).flatMap(scheduleDate) } |
| 66 | let key = section == .ready ? "pickedAt" : item.scheduleStatus == "posted" ? "postedAt" : "skippedAt" |
| 67 | return (item.schedule[key] as? String).flatMap(scheduleDate) ?? scheduleDate(item["updatedAt"]) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | struct PostResultNotice: Equatable { |
| 72 | let draftID: String |
| 73 | let message: String |
| 74 | |
| 75 | init?(_ result: WorkspaceRecord) { |
| 76 | switch result.kind { |
| 77 | case "publication" where result["status"] == "published" && !result["draftId"].isEmpty: |
| 78 | draftID = result["draftId"] |
| 79 | message = "Published on \(platformName(result["platform"]))" |
| 80 | case "draft" where result.scheduleStatus == "queued": |
| 81 | draftID = result.id |
| 82 | message = "Post scheduled" |
| 83 | case "newsletter" where result["state"] == "published" || result["state"] == "scheduled": |
| 84 | draftID = result.id |
| 85 | message = result["state"] == "published" ? "Newsletter published" : "Newsletter scheduled" |
| 86 | default: |
| 87 | return nil |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | enum PublishedPostFeed { |
| 93 | static func entries(in records: [WorkspaceRecord], projectID: String? = nil, |
| 94 | channel: String? = nil) -> [CompanionPublication] { |
| 95 | let projects = Dictionary(records.filter { $0.kind == "project" }.map { ($0.id, $0.title) }, |
| 96 | uniquingKeysWith: { first, _ in first }) |
| 97 | let draftsByID = Dictionary(records.filter { $0.kind == "draft" }.map { ($0.id, $0) }, |
| 98 | uniquingKeysWith: { first, _ in first }) |
| 99 | var entries: [String: CompanionPublication] = [:] |
| 100 | for receipt in records where receipt.kind == "publication" |
| 101 | && (projectID == nil || receipt.projectID == projectID) { |
| 102 | let platform = receipt["platform"] |
| 103 | guard !platform.isEmpty, channel == nil || channel == platform else { continue } |
| 104 | let steps = receipt.fields["steps"] as? [[String: Any]] ?? [] |
| 105 | let complete = receipt["status"] == "published" |
| 106 | guard complete || !steps.isEmpty && ["partial", "publishing", "uncertain"].contains(receipt["status"]), |
| 107 | let date = scheduleDate(receipt["publishedAt"]) |
| 108 | ?? (steps.first?["at"] as? String).flatMap(scheduleDate) |
| 109 | ?? scheduleDate(receipt["updatedAt"]) else { continue } |
| 110 | let id = receipt["draftId"].isEmpty ? receipt.id : receipt["draftId"] |
| 111 | let links = steps.compactMap { ($0["url"] as? String).flatMap(CompanionPublication.postURL) } |
| 112 | if let existing = entries[id] { |
| 113 | if !existing.incomplete && !complete { continue } |
| 114 | if existing.incomplete == !complete && existing.publishedAt >= date { continue } |
| 115 | } |
| 116 | entries[id] = CompanionPublication(id: id, title: receipt.title, project: projects[receipt.projectID] ?? "Inkspring", |
| 117 | channel: platform, publishedAt: date, links: links, incomplete: !complete, |
| 118 | lastUpdatedAt: draftsByID[id].flatMap { scheduleDate($0["updatedAt"]) } |
| 119 | ?? scheduleDate(receipt["updatedAt"])) |
| 120 | } |
| 121 | for item in records where projectID == nil || item.projectID == projectID { |
| 122 | let platform = ScheduleListing.channel(of: item) |
| 123 | guard channel == nil || channel == platform else { continue } |
| 124 | let date: Date? |
| 125 | let address: String |
| 126 | if item.kind == "newsletter", item["state"] == "published" { |
| 127 | date = scheduleDate(item["publishedAt"]) ?? scheduleDate(item["updatedAt"]) |
| 128 | address = item["postUrl"] |
| 129 | } else if item.kind == "draft", item.scheduleStatus == "posted" { |
| 130 | date = ScheduleListing.date(for: item, in: .history) |
| 131 | address = item.schedule["url"] as? String ?? "" |
| 132 | } else if item.kind == "article", item.isPublishedContent { |
| 133 | date = scheduleDate(item["articlePublishedAt"]) ?? scheduleDate(item["updatedAt"]) |
| 134 | address = item["articleURL"] |
| 135 | } else { continue } |
| 136 | guard let date else { continue } |
| 137 | let link = CompanionPublication.postURL(address) |
| 138 | if let existing = entries[item.id], !existing.links.isEmpty || link == nil { continue } |
| 139 | entries[item.id] = CompanionPublication(id: item.id, title: item.title, project: projects[item.projectID] ?? "Inkspring", |
| 140 | channel: platform, publishedAt: date, links: link.map { [$0] } ?? [], |
| 141 | lastUpdatedAt: scheduleDate(item["updatedAt"])) |
| 142 | } |
| 143 | return entries.values.sorted { first, second in |
| 144 | first.publishedAt == second.publishedAt ? first.id < second.id : first.publishedAt > second.publishedAt |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | enum PostScheduling { |
| 150 | struct PostingHour: Identifiable { |
| 151 | let start: Date |
| 152 | let end: Date |
| 153 | let post: WorkspaceRecord? |
| 154 | |
| 155 | var id: Date { start } |
| 156 | } |
| 157 | |
| 158 | private static let xHours = [9, 11, 13, 15, 17] |
| 159 | private static let visibleStates = ["queued", "due", "posting", "posted"] |
| 160 | static let leadTime: TimeInterval = 120 |
| 161 | |
| 162 | static func fiveMinutesFromNow(_ now: Date = .now) -> Date { |
| 163 | let target = now.addingTimeInterval(5 * 60) |
| 164 | return Date(timeIntervalSince1970: ceil(target.timeIntervalSince1970 / 60) * 60) |
| 165 | } |
| 166 | |
| 167 | static func startOfMinute(_ date: Date) -> Date { |
| 168 | Date(timeIntervalSince1970: floor(date.timeIntervalSince1970 / 60) * 60) |
| 169 | } |
| 170 | |
| 171 | static func xPostingHours(on day: Date, in records: [WorkspaceRecord], |
| 172 | calendar: Calendar = .current) -> [PostingHour] { |
| 173 | let draft = WorkspaceRecord(kind: "draft", fields: ["platform": "x"]) |
| 174 | return xHours.compactMap { hour in |
| 175 | guard let time = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day), |
| 176 | let interval = calendar.dateInterval(of: .hour, for: time) else { return nil } |
| 177 | let post = occupyingPost(time, for: draft, in: records, calendar: calendar, linkedInPersonalURN: nil) |
| 178 | return PostingHour(start: interval.start, end: interval.end, post: post) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | static func proposedTimes(for draft: WorkspaceRecord, in records: [WorkspaceRecord], |
| 183 | now: Date = .now, calendar: Calendar = .current, linkedInPersonalURN: String? = nil, |
| 184 | window: CompanionPostingWindow? = nil) -> [Date] { |
| 185 | let hours = window.map { Array($0.hours) } ?? { |
| 186 | switch draft["platform"] { |
| 187 | case "linkedin": [9] |
| 188 | case "instagram": [13] |
| 189 | default: xHours |
| 190 | } |
| 191 | }() |
| 192 | var dates: [Date] = [] |
| 193 | for offset in 0..<60 { |
| 194 | guard dates.count < 8, let day = calendar.date(byAdding: .day, value: offset, to: now) else { break } |
| 195 | if draft["platform"] == "linkedin" && calendar.isDateInWeekend(day) { continue } |
| 196 | for hour in hours where dates.count < 8 { |
| 197 | if let date = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day), |
| 198 | date > now.addingTimeInterval(leadTime), |
| 199 | isFree(date, for: draft, in: records, calendar: calendar, linkedInPersonalURN: linkedInPersonalURN) { dates.append(date) } |
| 200 | } |
| 201 | } |
| 202 | return dates |
| 203 | } |
| 204 | |
| 205 | static func isFree(_ time: Date, for draft: WorkspaceRecord, in records: [WorkspaceRecord], |
| 206 | calendar: Calendar = .current, linkedInPersonalURN: String? = nil, customTime: Bool = false) -> Bool { |
| 207 | occupyingPost(time, for: draft, in: records, calendar: calendar, linkedInPersonalURN: linkedInPersonalURN, |
| 208 | customTime: customTime) == nil |
| 209 | } |
| 210 | |
| 211 | private static func occupyingPost(_ time: Date, for draft: WorkspaceRecord, in records: [WorkspaceRecord], |
| 212 | calendar: Calendar, linkedInPersonalURN: String?, customTime: Bool = false) -> WorkspaceRecord? { |
| 213 | let platform = draft["platform"] |
| 214 | let interval: Calendar.Component |
| 215 | if customTime && ["x", "linkedin"].contains(platform) { |
| 216 | interval = .minute |
| 217 | } else { |
| 218 | interval = ["x", "tiktok"].contains(platform) ? .hour : .day |
| 219 | } |
| 220 | let urn = (draft.fields["linkedinDestination"] as? [String: Any])?["urn"] as? String ?? linkedInPersonalURN |
| 221 | return records.first { other in |
| 222 | guard other.kind == "draft", other.id != draft.id, other["platform"] == platform, |
| 223 | visibleStates.contains(other.scheduleStatus), |
| 224 | let value = (other.schedule["postedAt"] as? String).flatMap(scheduleDate) |
| 225 | ?? (other.schedule["slotAt"] as? String).flatMap(scheduleDate) else { return false } |
| 226 | if platform == "linkedin" { |
| 227 | let otherURN = (other.fields["linkedinDestination"] as? [String: Any])?["urn"] as? String ?? linkedInPersonalURN |
| 228 | if let urn, let otherURN, urn != otherURN { return false } |
| 229 | } |
| 230 | return calendar.isDate(time, equalTo: value, toGranularity: interval) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | static func parseLocalHour(_ value: String) -> Date? { |
| 235 | if let exact = scheduleDate(value) { return exact } |
| 236 | guard value.range(of: #"\A[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}\z"#, |
| 237 | options: .regularExpression) != nil else { return nil } |
| 238 | let parser = DateFormatter() |
| 239 | parser.calendar = Calendar(identifier: .gregorian) |
| 240 | parser.locale = Locale(identifier: "en_US_POSIX") |
| 241 | parser.timeZone = .current |
| 242 | parser.dateFormat = "yyyy-MM-dd'T'HH:mm" |
| 243 | guard let date = parser.date(from: value), parser.string(from: date) == value else { return nil } |
| 244 | return date |
| 245 | } |
| 246 | |
| 247 | static func date(hour: Date, minute: Int?, now: Date = .now, calendar: Calendar = .current) throws -> Date { |
| 248 | guard let start = calendar.dateInterval(of: .hour, for: hour)?.start, |
| 249 | minute == nil || (0...59).contains(minute ?? 0) else { |
| 250 | throw WorkspaceError("Choose a posting minute from 00 through 59.") |
| 251 | } |
| 252 | let options = minute.map { [$0] } ?? (7...55).filter { $0 % 5 != 0 } |
| 253 | let available = options.compactMap { calendar.date(byAdding: .minute, value: $0, to: start) } |
| 254 | .filter { $0 > now.addingTimeInterval(leadTime) } |
| 255 | guard let result = available.randomElement() else { throw WorkspaceError("Choose a posting time in the future.") } |
| 256 | return result |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | extension Workspace { |
| 261 | func postingWindow(for platform: String) -> CompanionPostingWindow { |
| 262 | let values = settings["postingWindows"] as? [String: [String: Int]] ?? [:] |
| 263 | let value = values[platform] |
| 264 | return CompanionPostingWindow(firstHour: value?["firstHour"] ?? 9, lastHour: value?["lastHour"] ?? 17) |
| 265 | } |
| 266 | |
| 267 | func postingMinute(for platform: String) -> Int { |
| 268 | let values = settings["postingWindows"] as? [String: [String: Int]] ?? [:] |
| 269 | let minute = values[platform]?["minute"] ?? -1 |
| 270 | return (-1...59).contains(minute) ? minute : -1 |
| 271 | } |
| 272 | |
| 273 | func setPostingPreferences(for platform: String, window: CompanionPostingWindow, minute: Int) throws { |
| 274 | try withChanges { |
| 275 | var values = settings["postingWindows"] as? [String: [String: Int]] ?? [:] |
| 276 | values[platform] = ["firstHour": window.firstHour, "lastHour": window.lastHour, "minute": minute] |
| 277 | try set("postingWindows", to: values) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | func preferredPostingDate(for platform: String, hour: Date, minute: Int) throws -> Date { |
| 282 | guard postingWindow(for: platform).hours.contains(Calendar.current.component(.hour, from: hour)) else { |
| 283 | throw WorkspaceError("Choose an hour within this platform’s preferred posting hours in Mac Settings.") |
| 284 | } |
| 285 | return try PostScheduling.date(hour: hour, minute: minute < 0 ? nil : minute) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | extension Workspace { |
| 290 | func runDuePosts(publisher override: SocialPublisher? = nil, now: Date = .now, |
| 291 | notify: @MainActor (ScheduleReminder) async -> Void = ScheduleNotifications.deliver) async { |
| 292 | guard !runningDuePosts, settings["autoPost"] as? Bool == true else { return } |
| 293 | runningDuePosts = true |
| 294 | defer { runningDuePosts = false } |
| 295 | let publisher = override ?? SocialPublisher(workspace: self) |
| 296 | func remind(_ draft: WorkspaceRecord, _ reason: ScheduleReminder.Reason) async { |
| 297 | if settings[ScheduleNotifications.settingKey] as? Bool == true { |
| 298 | await notify(ScheduleReminder(draft, reason: reason)) |
| 299 | } |
| 300 | } |
| 301 | let due = records.compactMap { draft -> (WorkspaceRecord, Date)? in |
| 302 | guard draft.kind == "draft", draft.scheduleStatus == "queued", |
| 303 | let slot = (draft.schedule["slotAt"] as? String).flatMap(scheduleDate), slot <= now else { return nil } |
| 304 | return (draft, slot) |
| 305 | }.sorted { $0.1 < $1.1 } |
| 306 | for (draft, slot) in due { |
| 307 | if Task.isCancelled { return } |
| 308 | guard settings["autoPost"] as? Bool == true else { return } |
| 309 | let platform = draft["platform"] |
| 310 | if ["instagram", "reddit"].contains(platform) { |
| 311 | if (try? updateDueDraft(draft, state: "due", error: "This post is ready for review and publishing.")) == true { |
| 312 | await remind(draft, .review) |
| 313 | } |
| 314 | continue |
| 315 | } |
| 316 | if now.timeIntervalSince(slot) > 10_800 { |
| 317 | if (try? updateDueDraft(draft, state: "failed", error: "Inkspring missed the posting time. Schedule again or review to publish now.")) == true { |
| 318 | await remind(draft, .check) |
| 319 | } |
| 320 | continue |
| 321 | } |
| 322 | do { |
| 323 | if platform == "x" { |
| 324 | let posts = ["followup", "thread"].contains(draft["format"]) ? XThreadText.posts(in: draft.body) : [draft.body] |
| 325 | let links = try XPostArticleLinks(draft: draft, posts: posts, records: records) |
| 326 | if links.articles.contains(where: { $0["state"] != "published" }), |
| 327 | let pair = try await publisher.reviewXArticlePost(draft) { |
| 328 | _ = try await publisher.publishXArticlePost(pair, automatic: true) |
| 329 | continue |
| 330 | } |
| 331 | } |
| 332 | if platform == "linkedin", |
| 333 | LinkedInDestination(fields: draft.fields["linkedinDestination"] as? [String: Any]) == nil { |
| 334 | throw WorkspaceError("Choose a LinkedIn destination and schedule this post again.") |
| 335 | } |
| 336 | var options = SocialPublishOptions() |
| 337 | var expectedAccount: String? |
| 338 | if platform == "tiktok" { |
| 339 | guard let consent = records.first(where: { |
| 340 | $0.kind == "tiktok-consent" && $0["draftId"] == draft.id && $0["draftRevision"] == draft["updatedAt"] |
| 341 | && $0["slotAt"] == draft.schedule["slotAt"] as? String |
| 342 | }), let raw = consent.fields["options"] else { |
| 343 | throw WorkspaceError("Review this TikTok post and choose a time again.") |
| 344 | } |
| 345 | let data = try JSONSerialization.data(withJSONObject: raw) |
| 346 | options.tiktok = try JSONDecoder().decode(TikTokReviewOptions.self, from: data) |
| 347 | options.imageURL = consent["imageURL"] |
| 348 | expectedAccount = consent["accountId"] |
| 349 | } |
| 350 | let review = try await publisher.review(draft, options: options) |
| 351 | if let expectedAccount, review.accountID != expectedAccount { |
| 352 | throw WorkspaceError("The TikTok account changed. Review and schedule again.") |
| 353 | } |
| 354 | guard settings["autoPost"] as? Bool == true else { return } |
| 355 | _ = try await publisher.publish(review, automatic: true) |
| 356 | } catch is CompanionScheduleError { |
| 357 | continue |
| 358 | } catch is PublicationLeaseBusy { |
| 359 | continue |
| 360 | } catch { |
| 361 | if settings["autoPost"] as? Bool != true { return } |
| 362 | let changed = (try? updateDueDraft(draft, state: "failed", error: error.localizedDescription)) == true |
| 363 | let failedDuringSend = records.contains { row in |
| 364 | row.kind == "draft" && row.id == draft.id && row.scheduleStatus == "failed" |
| 365 | && row.schedule["slotAt"] as? String == draft.schedule["slotAt"] as? String |
| 366 | } |
| 367 | if changed || failedDuringSend { await remind(draft, .check) } |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | private func updateDueDraft(_ input: WorkspaceRecord, state: String, error: String) throws -> Bool { |
| 373 | try reload() |
| 374 | guard var draft = records.first(where: { $0.id == input.id && $0.kind == "draft" }), |
| 375 | draft.scheduleStatus == "queued", draft["updatedAt"] == input["updatedAt"] else { return false } |
| 376 | var schedule = draft.schedule |
| 377 | schedule["status"] = state |
| 378 | schedule["error"] = error |
| 379 | draft.fields["schedule"] = schedule |
| 380 | try save(draft) |
| 381 | return true |
| 382 | } |
| 383 | } |