SPB Git

Repository Public License

CapsuleImport.swift 32.1 KB 547 lines swift

1// SyncEngine — reading a capsule: strict validation, preview, merge into the database.2import Foundation3import NavigatorCore4import Persistence56/// A capsule that passed every check: container structure, integrity, manifest, hashes, content rules.7/// Holding one means nothing has been written yet; `CapsuleImporter.preview` and `apply` take it from here.8public struct CapsuleContents: Sendable {9    public let manifest: CapsuleManifest10    public let wasEncrypted: Bool11    var bookmarks: [Bookmark] = []12    var notes: [Note] = []13    var canvases: [CanvasDocument] = []14    var workflows: [Workflow] = []15    var spaces: [CapsuleSpace] = []16    var visits: [CapsuleVisit] = []17    var archives: [Archive] = []18    /// Entry name → bytes, for archive files and canvas attachments.19    var files: [String: Data] = [:]2021    public var includesHistory: Bool { !visits.isEmpty }22    public func count(of kind: CapsuleItemKind) -> Int {23        switch kind {24        case .bookmarks: return bookmarks.count25        case .notes: return notes.count26        case .canvases: return canvases.count27        case .workflows: return workflows.count28        case .spaces: return spaces.count29        case .history: return visits.count30        case .archives: return archives.count31        case .archiveFile: return files.keys.filter { $0.hasPrefix("files/archives/") }.count32        case .canvasAttachment: return files.keys.filter { $0.hasPrefix("files/canvas/") }.count33        }34    }35}3637public enum CapsuleReader {38    static let allowedSchemes: Set<String> = ["http", "https", "ftp", "file"]3940    public static func isEncrypted(_ file: Data) -> Bool { CapsuleContainer.isEncrypted(file) }4142    private static func checkURL(_ url: URL?, _ what: String) throws {43        guard let url else { return }44        guard let scheme = url.scheme?.lowercased(), allowedSchemes.contains(scheme) else {45            throw CapsuleError.unsafeContent("\(what) with a “\(url.scheme ?? "")” address")46        }47    }4849    private static func checkText(_ text: String, _ what: String, limits: CapsuleLimits) throws {50        guard text.utf8.count <= limits.maximumTextBytes else { throw CapsuleError.limitExceeded("\(what) text") }51    }5253    private static func decode<T: Decodable>(_ type: [T].Type, _ item: CapsuleManifest.Item, _ data: Data, limits: CapsuleLimits) throws -> [T] {54        guard let values = try? CapsuleCoding.decoder().decode(type, from: data) else { throw CapsuleError.malformed("\(item.name) does not decode") }55        guard values.count == item.count else { throw CapsuleError.malformed("\(item.name) holds \(values.count) records, the manifest says \(item.count)") }56        guard values.count <= limits.maximumItemsPerKind else { throw CapsuleError.limitExceeded("\(item.name) record count") }57        return values58    }5960    /// Opens capsule bytes. Any defect — wrong magic, newer version, truncation, a size over the limits, a name61    /// that could escape a directory, a hash that does not match, an entry the manifest does not list, content62    /// with a forbidden address scheme — rejects the whole capsule. Nothing is written by this call.63    public static func open(_ file: Data, password: String? = nil, limits: CapsuleLimits = CapsuleLimits()) throws -> CapsuleContents {64        let entries = try CapsuleContainer.read(file, password: password, limits: limits)65        guard let first = entries.first, first.name == CapsuleManifest.entryName else { throw CapsuleError.malformed("the manifest is not the first entry") }66        guard let manifest = try? CapsuleCoding.decoder().decode(CapsuleManifest.self, from: first.data) else { throw CapsuleError.malformed("manifest") }67        guard manifest.format == CapsuleManifest.formatIdentifier else { throw CapsuleError.notACapsule }68        guard manifest.formatVersion == CapsuleManifest.currentFormatVersion else { throw CapsuleError.unsupportedVersion(manifest.formatVersion) }69        // The manifest and the entries must describe exactly the same set.70        let payloads = Dictionary(uniqueKeysWithValues: entries.dropFirst().map { ($0.name, $0.data) })71        guard manifest.items.count == payloads.count, Set(manifest.items.map(\.name)).count == manifest.items.count else {72            throw CapsuleError.malformed("the manifest does not match the entries")73        }74        var contents = CapsuleContents(manifest: manifest, wasEncrypted: CapsuleContainer.isEncrypted(file))75        var seenKinds = Set<CapsuleItemKind>()76        for item in manifest.items {77            guard let data = payloads[item.name] else { throw CapsuleError.malformed("missing entry \(item.name)") }78            guard data.count == item.byteSize, item.count >= 0 else { throw CapsuleError.malformed("size of \(item.name)") }79            guard CapsuleCoding.sha256(data) == item.sha256.lowercased() else { throw CapsuleError.hashMismatch(item.name) }80            let expectedName: String?81            switch item.kind {82            case .bookmarks: expectedName = "data/bookmarks.json"83            case .notes: expectedName = "data/notes.json"84            case .canvases: expectedName = "data/canvases.json"85            case .workflows: expectedName = "data/workflows.json"86            case .spaces: expectedName = "data/spaces.json"87            case .history: expectedName = "data/history.json"88            case .archives: expectedName = "data/archives.json"89            case .archiveFile, .canvasAttachment: expectedName = nil90            }91            if let expectedName {92                guard item.name == expectedName, seenKinds.insert(item.kind).inserted else { throw CapsuleError.malformed("unexpected entry \(item.name)") }93            }94            switch item.kind {95            case .bookmarks:96                contents.bookmarks = try decode([Bookmark].self, item, data, limits: limits)97                for bookmark in contents.bookmarks {98                    try checkURL(bookmark.url, "a bookmark")99                    try checkText(bookmark.title, "bookmark", limits: limits)100                    guard bookmark.kind == .folder || bookmark.url != nil, bookmark.tags.count <= 200 else { throw CapsuleError.malformed("bookmark \(bookmark.id)") }101                }102                guard Set(contents.bookmarks.map(\.id)).count == contents.bookmarks.count else { throw CapsuleError.malformed("duplicate bookmark") }103            case .notes:104                contents.notes = try decode([Note].self, item, data, limits: limits)105                for note in contents.notes {106                    try checkURL(note.url, "a note")107                    try checkText(note.body, "note", limits: limits); try checkText(note.title, "note", limits: limits)108                    try checkText(note.quote ?? "", "note", limits: limits)109                }110                guard Set(contents.notes.map(\.id)).count == contents.notes.count else { throw CapsuleError.malformed("duplicate note") }111            case .canvases:112                contents.canvases = try decode([CanvasDocument].self, item, data, limits: limits)113                for canvas in contents.canvases {114                    guard canvas.cards.count <= 20_000, canvas.connections.count <= 50_000, Set(canvas.cards.map(\.id)).count == canvas.cards.count else {115                        throw CapsuleError.malformed("canvas \(canvas.id)")116                    }117                    try checkText(canvas.title, "canvas", limits: limits)118                    for card in canvas.cards {119                        guard card.origin.x.isFinite, card.origin.y.isFinite, card.size.width.isFinite, card.size.height.isFinite else {120                            throw CapsuleError.malformed("canvas \(canvas.id) geometry")121                        }122                        switch card.content {123                        case .page(let url, let title): try checkURL(url, "a canvas card"); try checkText(title, "canvas card", limits: limits)124                        case .note(let text): try checkText(text, "canvas card", limits: limits)125                        case .image(let path), .pdf(let path, _):126                            // The only names a card may refer to are content-hash names: no path can be smuggled in.127                            guard CapsuleExporter.isAttachmentName(path) else { throw CapsuleError.unsafeName(path) }128                        }129                    }130                    let ids = Set(canvas.cards.map(\.id))131                    guard canvas.connections.allSatisfy({ ids.contains($0.from) && ids.contains($0.to) && $0.from != $0.to }) else {132                        throw CapsuleError.malformed("canvas \(canvas.id) connections")133                    }134                }135                guard Set(contents.canvases.map(\.id)).count == contents.canvases.count else { throw CapsuleError.malformed("duplicate canvas") }136            case .workflows:137                contents.workflows = try decode([Workflow].self, item, data, limits: limits)138                for workflow in contents.workflows {139                    // A workflow is text; it is validated by the Flow engine before it can ever run.140                    guard workflow.source.utf8.count <= 256 * 1024 else { throw CapsuleError.limitExceeded("workflow source") }141                    try checkText(workflow.name, "workflow", limits: limits)142                }143                guard Set(contents.workflows.map(\.id)).count == contents.workflows.count else { throw CapsuleError.malformed("duplicate workflow") }144            case .spaces:145                contents.spaces = try decode([CapsuleSpace].self, item, data, limits: limits)146                for space in contents.spaces {147                    guard space.tabs.count <= 5_000, space.symbol.utf8.count <= 200 else { throw CapsuleError.limitExceeded("tabs of a space") }148                    try checkText(space.name, "space", limits: limits)149                    for tab in space.tabs { try checkURL(tab.url, "a tab"); try checkText(tab.title, "tab", limits: limits) }150                }151                guard Set(contents.spaces.map(\.id)).count == contents.spaces.count else { throw CapsuleError.malformed("duplicate space") }152            case .history:153                guard manifest.includesHistory else { throw CapsuleError.malformed("history present but not declared") }154                contents.visits = try decode([CapsuleVisit].self, item, data, limits: limits)155                for visit in contents.visits { try checkURL(visit.url, "a history entry"); try checkText(visit.title, "history", limits: limits) }156            case .archives:157                contents.archives = try decode([Archive].self, item, data, limits: limits)158                for archive in contents.archives {159                    try checkURL(archive.url, "an archive"); try checkText(archive.title, "archive", limits: limits)160                    guard archive.missing.count <= 10_000 else { throw CapsuleError.limitExceeded("archive details") }161                }162                guard Set(contents.archives.map(\.id)).count == contents.archives.count else { throw CapsuleError.malformed("duplicate archive") }163            case .archiveFile, .canvasAttachment:164                let parts = item.name.split(separator: "/").map(String.init)165                let prefix = item.kind == .archiveFile ? ["files", "archives"] : ["files", "canvas"]166                guard parts.count == 4, Array(parts.prefix(2)) == prefix, UUID(uuidString: parts[2]) != nil, item.count == 1 else {167                    throw CapsuleError.unsafeName(item.name)168                }169                if item.kind == .canvasAttachment { guard CapsuleExporter.isAttachmentName(parts[3]) else { throw CapsuleError.unsafeName(item.name) } }170                contents.files[item.name] = data171            }172        }173        if manifest.includesHistory != !contents.visits.isEmpty, manifest.includesHistory { throw CapsuleError.malformed("history declared but absent") }174        // Every file must belong to something in the capsule, and every archive must point at its own file.175        let archiveIDs = Set(contents.archives.map(\.id.string)), canvasIDs = Set(contents.canvases.map(\.id.string))176        for name in contents.files.keys {177            let parts = name.split(separator: "/").map(String.init)178            guard (parts[1] == "archives" ? archiveIDs : canvasIDs).contains(parts[2].uppercased()) else { throw CapsuleError.malformed("orphan file \(name)") }179        }180        for archive in contents.archives where !archive.relativePath.isEmpty {181            guard archive.relativePath.hasPrefix("files/archives/\(archive.id.string)/"), contents.files[archive.relativePath] != nil else {182                throw CapsuleError.unsafeName(archive.relativePath)183            }184        }185        return contents186    }187}188189public enum CapsuleConflictPolicy: String, Sendable, Codable, CaseIterable {190    /// Import the incoming item under a new identifier next to the existing one.191    case keepBoth192    /// Overwrite the existing item with the incoming one.193    case replace194    /// Keep the existing item, ignore the incoming one.195    case skip196}197198public struct CapsuleImportOptions: Sendable {199    /// Profile that receives bookmarks, spaces, archives and history.200    public var profileID: ProfileID201    public var policy: CapsuleConflictPolicy202    /// History in the capsule is imported only when this is set too.203    public var importHistory = false204    public var archiveDirectory: URL?205    public var canvasAttachmentDirectory: URL?206207    public init(profileID: ProfileID, policy: CapsuleConflictPolicy, importHistory: Bool = false, archiveDirectory: URL? = nil,208                canvasAttachmentDirectory: URL? = nil) {209        self.profileID = profileID; self.policy = policy; self.importHistory = importHistory210        self.archiveDirectory = archiveDirectory; self.canvasAttachmentDirectory = canvasAttachmentDirectory211    }212}213214public struct CapsuleKindSummary: Sendable, Hashable {215    public var total = 0216    /// Not present in the destination.217    public var new = 0218    /// Present and identical: nothing to do.219    public var identical = 0220    /// Present with different content: the conflict policy decides.221    public var conflicting = 0222}223224/// What an import would do, computed without writing anything.225public struct CapsulePreview: Sendable, Hashable {226    public var manifest: CapsuleManifest227    public var wasEncrypted: Bool228    public var kinds: [CapsuleItemKind: CapsuleKindSummary]229    public var fileCount: Int230    public var totalBytes: Int231    /// Things that will not be imported with the given options, and why.232    public var notes: [String]233234    public var hasConflicts: Bool { kinds.values.contains { $0.conflicting > 0 } }235}236237public struct CapsuleImportReport: Sendable, Hashable {238    public struct Counts: Sendable, Hashable {239        public var imported = 0240        public var replaced = 0241        /// Imported under a new identifier because of a conflict (`keepBoth`).242        public var duplicated = 0243        public var skipped = 0244        public var identical = 0245    }246    public var kinds: [CapsuleItemKind: Counts] = [:]247    public var filesWritten = 0248    public var notes: [String] = []249250    public var totalWritten: Int { kinds.values.reduce(0) { $0 + $1.imported + $1.replaced + $1.duplicated } }251}252253/// Merges an opened capsule into the database.254///255/// Each item is written in its own transaction through the public stores; the import as a whole is not one256/// transaction (see docs/CAPSULE_FORMAT.md). Existing items are never overwritten unless the policy is `replace`.257public actor CapsuleImporter {258    private let database: NavigatorDatabase259260    public init(database: NavigatorDatabase) { self.database = database }261262    private enum Action { case create, identical, replace, duplicate, skip }263264    private func decide(exists: Bool, identical: Bool, policy: CapsuleConflictPolicy) -> Action {265        guard exists else { return .create }266        if identical { return .identical }267        switch policy {268        case .keepBoth: return .duplicate269        case .replace: return .replace270        case .skip: return .skip271        }272    }273274    private struct Plan {275        var spaces: [(space: CapsuleSpace, action: Action, finalID: SpaceID)] = []276        var bookmarks: [(bookmark: Bookmark, action: Action)] = []277        var notes: [(note: Note, action: Action)] = []278        var canvases: [(canvas: CanvasDocument, action: Action, sourceID: CanvasID)] = []279        var workflows: [(workflow: Workflow, action: Action)] = []280        var archives: [(archive: Archive, action: Action, entry: String)] = []281        var visits: [NavigationEntry] = []282        var duplicateVisits = 0283        var remarks: [String] = []284    }285286    /// A note or canvas keeps its space when that space is imported with it or already exists here.287    private func resolvedSpace(_ id: SpaceID?, _ map: [SpaceID: SpaceID]) async throws -> SpaceID? {288        guard let id else { return nil }289        if let mapped = map[id] { return mapped }290        return try await database.spaces.space(id) != nil ? id : nil291    }292293    /// Everything the import would do, decided from reads only.294    private func plan(_ contents: CapsuleContents, _ options: CapsuleImportOptions) async throws -> Plan {295        guard try await database.profiles.profile(options.profileID) != nil else {296            throw PersistenceError.ownerNotPersisted(owner: "profile", id: options.profileID.string)297        }298        var plan = Plan()299300        // Spaces first: notes and canvases refer to them.301        var spaceMap: [SpaceID: SpaceID] = [:]302        for space in contents.spaces {303            var action = Action.create, finalID = space.id304            if let existing = try await database.spaces.space(space.id) {305                let tabs = try await database.tabs.tabs(space: space.id).compactMap { tab in306                    tab.url.map { CapsuleSpace.Tab(url: $0, title: tab.title, isPinned: tab.isPinned) }307                }308                let same = existing.name == space.name && existing.symbol == space.symbol && existing.tint == space.tint && tabs == space.tabs309                // An open workspace is never overwritten: "replace" is treated as "keep both" for spaces.310                action = decide(exists: true, identical: same, policy: options.policy == .replace ? .keepBoth : options.policy)311                if action == .duplicate { finalID = SpaceID() }312            }313            if action == .create || action == .identical || action == .skip { spaceMap[space.id] = space.id }314            if action == .duplicate || action == .create { spaceMap[space.id] = finalID }315            plan.spaces.append((space, action, finalID))316        }317        if options.policy == .replace, plan.spaces.contains(where: { $0.action == .duplicate }) {318            plan.remarks.append("Spaces that already exist are imported as copies: an open space is never replaced.")319        }320        let spaces = spaceMap321322        // Bookmarks: parents before children; identifiers may change under "keep both".323        var byID = Dictionary(uniqueKeysWithValues: contents.bookmarks.map { ($0.id, $0) })324        var ordered: [Bookmark] = []325        var visited = Set<BookmarkID>()326        func visit(_ bookmark: Bookmark, depth: Int) {327            guard visited.insert(bookmark.id).inserted else { return }328            if depth < 128, let parent = bookmark.parentID, let parentBookmark = byID[parent] { visit(parentBookmark, depth: depth + 1) }329            ordered.append(bookmark)330        }331        for bookmark in contents.bookmarks.sorted(by: { ($0.order, $0.id) < ($1.order, $1.id) }) { visit(bookmark, depth: 0) }332        byID.removeAll()333        var bookmarkMap: [BookmarkID: BookmarkID] = [:]334        var folderIDs = Set<BookmarkID>()335        for original in ordered {336            var target = original337            target.profileID = options.profileID338            if let parent = original.parentID {339                if let mapped = bookmarkMap[parent] {340                    target.parentID = folderIDs.contains(mapped) ? mapped : nil341                } else if let existingParent = try await database.bookmarks.bookmark(parent), existingParent.kind == .folder,342                          existingParent.profileID == options.profileID {343                    target.parentID = parent344                } else {345                    target.parentID = nil   // the folder is neither in the capsule nor in this profile346                }347            }348            let existing = try await database.bookmarks.bookmark(original.id)349            var action = decide(exists: existing != nil, identical: existing == target, policy: options.policy)350            // A bookmark of another profile with the same identifier cannot be replaced in place.351            if let existing, existing.profileID != options.profileID, action == .replace { action = .duplicate }352            if action == .duplicate { target.id = BookmarkID() }353            let finalID = action == .skip || action == .identical ? original.id : target.id354            bookmarkMap[original.id] = finalID355            let finalKind = action == .skip ? existing?.kind : target.kind356            let finalProfile = action == .skip ? existing?.profileID : target.profileID357            if finalKind == .folder, finalProfile == options.profileID { folderIDs.insert(finalID) }358            plan.bookmarks.append((target, action))359        }360361        for original in contents.notes {362            var target = original363            target.spaceID = try await resolvedSpace(original.spaceID, spaces)364            let existing = try await database.notes.note(original.id)365            let action = decide(exists: existing != nil, identical: existing == target, policy: options.policy)366            if action == .duplicate { target.id = NoteID() }367            plan.notes.append((target, action))368        }369        for original in contents.canvases {370            var target = original371            target.spaceID = try await resolvedSpace(original.spaceID, spaces)372            let existing = try await database.canvases.document(original.id)373            let action = decide(exists: existing != nil, identical: existing == target, policy: options.policy)374            if action == .duplicate { target.id = CanvasID() }375            plan.canvases.append((target, action, original.id))376        }377        for original in contents.workflows {378            var target = original379            let existing = try await database.workflows.workflow(original.id)380            let action = decide(exists: existing != nil, identical: existing == target, policy: options.policy)381            if action == .duplicate { target.id = WorkflowID() }382            plan.workflows.append((target, action))383        }384        if !contents.archives.isEmpty, options.archiveDirectory == nil {385            plan.remarks.append("Archives are not imported: no archive folder was given.")386        } else {387            for original in contents.archives {388                guard !original.relativePath.isEmpty else {389                    plan.remarks.append("Archive “\(original.title)” has no file in this capsule and is not imported.")390                    continue391                }392                var target = original393                target.profileID = options.profileID394                let existing = try await database.archives.archive(original.id)395                var comparable = target396                comparable.relativePath = existing?.relativePath ?? ""397                var action = decide(exists: existing != nil, identical: existing == comparable, policy: options.policy)398                if let existing, existing.profileID != options.profileID, action == .replace { action = .duplicate }399                if action == .duplicate { target.id = ArchiveID() }400                // Where the file goes is decided here, never by the capsule.401                target.relativePath = "capsule/\(target.id.string)/\(CapsuleContainer.sanitisedFileName(original.relativePath))"402                plan.archives.append((target, action, original.relativePath))403            }404        }405        if !contents.visits.isEmpty {406            if options.importHistory {407                let dates = contents.visits.map(\.visitedAt)408                var known = Set<String>()409                if let first = dates.min(), let last = dates.max() {410                    let range = DateInterval(start: first, end: last.addingTimeInterval(1))411                    for visit in try await database.history.visits(profile: options.profileID, in: range, limit: 1_000_000) {412                        known.insert("\(visit.url.absoluteString)|\(visit.visitedAt.timeIntervalSince1970)")413                    }414                }415                for visit in contents.visits {416                    if known.insert("\(visit.url.absoluteString)|\(visit.visitedAt.timeIntervalSince1970)").inserted {417                        plan.visits.append(NavigationEntry(profileID: options.profileID, url: visit.url, title: visit.title,418                                                           visitedAt: visit.visitedAt, transition: visit.transition))419                    } else {420                        plan.duplicateVisits += 1421                    }422                }423            } else {424                plan.remarks.append("The capsule contains browsing history; it is not imported unless you ask for it.")425            }426        }427        return plan428    }429430    private func summary<T>(_ entries: [T], _ action: (T) -> Action) -> CapsuleKindSummary {431        var summary = CapsuleKindSummary(total: entries.count)432        for entry in entries {433            switch action(entry) {434            case .create: summary.new += 1435            case .identical: summary.identical += 1436            case .replace, .duplicate, .skip: summary.conflicting += 1437            }438        }439        return summary440    }441442    /// What `apply` would do with these options. Reads only.443    public func preview(_ contents: CapsuleContents, options: CapsuleImportOptions) async throws -> CapsulePreview {444        let plan = try await plan(contents, options)445        var kinds: [CapsuleItemKind: CapsuleKindSummary] = [:]446        if !contents.spaces.isEmpty { kinds[.spaces] = summary(plan.spaces) { $0.action } }447        if !contents.bookmarks.isEmpty { kinds[.bookmarks] = summary(plan.bookmarks) { $0.action } }448        if !contents.notes.isEmpty { kinds[.notes] = summary(plan.notes) { $0.action } }449        if !contents.canvases.isEmpty { kinds[.canvases] = summary(plan.canvases) { $0.action } }450        if !contents.workflows.isEmpty { kinds[.workflows] = summary(plan.workflows) { $0.action } }451        if !contents.archives.isEmpty {452            var archives = summary(plan.archives) { $0.action }453            archives.total = contents.archives.count454            kinds[.archives] = archives455        }456        if !contents.visits.isEmpty {457            kinds[.history] = CapsuleKindSummary(total: contents.visits.count, new: plan.visits.count, identical: plan.duplicateVisits, conflicting: 0)458        }459        return CapsulePreview(manifest: contents.manifest, wasEncrypted: contents.wasEncrypted, kinds: kinds, fileCount: contents.files.count,460                              totalBytes: contents.manifest.items.reduce(0) { $0 + $1.byteSize }, notes: plan.remarks)461    }462463    private func count(_ action: Action, into counts: inout CapsuleImportReport.Counts) {464        switch action {465        case .create: counts.imported += 1466        case .identical: counts.identical += 1467        case .replace: counts.replaced += 1468        case .duplicate: counts.duplicated += 1469        case .skip: counts.skipped += 1470        }471    }472473    /// Merges the capsule into the database according to the options.474    public func apply(_ contents: CapsuleContents, options: CapsuleImportOptions) async throws -> CapsuleImportReport {475        let plan = try await plan(contents, options)476        var report = CapsuleImportReport(notes: plan.remarks)477478        for entry in plan.spaces {479            count(entry.action, into: &report.kinds[.spaces, default: .init()])480            guard entry.action == .create || entry.action == .duplicate else { continue }481            let existing = try await database.spaces.spaces(profile: options.profileID)482            var name = entry.space.name483            if existing.contains(where: { $0.name == name }) { name += " (imported)" }484            let space = OrbitSpace(id: entry.finalID, profileID: options.profileID, name: name, symbol: entry.space.symbol, tint: entry.space.tint,485                                   order: (existing.map(\.order).max() ?? -1) + 1)486            try await database.spaces.save(space)487            guard !entry.space.tabs.isEmpty else { continue }488            let window = BrowserWindow(spaceID: space.id)489            try await database.windows.save(window)490            // Tabs arrive dormant: an address and a title, no session state, nothing loaded until the user opens them.491            let tabs = entry.space.tabs.enumerated().map { index, tab in492                Tab(windowID: window.id, spaceID: space.id, url: tab.url, title: tab.title, isPinned: tab.isPinned, order: index, lifecycle: .dormant)493            }494            try await database.tabs.save(tabs)495        }496        for entry in plan.bookmarks {497            count(entry.action, into: &report.kinds[.bookmarks, default: .init()])498            if entry.action == .create || entry.action == .replace || entry.action == .duplicate { try await database.bookmarks.save(entry.bookmark) }499        }500        for entry in plan.notes {501            count(entry.action, into: &report.kinds[.notes, default: .init()])502            if entry.action == .create || entry.action == .replace || entry.action == .duplicate { try await database.notes.save(entry.note) }503        }504        for entry in plan.canvases {505            count(entry.action, into: &report.kinds[.canvases, default: .init()])506            guard entry.action == .create || entry.action == .replace || entry.action == .duplicate else { continue }507            try await database.canvases.save(entry.canvas)508            guard let root = options.canvasAttachmentDirectory else { continue }509            let prefix = "files/canvas/\(entry.sourceID.string)/"510            for (name, data) in contents.files where name.hasPrefix(prefix) {511                let fileName = String(name.dropFirst(prefix.count))512                guard CapsuleExporter.isAttachmentName(fileName) else { continue }513                let directory = root.appending(path: entry.canvas.id.string, directoryHint: .isDirectory)514                try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)515                let destination = directory.appending(path: fileName)516                // Content-addressed: an existing file with that name already has these bytes.517                if !FileManager.default.fileExists(atPath: destination.path) { try data.write(to: destination, options: [.atomic]); report.filesWritten += 1 }518            }519        }520        if !contents.canvases.isEmpty, options.canvasAttachmentDirectory == nil, contents.count(of: .canvasAttachment) > 0 {521            report.notes.append("Canvas attachments were not written: no attachment folder was given.")522        }523        for entry in plan.workflows {524            count(entry.action, into: &report.kinds[.workflows, default: .init()])525            if entry.action == .create || entry.action == .replace || entry.action == .duplicate { try await database.workflows.save(entry.workflow) }526        }527        for entry in plan.archives {528            count(entry.action, into: &report.kinds[.archives, default: .init()])529            guard entry.action == .create || entry.action == .replace || entry.action == .duplicate, let root = options.archiveDirectory,530                  let data = contents.files[entry.entry] else { continue }531            guard let destination = CapsuleExporter.contained(entry.archive.relativePath, in: root) else { throw CapsuleError.unsafeName(entry.archive.relativePath) }532            try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)533            try data.write(to: destination, options: [.atomic])534            report.filesWritten += 1535            var archive = entry.archive536            archive.byteSize = Int64(data.count)537            archive.contentHash = CapsuleCoding.sha256(data)538            try await database.archives.save(archive)539        }540        if !plan.visits.isEmpty || plan.duplicateVisits > 0 {541            try await database.history.recordVisits(plan.visits)542            report.kinds[.history] = CapsuleImportReport.Counts(imported: plan.visits.count, replaced: 0, duplicated: 0, skipped: 0, identical: plan.duplicateVisits)543        }544        return report545    }546}547
Files main
Menu

Theme