SPB Git

Repository Public License

CapsuleExport.swift 12.2 KB 227 lines swift

1// SyncEngine — choosing what goes into a capsule and writing it.2import Foundation3import NavigatorCore4import Persistence56public enum CapsulePick<Identifier: Hashable & Sendable>: Sendable, Hashable {7    case none8    case all9    case only(Set<Identifier>)1011    var isNone: Bool { if case .none = self { return true } else { return false } }12    func includes(_ id: Identifier) -> Bool {13        switch self {14        case .none: return false15        case .all: return true16        case .only(let ids): return ids.contains(id)17        }18    }19}2021/// What the user ticked in the export sheet. Everything defaults to "nothing"; history must be ticked explicitly.22///23/// There is no field for cookies, website data, settings, permissions, downloads, agent runs, the memory index24/// or secrets: a capsule cannot carry them.25public struct CapsuleSelection: Sendable, Hashable {26    /// The profile whose bookmarks, archives and history are exported.27    public var profileID: ProfileID28    /// A selected folder brings its whole subtree.29    public var bookmarks: CapsulePick<BookmarkID> = .none30    public var notes: CapsulePick<NoteID> = .none31    public var canvases: CapsulePick<CanvasID> = .none32    public var workflows: CapsulePick<WorkflowID> = .none33    /// Spaces are exported as a name, a symbol, a tint and the list of their open tabs (URL, title, pinned).34    public var spaces: CapsulePick<SpaceID> = .none35    public var archives: CapsulePick<ArchiveID> = .none36    /// Off unless the user explicitly asks for it.37    public var includeHistory = false38    public var historyLimit = 20_0003940    public init(profileID: ProfileID) { self.profileID = profileID }41}4243struct CapsuleSpace: Codable, Sendable, Hashable {44    struct Tab: Codable, Sendable, Hashable {45        var url: URL46        var title: String47        var isPinned: Bool48    }49    var id: SpaceID50    var name: String51    var symbol: String52    var tint: SpaceTint53    var tabs: [Tab]54}5556struct CapsuleVisit: Codable, Sendable, Hashable {57    var url: URL58    var title: String59    var visitedAt: Date60    var transition: NavigationEntry.Transition61}6263public struct CapsuleExportReport: Sendable, Hashable {64    public var manifest: CapsuleManifest65    public var byteCount: Int66    public var isEncrypted: Bool67    /// Things that were selected but left out, with the reason (a missing archive file, for instance).68    public var omissions: [String]69}7071/// Builds capsules from the database. File reads happen on this actor, never on the main actor.72public actor CapsuleExporter {73    private let database: NavigatorDatabase74    private let appVersion: String75    private let archiveDirectory: URL?76    private let canvasAttachmentDirectory: URL?77    private let limits: CapsuleLimits7879    /// - Parameters:80    ///   - archiveDirectory: the directory `Archive.relativePath` is relative to (for the exported profile);81    ///     without it archives are exported as metadata only.82    ///   - canvasAttachmentDirectory: the root of `CanvasAttachmentStore` (`<root>/<canvas id>/<file>`).83    public init(database: NavigatorDatabase, appVersion: String, archiveDirectory: URL? = nil, canvasAttachmentDirectory: URL? = nil,84                limits: CapsuleLimits = CapsuleLimits()) {85        self.database = database; self.appVersion = appVersion; self.archiveDirectory = archiveDirectory86        self.canvasAttachmentDirectory = canvasAttachmentDirectory; self.limits = limits87    }8889    static func isAttachmentName(_ name: String) -> Bool {90        let parts = name.split(separator: ".", omittingEmptySubsequences: false)91        return parts.count == 2 && parts[0].utf8.count == 64 && parts[0].utf8.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }92            && ["png", "jpg", "gif", "webp", "heic", "tiff", "pdf"].contains(String(parts[1]))93    }9495    /// Resolves a relative path inside a directory, refusing anything that would leave it.96    static func contained(_ relativePath: String, in directory: URL) -> URL? {97        guard !relativePath.isEmpty, !relativePath.hasPrefix("/"), !relativePath.contains("\\"), !relativePath.contains("\0") else { return nil }98        let components = relativePath.split(separator: "/", omittingEmptySubsequences: false)99        guard !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) else { return nil }100        let base = directory.standardizedFileURL.resolvingSymlinksInPath()101        let candidate = base.appending(path: relativePath).standardizedFileURL.resolvingSymlinksInPath()102        return candidate.path.hasPrefix(base.path + "/") ? candidate : nil103    }104105    /// Builds the capsule bytes. With a password the content is encrypted (AES-256-GCM, key from106    /// PBKDF2-HMAC-SHA256); without one the capsule is readable by anyone who has the file.107    public func export(_ selection: CapsuleSelection, password: String? = nil, createdAt: Date = .now) async throws -> (data: Data, report: CapsuleExportReport) {108        var entries: [CapsuleEntry] = []109        var items: [CapsuleManifest.Item] = []110        var omissions: [String] = []111        func add(_ name: String, _ kind: CapsuleItemKind, _ data: Data, count: Int) {112            entries.append(CapsuleEntry(name: name, data: data))113            items.append(CapsuleManifest.Item(name: name, kind: kind, count: count, byteSize: data.count, sha256: CapsuleCoding.sha256(data)))114        }115        let encoder = CapsuleCoding.encoder()116117        if !selection.bookmarks.isNone {118            let all = try await database.bookmarks.all(profile: selection.profileID)119            var chosen: [Bookmark] = []120            if case .only(let ids) = selection.bookmarks {121                // A selected folder brings everything below it.122                let children = Dictionary(grouping: all, by: \.parentID)123                var included = Set<BookmarkID>()124                var queue = all.filter { ids.contains($0.id) }.map(\.id)125                while let next = queue.popLast() {126                    if included.insert(next).inserted { queue += (children[next] ?? []).map(\.id) }127                }128                chosen = all.filter { included.contains($0.id) }129            } else {130                chosen = all131            }132            chosen.sort { $0.id < $1.id }133            if !chosen.isEmpty { add("data/bookmarks.json", .bookmarks, try encoder.encode(chosen), count: chosen.count) }134        }135        if !selection.notes.isNone {136            let notes = try await database.notes.notes(limit: limits.maximumItemsPerKind).filter { selection.notes.includes($0.id) }.sorted { $0.id < $1.id }137            if !notes.isEmpty { add("data/notes.json", .notes, try encoder.encode(notes), count: notes.count) }138        }139        var canvases: [CanvasDocument] = []140        if !selection.canvases.isNone {141            canvases = try await database.canvases.documents().filter { selection.canvases.includes($0.id) }.sorted { $0.id < $1.id }142            if !canvases.isEmpty { add("data/canvases.json", .canvases, try encoder.encode(canvases), count: canvases.count) }143        }144        if !selection.workflows.isNone {145            let workflows = try await database.workflows.all().filter { selection.workflows.includes($0.id) }.sorted { $0.id < $1.id }146            if !workflows.isEmpty { add("data/workflows.json", .workflows, try encoder.encode(workflows), count: workflows.count) }147        }148        if !selection.spaces.isNone {149            var spaces: [CapsuleSpace] = []150            for space in try await database.spaces.spaces(profile: selection.profileID) where selection.spaces.includes(space.id) {151                // Only the address, the title and the pinned state of a tab leave the device: no session state.152                let tabs = try await database.tabs.tabs(space: space.id).compactMap { tab in153                    tab.url.map { CapsuleSpace.Tab(url: $0, title: tab.title, isPinned: tab.isPinned) }154                }155                spaces.append(CapsuleSpace(id: space.id, name: space.name, symbol: space.symbol, tint: space.tint, tabs: tabs))156            }157            spaces.sort { $0.id < $1.id }158            if !spaces.isEmpty { add("data/spaces.json", .spaces, try encoder.encode(spaces), count: spaces.count) }159        }160        if selection.includeHistory {161            let visits = try await database.history.visits(profile: selection.profileID, limit: max(0, min(selection.historyLimit, limits.maximumItemsPerKind)))162                .map { CapsuleVisit(url: $0.url, title: $0.title, visitedAt: $0.visitedAt, transition: $0.transition) }163            if !visits.isEmpty { add("data/history.json", .history, try encoder.encode(visits), count: visits.count) }164        }165        if !selection.archives.isNone {166            var archives = try await database.archives.archives(profile: selection.profileID, limit: limits.maximumItemsPerKind)167                .filter { selection.archives.includes($0.id) }.sorted { $0.id < $1.id }168            var files: [(String, Data)] = []169            for index in archives.indices {170                let archive = archives[index]171                let name = "files/archives/\(archive.id.string)/\(CapsuleContainer.sanitisedFileName(archive.relativePath))"172                guard let directory = archiveDirectory, let location = Self.contained(archive.relativePath, in: directory),173                      let data = try? Data(contentsOf: location, options: [.mappedIfSafe]) else {174                    omissions.append("Archive “\(archive.title)”: its file could not be read; only its description is exported.")175                    archives[index].relativePath = ""176                    continue177                }178                // Inside a capsule the path of an archive file is its entry name.179                archives[index].relativePath = name180                files.append((name, data))181            }182            if !archives.isEmpty {183                add("data/archives.json", .archives, try encoder.encode(archives), count: archives.count)184                for (name, data) in files { add(name, .archiveFile, data, count: 1) }185            }186        }187        if let root = canvasAttachmentDirectory {188            for canvas in canvases {189                var names = Set<String>()190                for card in canvas.cards {191                    switch card.content {192                    case .image(let path), .pdf(let path, _): names.insert(path)193                    case .page, .note: break194                    }195                }196                for name in names.sorted() {197                    let location = root.appending(path: canvas.id.string).appending(path: name)198                    guard Self.isAttachmentName(name), let data = try? Data(contentsOf: location, options: [.mappedIfSafe]) else {199                        omissions.append("Canvas “\(canvas.title)”: attachment \(name.prefix(12))… could not be read.")200                        continue201                    }202                    add("files/canvas/\(canvas.id.string)/\(name)", .canvasAttachment, data, count: 1)203                }204            }205        }206        guard !entries.isEmpty else { throw CapsuleError.emptySelection }207208        // Sorted by name, manifest first: the same selection and date always produce the same clear-text bytes.209        entries.sort { $0.name < $1.name }210        items.sort { $0.name < $1.name }211        let manifest = CapsuleManifest(format: CapsuleManifest.formatIdentifier, formatVersion: CapsuleManifest.currentFormatVersion,212                                       createdAt: Date(timeIntervalSince1970: createdAt.timeIntervalSince1970.rounded()), appVersion: appVersion,213                                       includesHistory: items.contains { $0.kind == .history }, items: items)214        entries.insert(CapsuleEntry(name: CapsuleManifest.entryName, data: try encoder.encode(manifest)), at: 0)215        let data = try CapsuleContainer.write(entries, password: password, limits: limits)216        return (data, CapsuleExportReport(manifest: manifest, byteCount: data.count, isEncrypted: password != nil, omissions: omissions))217    }218219    /// Writes a capsule to a file (`.orixcapsule`), atomically.220    @discardableResult221    public func export(_ selection: CapsuleSelection, to url: URL, password: String? = nil, createdAt: Date = .now) async throws -> CapsuleExportReport {222        let (data, report) = try await export(selection, password: password, createdAt: createdAt)223        try data.write(to: url, options: [.atomic])224        return report225    }226}227
Files main
Menu

Theme