Branchwell

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

1import Foundation
2
3struct WorkspaceBackup {
4 let records: [WorkspaceRecord]
5 let preferences: [String: Any]
6 let media: [Media]
7 let stagingDirectory: URL?
8 var isLegacy = false
9
10 struct RestorePlan: Equatable {
11 let preservedIDs: Set<String>
12 let replacements: [String: String]
13 }
14
15 func restorePlan(over current: [WorkspaceRecord]) throws -> RestorePlan {
16 let local = Dictionary(uniqueKeysWithValues: current.map { ($0.id, $0) })
17 let deliveryStates = ["publishing", "published", "uncertain", "partial"]
18 let protectedDrafts = Set(current.filter {
19 $0.kind == "publication" && deliveryStates.contains($0["status"])
20 }.map { $0["draftId"] })
21 var preserved = Set<String>()
22 var replacements: [String: String] = [:]
23 for incoming in records {
24 guard let existing = local[incoming.id] else { continue }
25 guard incoming.kind == existing.kind else {
26 throw WorkspaceError("A backup ID conflicts with a different type of local record.")
27 }
28 let keep = switch existing.kind {
29 case "publication":
30 existing["status"] == "published" || incoming["status"] != "published" || existing["draftId"] != incoming["draftId"]
31 case "newsletter": !existing["remoteId"].isEmpty
32 case "draft": ["posting", "posted"].contains(existing.scheduleStatus) || protectedDrafts.contains(existing.id)
33 default: false
34 }
35 if keep { preserved.insert(existing.id) }
36 else { replacements[existing.id] = existing["updatedAt"] }
37 }
38 return RestorePlan(preservedIDs: preserved, replacements: replacements)
39 }
40
41 struct Media: Codable {
42 let kind: String
43 let file: String?
44 let id: String?
45 let entry: String
46 let size: Int64
47 let sha256: String
48
49 func validate() throws {
50 let validPath = switch kind {
51 case "image": file.map { entry == "media/images/" + $0 } ?? false
52 case "video": id.map { entry.hasPrefix("media/videos/" + $0 + ".") } ?? false
53 default: false
54 }
55 guard validPath, ZipArchive.safe(entry), (1...ZipArchive.mediaLimit).contains(size),
56 sha256.range(of: #"\A[a-f0-9]{64}\z"#, options: .regularExpression) != nil else {
57 throw WorkspaceError("The backup has an invalid media manifest.")
58 }
59 }
60 }
61
62 private static let supportedKinds: Set<String> = [
63 "project", "draft", "source", "idea", "newsletter", "script", "article", "publication", "personal-inbox",
64 "discovery", "research-feedback", "brief-run", "idea-queue-state", "reply-inbox",
65 "analytics-day", "analytics-post", "analytics-state", "r2-object", "local-video"
66 ]
67
68 private static let safePreferences: Set<String> = [
69 StudioChatAgent.writingPreference, "studioWritingModel.antigravity", "studioWritingModel.codex", "studioWritingModel.claude",
70 StudioWritingConnection.preferenceKey, "provider", "imageProvider", "anthropicModel", "openaiModel", "geminiModel",
71 "openaiImageModel", "geminiImageModel", "anthropicWorkspaceId", "personalProfile",
72 "personalSetupDismissed", "ideaQueueTarget", "onDeviceAssistantHistory"
73 ]
74
75 private static let secretFields: Set<String> = [
76 "apikey", "accesstoken", "refreshtoken", "idtoken", "clientsecret", "secretaccesskey",
77 "accesskeyid", "password", "authorization", "cookie", "cookies", "session", "sessionkey",
78 "token", "credentials", "privatekey", "signingkey", "codeverifier", "oauthstate", "uploadurl",
79 "presignedurl", "proto", "constructor", "prototype"
80 ]
81
82 static func stage(_ url: URL, in directory: URL) throws -> (backup: Self, files: [String: URL]) {
83 if url.pathExtension.lowercased() == "json" {
84 return (try stageLegacy(url), [:])
85 }
86 let staging = try temporaryDirectory(in: directory)
87 do {
88 let files = try ZipArchive.extract(from: url, to: staging)
89 guard let manifest = files["data.json"],
90 let object = try JSONSerialization.jsonObject(with: Data(contentsOf: manifest)) as? [String: Any],
91 object["app"] as? String == "inkspring-desktop", object["version"] as? Int == 2,
92 let rows = object["records"] as? [[String: Any]], rows.count <= 100_000,
93 let preferences = object["preferences"] as? [String: Any],
94 Set(preferences.keys).isSubset(of: safePreferences),
95 let entries = object["media"] as? [[String: Any]], entries.count <= 10_000 else {
96 throw WorkspaceError("Choose an Inkspring workspace ZIP backup (version 2).")
97 }
98 let records = try rows.map { row in
99 guard let kind = row["kind"] as? String, let fields = row["value"] as? [String: Any] else {
100 throw WorkspaceError("The backup contains an invalid workspace record.")
101 }
102 return try sanitized(WorkspaceRecord(kind: kind, fields: fields))
103 }
104 let media = try JSONDecoder().decode([Media].self, from: JSONSerialization.data(withJSONObject: entries))
105 try validate(records, media: media)
106 guard files.count == media.count + 1 else { throw WorkspaceError("The ZIP does not match its media manifest.") }
107 for item in media {
108 guard let file = files[item.entry],
109 try fileDigest(file) == (item.sha256, item.size) else {
110 throw WorkspaceError("A backup media file is missing or damaged.")
111 }
112 }
113 var cleanPreferences = try clean(preferences) as? [String: Any] ?? [:]
114 if let rawTheme = object[StudioTheme.preferenceKey] as? String, let theme = StudioTheme(rawValue: rawTheme) {
115 cleanPreferences[StudioTheme.preferenceKey] = theme.rawValue
116 }
117 return (Self(records: records, preferences: cleanPreferences, media: media, stagingDirectory: staging), files)
118 } catch {
119 try? FileManager.default.removeItem(at: staging)
120 throw error
121 }
122 }
123
124 private static func stageLegacy(_ url: URL) throws -> Self {
125 let limit = 20_000_000
126 let attributes = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
127 guard attributes.isRegularFile == true, let size = attributes.fileSize, size <= limit else {
128 throw WorkspaceError("Choose a regular JSON backup file under 20 MB.")
129 }
130 let handle = try FileHandle(forReadingFrom: url)
131 defer { try? handle.close() }
132 let bytes = try handle.read(upToCount: limit + 1) ?? Data()
133 guard bytes.count <= limit else { throw WorkspaceError("Choose an older JSON backup under 20 MB.") }
134 guard let data = try JSONSerialization.jsonObject(with: bytes) as? [String: Any],
135 data["version"] as? Int == 1,
136 data["app"] == nil || data["app"] as? String == "inkspring-desktop" else {
137 throw WorkspaceError("Choose an Inkspring workspace JSON backup (version 1).")
138 }
139 var records: [WorkspaceRecord] = []
140 for (field, kind, required) in [("projects", "project", true), ("drafts", "draft", true),
141 ("sources", "source", true), ("ideas", "idea", false),
142 ("newsletters", "newsletter", false), ("publications", "publication", false)] {
143 if !required, data[field] == nil { continue }
144 guard let rows = data[field] as? [[String: Any]], rows.count <= 10_000 else {
145 throw WorkspaceError("The older backup has an invalid \(field) list.")
146 }
147 for fields in rows {
148 var row = try sanitized(WorkspaceRecord(kind: kind, fields: fields))
149 let titleKey = kind == "project" ? "name" : kind == "idea" ? "topic" : "title"
150 guard kind == "project" || !row.projectID.isEmpty,
151 kind == "publication" || !row[titleKey].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
152 throw WorkspaceError("An older backup record is missing a project or title.")
153 }
154 for key in ["image", "video", "coverImage", "videoThumbnail"] { row.fields.removeValue(forKey: key) }
155 if kind == "draft", row["format"] == "carousel" {
156 let slides = (row.fields.removeValue(forKey: "slides") as? [[String: Any]] ?? []).map { slide in
157 ["title", "body"].compactMap { slide[$0] as? String }
158 .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
159 .joined(separator: "\n")
160 }
161 row["content"] = String(([row["content"]] + slides).filter { !$0.isEmpty }
162 .joined(separator: "\n\n").prefix(40_000))
163 row["format"] = "post"
164 }
165 if kind == "newsletter" {
166 for key in ["remoteId", "publication", "editUrl", "publicUrl", "postUrl", "remoteFingerprint",
167 "syncedRevision", "scheduledAt", "publishedAt", "requestedAction", "requestedAt", "error"] {
168 row.fields.removeValue(forKey: key)
169 }
170 row["state"] = "draft"
171 row.fields["revision"] = 1
172 if row["audience"].isEmpty { row["audience"] = "everyone" }
173 }
174 records.append(row)
175 }
176 }
177 try validate(records, media: [])
178 let drafts = Dictionary(uniqueKeysWithValues: records.filter { $0.kind == "draft" }.map { ($0.id, $0.projectID) })
179 guard records.filter({ $0.kind == "publication" }).allSatisfy({ drafts[$0["draftId"]] == $0.projectID }) else {
180 throw WorkspaceError("An older backup receipt references a missing post.")
181 }
182 var preferences: [String: Any] = [:]
183 if let profile = data["personalProfile"] {
184 guard let fields = try clean(profile) as? [String: Any] else { throw WorkspaceError("Invalid writing profile in backup.") }
185 preferences["personalProfile"] = try PersonalProfile.normalized(fields)
186 }
187 return Self(records: records, preferences: preferences, media: [], stagingDirectory: nil, isLegacy: true)
188 }
189
190 static func export(records: [WorkspaceRecord], preferences: [String: Any], directory: URL, to url: URL,
191 stagingParent: URL? = nil) throws {
192 let staging = try temporaryDirectory(in: stagingParent ?? directory)
193 defer { try? FileManager.default.removeItem(at: staging) }
194 let records = records.filter { $0.kind != "tiktok-consent" }
195 let rows = try records.reversed().map(sanitized)
196 let portablePreferences = try clean(preferences.filter { safePreferences.contains($0.key) })
197 var media: [Media] = []
198 var files: [(path: String, file: URL, size: Int64)] = []
199 let images = directory.appending(path: "images")
200 if FileManager.default.fileExists(atPath: images.path) {
201 for file in try FileManager.default.contentsOfDirectory(at: images, includingPropertiesForKeys: nil) {
202 let entry = "media/images/" + file.lastPathComponent
203 guard ZipArchive.safe(entry) else { continue }
204 let digest = try regularFileDigest(file)
205 media.append(Media(kind: "image", file: file.lastPathComponent, id: nil, entry: entry,
206 size: digest.size, sha256: digest.hash))
207 files.append((entry, file, digest.size))
208 }
209 }
210 for video in records where video.kind == "local-video" {
211 guard !video["path"].isEmpty else { throw WorkspaceError("A saved video is unavailable.") }
212 let file = URL(fileURLWithPath: video["path"])
213 let entry = "media/videos/\(video.id).\(file.pathExtension.lowercased())"
214 let digest = try regularFileDigest(file)
215 guard digest.hash == video["hash"], digest.size == video.fields["size"] as? Int64 else {
216 throw WorkspaceError("A video changed after it was attached. Attach it again before backing up.")
217 }
218 media.append(Media(kind: "video", file: nil, id: video.id, entry: entry,
219 size: digest.size, sha256: digest.hash))
220 files.append((entry, file, digest.size))
221 }
222 try validate(rows, media: media)
223 let manifest = staging.appending(path: "data.json")
224 var contents: [String: Any] = [
225 "app": "inkspring-desktop", "version": 2, "exportedAt": WorkspaceRecord.timestamp,
226 "records": rows.map { ["kind": $0.kind, "value": $0.fields] }, "preferences": portablePreferences,
227 "media": try JSONSerialization.jsonObject(with: JSONEncoder().encode(media))
228 ]
229 // Older importers ignore extra manifest fields and reject unknown preference keys.
230 if let rawTheme = preferences[StudioTheme.preferenceKey] as? String, let theme = StudioTheme(rawValue: rawTheme) {
231 contents[StudioTheme.preferenceKey] = theme.rawValue
232 }
233 let data = try JSONSerialization.data(withJSONObject: contents)
234 guard data.count <= ZipArchive.jsonLimit else { throw WorkspaceError("Workspace data exceeds the 100 MB backup limit.") }
235 try data.write(to: manifest)
236 let temporary = url.deletingLastPathComponent().appending(path: ".inkspring-\(UUID().uuidString).zip")
237 defer { try? FileManager.default.removeItem(at: temporary) }
238 try ZipArchive.write(to: temporary, files: [("data.json", manifest, Int64(data.count))] + files)
239 for (item, file) in zip(media, files) {
240 guard try regularFileDigest(file.file) == (item.sha256, item.size) else {
241 throw WorkspaceError("A media file changed during backup. Try again.")
242 }
243 }
244 if FileManager.default.fileExists(atPath: url.path) {
245 _ = try FileManager.default.replaceItemAt(url, withItemAt: temporary)
246 } else {
247 try FileManager.default.moveItem(at: temporary, to: url)
248 }
249 }
250
251 func restored(_ record: WorkspaceRecord) -> WorkspaceRecord {
252 var record = record
253 switch record.kind {
254 case "draft" where ["queued", "posting", "due"].contains(record.scheduleStatus):
255 var schedule = record.schedule
256 schedule["originalSlotAt"] = schedule["originalSlotAt"] ?? schedule["slotAt"]
257 schedule["slotAt"] = ""
258 schedule["status"] = "ready"
259 schedule["error"] = "Restored from backup. Review this post and choose a new time."
260 record.fields["schedule"] = schedule
261 case "newsletter":
262 record.fields["restoreSendEmail"] = record.fields["restoreSendEmail"] ?? record.fields["sendEmail"]
263 record.fields["sendEmail"] = false
264 if !record["remoteId"].isEmpty {
265 record.fields["restorePreviousState"] = record.fields["restorePreviousState"] ?? record.fields["state"]
266 record["state"] = "uncertain"
267 record["error"] = "Check Substack before syncing or sending. An existing remote schedule may still run there."
268 } else {
269 record["state"] = "draft"
270 record.fields["scheduledAt"] = nil
271 }
272 case "publication" where record["status"] != "published":
273 record["status"] = "uncertain"
274 record["error"] = "Restored receipt. Check the platform before another publishing attempt."
275 default:
276 break
277 }
278 return record
279 }
280
281 private static func validate(_ records: [WorkspaceRecord], media: [Media]) throws {
282 let projects = Set(records.filter { $0.kind == "project" }.map(\.id))
283 var ids: Set<String> = []
284 guard records.count <= 100_000, media.count <= 10_000 else {
285 throw WorkspaceError("This backup has too many records or files.")
286 }
287 for row in records {
288 guard supportedKinds.contains(row.kind), !row.id.isEmpty, row.id.utf16.count <= 500,
289 !row.id.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains),
290 ids.insert(row.id).inserted, row.projectID.isEmpty || projects.contains(row.projectID) else {
291 throw WorkspaceError("The backup contains an invalid or duplicate record.")
292 }
293 }
294 var paths: Set<String> = []
295 var images: Set<String> = []
296 var videos: Set<String> = []
297 var size: Int64 = 0
298 for item in media {
299 try item.validate()
300 guard paths.insert(item.entry).inserted else { throw WorkspaceError("The backup repeats a media path.") }
301 if let file = item.file, item.kind == "image" { images.insert(file) }
302 if let id = item.id, item.kind == "video", !videos.insert(id).inserted {
303 throw WorkspaceError("The backup repeats a video.")
304 }
305 size += item.size
306 guard size <= ZipArchive.totalLimit - ZipArchive.jsonLimit else {
307 throw WorkspaceError("This backup exceeds 64 GB of media.")
308 }
309 }
310 let videoRecords = Set(records.filter { $0.kind == "local-video" }.map(\.id))
311 for row in records {
312 if ["draft", "idea", "newsletter"].contains(row.kind) {
313 for key in row.kind == "draft" ? ["image", "videoThumbnail"] : [row.kind == "idea" ? "image" : "coverImage"] {
314 if let image = row.fields[key] as? [String: Any],
315 !images.contains(image["file"] as? String ?? "") {
316 throw WorkspaceError("A workspace image is missing from the backup.")
317 }
318 }
319 }
320 if row.kind == "draft", let video = row.fields["video"] as? [String: Any] {
321 let id = video["id"] as? String ?? ""
322 guard videos.contains(id), videoRecords.contains(id) else {
323 throw WorkspaceError("A draft video is missing from the backup.")
324 }
325 }
326 if row.kind == "local-video", !videos.contains(row.id) {
327 throw WorkspaceError("A workspace video is missing from the backup.")
328 }
329 }
330 }
331
332 private static func sanitized(_ input: WorkspaceRecord) throws -> WorkspaceRecord {
333 var record = WorkspaceRecord(kind: input.kind, fields: try clean(input.fields) as? [String: Any] ?? [:])
334 if record.kind == "local-video" {
335 record.fields["path"] = nil
336 record.fields["mtime"] = nil
337 }
338 if record.kind == "publication" {
339 record.fields["containers"] = []
340 record.fields["containerId"] = nil
341 }
342 return record
343 }
344
345 private static func clean(_ input: Any, depth: Int = 0) throws -> Any {
346 guard depth <= 40 else { throw WorkspaceError("This backup contains excessively nested data.") }
347 if let values = input as? [Any] { return try values.map { try clean($0, depth: depth + 1) } }
348 if let object = input as? [String: Any] {
349 return try object.filter {
350 let key = $0.key.lowercased().replacingOccurrences(of: "_", with: "").replacingOccurrences(of: "-", with: "")
351 return !secretFields.contains(key)
352 }.mapValues { try clean($0, depth: depth + 1) }
353 }
354 return input
355 }
356
357 private static func regularFileDigest(_ file: URL) throws -> (hash: String, size: Int64) {
358 let attributes = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
359 guard attributes.isRegularFile == true, attributes.isSymbolicLink != true else {
360 throw WorkspaceError("Backups require regular image and video files.")
361 }
362 return try fileDigest(file)
363 }
364
365 private static func temporaryDirectory(in directory: URL) throws -> URL {
366 let folder = directory.appending(path: ".transfer-\(UUID().uuidString)", directoryHint: .isDirectory)
367 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false,
368 attributes: [.posixPermissions: 0o700])
369 return folder
370 }
371}