Branchwell

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

Raw 8.1 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import Foundation
2
3struct WorkspaceMigration {
4 struct Report {
5 let records: Int
6 let images: Int
7 let videos: Int
8 }
9
10 static func prepareImport(from source: URL, into workspace: URL) throws -> URL {
11 let database = source.appending(path: "workspace.sqlite")
12 let attributes = try? database.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
13 guard source.resolvingSymlinksInPath().standardizedFileURL != workspace.resolvingSymlinksInPath().standardizedFileURL,
14 attributes?.isRegularFile == true, attributes?.isSymbolicLink != true else {
15 throw WorkspaceError("Choose an Inkspring workspace folder containing workspace.sqlite.")
16 }
17 let staging = workspace.appending(path: ".workspace-import-\(UUID().uuidString)", directoryHint: .isDirectory)
18 let manager = FileManager.default
19 try manager.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
20 do {
21 let snapshotFile = staging.appending(path: "workspace.sqlite")
22 try WorkspaceDatabase.copy(from: database, to: snapshotFile)
23 let snapshot = try WorkspaceDatabase(url: snapshotFile).snapshot()
24 let archive = staging.appending(path: "Workspace.zip")
25 try WorkspaceBackup.export(records: snapshot.records, preferences: snapshot.settings,
26 directory: source, to: archive, stagingParent: staging)
27 return archive
28 } catch {
29 try? manager.removeItem(at: staging)
30 throw error
31 }
32 }
33
34 static func stage(from source: URL, to destination: URL) throws -> Report {
35 let manager = FileManager.default
36 let sourceDatabase = source.appending(path: "workspace.sqlite")
37 guard source.standardizedFileURL != destination.standardizedFileURL,
38 manager.fileExists(atPath: sourceDatabase.path),
39 !manager.fileExists(atPath: destination.path) else {
40 throw WorkspaceError("Choose an existing Inkspring workspace and a new destination folder.")
41 }
42 let parent = destination.deletingLastPathComponent()
43 let stage = parent.appending(path: ".inkspring-migration-\(UUID().uuidString)", directoryHint: .isDirectory)
44 try manager.createDirectory(at: stage, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
45 defer { try? manager.removeItem(at: stage) }
46 try WorkspaceDatabase.copy(from: sourceDatabase, to: stage.appending(path: "workspace.sqlite"))
47 let result = try copyAttachmentsAndPrepare(source: source, stage: stage, destination: destination)
48 try manager.moveItem(at: stage, to: destination)
49 return result
50 }
51
52 private static func copyAttachmentsAndPrepare(source: URL, stage: URL, destination: URL) throws -> Report {
53 let manager = FileManager.default
54 let database = try WorkspaceDatabase(url: stage.appending(path: "workspace.sqlite"))
55 let records = try database.records()
56 let sourceImages = source.appending(path: "images", directoryHint: .isDirectory)
57 let images = stage.appending(path: "images", directoryHint: .isDirectory)
58 let videos = stage.appending(path: "videos", directoryHint: .isDirectory)
59 try manager.createDirectory(at: images, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
60 try manager.createDirectory(at: videos, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
61
62 var copiedImages: Set<String> = []
63 if manager.fileExists(atPath: sourceImages.path) {
64 for input in try manager.contentsOfDirectory(at: sourceImages, includingPropertiesForKeys: nil) {
65 let file = input.lastPathComponent
66 guard ZipArchive.safe("media/images/" + file) else { continue }
67 _ = try copyChecked(input, to: images.appending(path: file))
68 copiedImages.insert(file)
69 }
70 }
71 for row in records where ["draft", "newsletter"].contains(row.kind) {
72 for key in row.kind == "draft" ? ["image", "videoThumbnail"] : row.kind == "idea" ? ["image"] : ["coverImage"] {
73 if let image = row.fields[key] as? [String: Any],
74 !copiedImages.contains(image["file"] as? String ?? "") {
75 throw WorkspaceError("A source draft references an unavailable image. The source workspace is unchanged.")
76 }
77 }
78 }
79
80 let videoRecords = records.filter { $0.kind == "local-video" }
81 let ids = Set(videoRecords.map(\.id))
82 for row in records where row.kind == "draft" {
83 if let video = row.fields["video"] as? [String: Any],
84 !ids.contains(video["id"] as? String ?? "") {
85 throw WorkspaceError("A source draft references an unavailable video.")
86 }
87 }
88 var migratedVideos: [WorkspaceRecord] = []
89 for record in videoRecords {
90 var record = record
91 guard record["path"].hasPrefix("/") else { throw WorkspaceError("A local video path is missing.") }
92 let input = URL(fileURLWithPath: record["path"])
93 let fileExtension = input.pathExtension.lowercased()
94 let hash = record["hash"]
95 guard ["mp4", "mov", "webm"].contains(fileExtension),
96 hash.range(of: #"\A[a-f0-9]{64}\z"#, options: .regularExpression) != nil else {
97 throw WorkspaceError("A source video has invalid attachment metadata.")
98 }
99 let file = hash + "." + fileExtension
100 let target = videos.appending(path: file)
101 let digest = try manager.fileExists(atPath: target.path)
102 ? fileDigest(target) : copyChecked(input, to: target)
103 guard digest.hash == hash, digest.size == record.fields["size"] as? Int64 else {
104 throw WorkspaceError("A source video changed after it was attached.")
105 }
106 record["path"] = destination.appending(path: "videos").appending(path: file).path
107 record.fields["mtime"] = try target.resourceValues(forKeys: [.contentModificationDateKey])
108 .contentModificationDate.map { $0.timeIntervalSince1970 * 1000 }
109 migratedVideos.append(record)
110 }
111
112 try database.transaction {
113 for video in migratedVideos { try database.put(video) }
114 // Keep existing schedules and receipts for review. Pause automation until
115 // the native app's connections and permissions have been configured.
116 for key in ["mcpEnabled", "mcpAllowPosting", AgentMCP.credentialPermission,
117 "ideaQueueAutomatic", "autoPost", "dailyBackupEnabled"] {
118 try database.set(key, to: false)
119 }
120 try database.set("analyticsAutomatic", to: [String: Bool]())
121 try database.set("replyMonitoringX", to: ["enabled": false])
122 let settings = try database.settings()
123 if var vault = settings["obsidianVault"] as? [String: Any] {
124 vault["allowAgents"] = false
125 try database.set("obsidianVault", to: vault)
126 }
127 try database.set("workspaceMigrationAt", to: WorkspaceRecord.timestamp)
128 }
129 return Report(records: records.count, images: copiedImages.count, videos: videoRecords.count)
130 }
131
132 private static func copyChecked(_ source: URL, to destination: URL) throws -> (hash: String, size: Int64) {
133 let attributes = try source.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
134 guard attributes.isRegularFile == true, attributes.isSymbolicLink != true else {
135 throw WorkspaceError("The migration found a missing or unsupported attachment.")
136 }
137 let digest = try fileDigest(source)
138 try FileManager.default.copyItem(at: source, to: destination)
139 guard try fileDigest(destination) == digest else {
140 throw WorkspaceError("An attachment changed during migration. Try again after editing finishes.")
141 }
142 return digest
143 }
144}