Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / InkspringApp.swift
| 1 | import AppKit |
| 2 | import Foundation |
| 3 | import SwiftUI |
| 4 | import UserNotifications |
| 5 | |
| 6 | @main |
| 7 | enum InkspringMain { |
| 8 | @MainActor |
| 9 | static func main() { |
| 10 | if CommandLine.arguments.dropFirst() == ["--daily-backup"] { |
| 11 | do { |
| 12 | try DailyBackup.run(in: DailyBackup.directory()) |
| 13 | } catch { |
| 14 | FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)) |
| 15 | exit(EXIT_FAILURE) |
| 16 | } |
| 17 | } else if CommandLine.arguments.dropFirst() == ["--refresh-daily-backup-registration"] { |
| 18 | Task { @MainActor in |
| 19 | do { |
| 20 | let updated = try await DailyBackup.refreshRegistration(in: DailyBackup.directory()) |
| 21 | print(updated ? "Daily backup helper re-registered." : "No change to the daily backup registration.") |
| 22 | exit(EXIT_SUCCESS) |
| 23 | } catch { |
| 24 | FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)) |
| 25 | exit(EXIT_FAILURE) |
| 26 | } |
| 27 | } |
| 28 | dispatchMain() |
| 29 | } else if CommandLine.arguments.dropFirst() == ["--mcp"] || |
| 30 | (CommandLine.arguments.count == 3 && ["--mcp-chat", "--mcp-write"].contains(CommandLine.arguments[1])) { |
| 31 | do { |
| 32 | let directory = try DailyBackup.directory() |
| 33 | guard FileManager.default.fileExists(atPath: directory.appending(path: "workspace.sqlite").path) else { |
| 34 | throw WorkspaceError("Open Inkspring before connecting your agent.") |
| 35 | } |
| 36 | let workspace = Workspace(directory: directory) |
| 37 | if let error = workspace.startupError { throw WorkspaceError(error) } |
| 38 | Task { @MainActor in |
| 39 | let chat = CommandLine.arguments.count == 3 && CommandLine.arguments[1] == "--mcp-chat" |
| 40 | let writing = CommandLine.arguments.count == 3 && CommandLine.arguments[1] == "--mcp-write" |
| 41 | await AgentMCP(workspace: workspace, chatProjectID: chat ? CommandLine.arguments[2] : nil, |
| 42 | generationContext: writing ? URL(fileURLWithPath: CommandLine.arguments[2]) : nil).run() |
| 43 | exit(EXIT_SUCCESS) |
| 44 | } |
| 45 | dispatchMain() |
| 46 | } catch { |
| 47 | FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)) |
| 48 | exit(EXIT_FAILURE) |
| 49 | } |
| 50 | } else if CommandLine.arguments.dropFirst().first == "--stage-workspace" { |
| 51 | let arguments = Array(CommandLine.arguments.dropFirst(2)) |
| 52 | guard arguments.count == 2, arguments.allSatisfy({ $0.hasPrefix("/") }) else { |
| 53 | FileHandle.standardError.write(Data("Provide absolute source and destination directories.\n".utf8)) |
| 54 | exit(EXIT_FAILURE) |
| 55 | } |
| 56 | do { |
| 57 | let report = try WorkspaceMigration.stage( |
| 58 | from: URL(fileURLWithPath: arguments[0], isDirectory: true), |
| 59 | to: URL(fileURLWithPath: arguments[1], isDirectory: true) |
| 60 | ) |
| 61 | print("Migrated \(report.records) records, \(report.images) images and \(report.videos) videos.") |
| 62 | } catch { |
| 63 | FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)) |
| 64 | exit(EXIT_FAILURE) |
| 65 | } |
| 66 | } else { |
| 67 | InkspringTypography.registerFonts() |
| 68 | InkspringApp.main() |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | struct InkspringApp: App { |
| 74 | @NSApplicationDelegateAdaptor(WorkspaceLifecycle.self) private var lifecycle |
| 75 | @Environment(\.openWindow) private var openWindow |
| 76 | |
| 77 | private var workspace: Workspace { lifecycle.workspace } |
| 78 | |
| 79 | var body: some Scene { |
| 80 | Window("Inkspring", id: "workspace") { |
| 81 | WorkspaceWindow(workspace: workspace) |
| 82 | .frame(minWidth: 870, minHeight: 660) |
| 83 | .background(WindowTitleHider().allowsHitTesting(false)) |
| 84 | .onAppear { lifecycle.showWorkspace = { openWindow(id: "workspace") } } |
| 85 | } |
| 86 | .windowToolbarStyle(.unified) |
| 87 | .defaultSize(width: 1180, height: 810) |
| 88 | .commands { |
| 89 | CommandGroup(replacing: .help) { |
| 90 | Button("Get App Help") { NSWorkspace.shared.open(InkspringCommunity.support) } |
| 91 | Button("Setup and Troubleshooting") { NSWorkspace.shared.open(InkspringCommunity.websiteHelp) } |
| 92 | Button("Send Feedback") { NSWorkspace.shared.open(InkspringCommunity.feedback) } |
| 93 | } |
| 94 | CommandGroup(after: .appInfo) { |
| 95 | if lifecycle.updates.isConfigured { |
| 96 | Button("Check for Updates…", action: lifecycle.updates.check) |
| 97 | .disabled(!lifecycle.updates.canCheck) |
| 98 | } |
| 99 | } |
| 100 | CommandGroup(after: .newItem) { |
| 101 | Button("Export Backup…") { workspace.exportBackup() } |
| 102 | Button("Import / Restore…") { Task { await workspace.restoreBackup() } } |
| 103 | .disabled(workspace.restoringBackup || workspace.importingWorkspaceFolder) |
| 104 | Button("Import Workspace Folder…") { Task { await workspace.importWorkspaceFolder() } } |
| 105 | .disabled(workspace.restoringBackup || workspace.importingWorkspaceFolder) |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | private struct WindowTitleHider: NSViewRepresentable { |
| 112 | func makeNSView(context: Context) -> TitleView { TitleView() } |
| 113 | func updateNSView(_ view: TitleView, context: Context) { view.window?.titleVisibility = .hidden } |
| 114 | |
| 115 | final class TitleView: NSView { |
| 116 | override func viewDidMoveToWindow() { |
| 117 | super.viewDidMoveToWindow() |
| 118 | window?.titleVisibility = .hidden |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | @MainActor |
| 124 | final class WorkspaceLifecycle: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { |
| 125 | let workspace = Workspace() |
| 126 | let updates = InkspringUpdates() |
| 127 | private var tasks: [Task<Void, Never>] = [] |
| 128 | private var scheduledActivity: NSObjectProtocol? |
| 129 | var showWorkspace: (() -> Void)? |
| 130 | |
| 131 | func applicationDidFinishLaunching(_ notification: Notification) { |
| 132 | updates.start() |
| 133 | workspace.recoverInterruptedPublications() |
| 134 | workspace.recoverInterruptedNewsletters() |
| 135 | let workspace = workspace |
| 136 | repeatEvery(.seconds(2)) { workspace.refreshAfterExternalWrite() } |
| 137 | repeatEvery(.seconds(900)) { await workspace.checkDailyBackup() } |
| 138 | guard !DailyBackup.usesTestWorkspace else { return } |
| 139 | UNUserNotificationCenter.current().delegate = self |
| 140 | tasks.append(Task { await workspace.refreshDailyBackupRegistration() }) |
| 141 | repeatEvery(.seconds(30)) { await workspace.syncCompanion() } |
| 142 | repeatEvery(.seconds(25)) { await workspace.syncCompanionLibrary() } |
| 143 | repeatEvery(.seconds(300)) { await workspace.runDraftRevisionComments() } |
| 144 | repeatEvery(.seconds(60)) { workspace.recoverInterruptedPublications() } |
| 145 | repeatEvery(.seconds(10)) { [weak self] in |
| 146 | self?.updateScheduledActivity() |
| 147 | await workspace.runDuePosts() |
| 148 | self?.updateScheduledActivity() |
| 149 | } |
| 150 | repeatEvery(.seconds(60)) { |
| 151 | await workspace.refreshDueSubstackNewsletters() |
| 152 | await workspace.refreshScheduledWork() |
| 153 | await workspace.refillIdeaQueueIfNeeded() |
| 154 | } |
| 155 | repeatEvery(.seconds(60)) { await ReplyInbox(workspace: workspace).poll() } |
| 156 | repeatEvery(.seconds(60)) { await AccountAnalytics(workspace: workspace).poll() } |
| 157 | } |
| 158 | |
| 159 | func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } |
| 160 | |
| 161 | nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 162 | willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { |
| 163 | [.banner, .list] |
| 164 | } |
| 165 | |
| 166 | nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { |
| 167 | guard response.actionIdentifier == UNNotificationDefaultActionIdentifier, |
| 168 | let draftID = response.notification.request.content.userInfo[ScheduleNotifications.draftKey] as? String else { return } |
| 169 | await MainActor.run { |
| 170 | workspace.scheduleReminderDraftID = draftID |
| 171 | showWorkspace?() |
| 172 | NSApp.activate() |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func applicationWillTerminate(_ notification: Notification) { |
| 177 | for task in tasks { task.cancel() } |
| 178 | tasks.removeAll() |
| 179 | if let scheduledActivity { ProcessInfo.processInfo.endActivity(scheduledActivity) } |
| 180 | scheduledActivity = nil |
| 181 | } |
| 182 | |
| 183 | private func repeatEvery(_ delay: Duration, action: @escaping @MainActor () async -> Void) { |
| 184 | tasks.append(Task { @MainActor in |
| 185 | while !Task.isCancelled { |
| 186 | await action() |
| 187 | try? await Task.sleep(for: delay) |
| 188 | } |
| 189 | }) |
| 190 | } |
| 191 | |
| 192 | private func updateScheduledActivity() { |
| 193 | let soon = Date.now.addingTimeInterval(3 * 3600) |
| 194 | let needed = workspace.settings["autoPost"] as? Bool == true && workspace.records.contains { |
| 195 | $0.kind == "draft" && $0.scheduleStatus == "queued" && !["instagram", "reddit"].contains($0["platform"]) && |
| 196 | ($0.schedule["slotAt"] as? String).flatMap(scheduleDate).map { $0 <= soon } == true |
| 197 | } |
| 198 | if needed && scheduledActivity == nil { |
| 199 | scheduledActivity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep, |
| 200 | reason: "Check upcoming Inkspring posts") |
| 201 | } else if !needed, let activity = scheduledActivity { |
| 202 | ProcessInfo.processInfo.endActivity(activity) |
| 203 | scheduledActivity = nil |
| 204 | } |
| 205 | } |
| 206 | } |