SPB Git

Repository Public

Profile.swift 4.6 KB 115 lines swift

1import Foundation23/// A browsing identity with its own cookies, site data, history, bookmarks and permissions.4struct Profile: Codable, Equatable, Identifiable, Sendable {5    var id: UUID6    var name: String7    var colorIndex: Int = 08    var symbol: String = "person.crop.circle"9    var createdAt: Date = Date()1011    /// The profile created on first launch. Its identifier is random, so two data folders never share a WebKit store.12    static func makeDefault() -> Profile { Profile(id: UUID(), name: L("Personal")) }13}1415struct ProfileList: Codable, Equatable, Sendable {16    var profiles: [Profile]17    /// The profile that cannot be deleted and that new windows use.18    var defaultID: UUID1920    init() {21        let first = Profile.makeDefault()22        profiles = [first]23        defaultID = first.id24    }25}2627/// Knows which profiles exist and where each keeps its files.28final class ProfileStore: Sendable {29    let root: URL30    private let store: JSONFileStore<ProfileList>3132    init(root: URL) {33        self.root = root34        try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)35        store = JSONFileStore(url: root.appendingPathComponent("profiles.json"), defaults: ProfileList())36        let list = store.value37        if list.profiles.isEmpty {38            store.value = ProfileList()39        } else if !list.profiles.contains(where: { $0.id == list.defaultID }) {40            store.update { $0.defaultID = $0.profiles[0].id }41        } else if !FileManager.default.fileExists(atPath: root.appendingPathComponent("profiles.json").path) {42            store.value = list   // first launch: persist the generated identifier43        }44    }4546    var profiles: [Profile] { store.value.profiles }47    var defaultID: UUID { store.value.defaultID }48    var defaultProfile: Profile { profiles.first { $0.id == defaultID } ?? profiles[0] }4950    func profile(id: UUID?) -> Profile? { profiles.first { $0.id == id } }5152    func directory(for profile: Profile) -> URL {53        root.appendingPathComponent(profile.id.uuidString, isDirectory: true)54    }5556    @discardableResult57    func create(name: String, colorIndex: Int = 0, symbol: String = "person.crop.circle") -> Profile {58        let clean = name.trimmingCharacters(in: .whitespacesAndNewlines)59        let profile = Profile(id: UUID(), name: clean.isEmpty ? L("New Profile") : clean, colorIndex: colorIndex, symbol: symbol)60        store.update { $0.profiles.append(profile) }61        return profile62    }6364    func update(_ profile: Profile) {65        store.update { list in66            if let index = list.profiles.firstIndex(where: { $0.id == profile.id }) { list.profiles[index] = profile }67        }68    }6970    /// Removes a profile and its on-disk metadata. The default profile cannot be removed.71    /// The caller is responsible for removing the profile's WebKit data store.72    @discardableResult73    func delete(_ profile: Profile) -> Bool {74        guard profile.id != defaultID, profiles.contains(where: { $0.id == profile.id }) else { return false }75        store.update { $0.profiles.removeAll { $0.id == profile.id } }76        try? FileManager.default.removeItem(at: directory(for: profile))77        return true78    }79}8081/// Privacy-preserving logging: messages are written to the unified log, and — only when the user82/// opted in — appended to a local diagnostics file. URLs are reduced to their host before logging.83enum Log {84    nonisolated(unsafe) static var diagnosticsURL: URL?85    private static let lock = NSLock()8687    static func redact(_ url: URL?) -> String {88        guard let url else { return "<none>" }89        return (url.scheme ?? "?") + "://" + (url.host ?? "<local>")90    }9192    static func event(_ category: String, _ message: String) {93        #if DEBUG94        NSLog("[SPBrowser/%@] %@", category, message)95        #endif96        lock.lock(); defer { lock.unlock() }97        guard let url = diagnosticsURL else { return }98        let line = ISO8601DateFormatter().string(from: Date()) + " [" + category + "] " + message + "\n"99        guard let data = line.data(using: .utf8) else { return }100        if let handle = try? FileHandle(forWritingTo: url) {101            defer { try? handle.close() }102            _ = try? handle.seekToEnd()103            try? handle.write(contentsOf: data)104        } else {105            try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)106            try? data.write(to: url, options: .atomic)107        }108    }109110    static func setDiagnostics(enabled: Bool, directory: URL) {111        lock.lock(); defer { lock.unlock() }112        diagnosticsURL = enabled ? directory.appendingPathComponent("diagnostics.log") : nil113    }114}115
Files main
Menu

Theme