SPB Git

Repository Public License

DataControls.swift 9.9 KB 207 lines swift

1import Foundation2import NavigatorCore3import Persistence45/// The choices of the "Clear browsing data" sheet.6public enum BrowsingDataCategory: String, Sendable, Codable, CaseIterable {7    /// Visited pages. Also clears the Shield statistics of the same period, which name the visited sites.8    case history9    /// The list of downloads. Downloaded files are never deleted by this.10    case downloadList11    /// Per-site permission decisions (stored and session).12    case permissions13    /// Tabs and windows kept for "reopen closed tab/window".14    case recentlyClosed15    /// Every window, tab and tab group, open or closed.16    case openTabs17    case bookmarks18    /// Saved page archives and snapshots (the archive files are reported for deletion).19    case archives20    case notes21    case canvases22    case agentRuns23    case shieldStatistics24    /// Cookies, local storage, IndexedDB, service workers. Owned by WebKit: see `WebsiteDataInstruction`.25    case cookiesAndSiteData26    /// HTTP and memory caches. Owned by WebKit.27    case cache2829    /// Rows of the database this category maps to; empty for what WebKit or another service owns.30    public var storedTypes: Set<UserDataType> {31        switch self {32        case .history: [.history]33        case .downloadList: [.downloads]34        case .permissions: [.permissions]35        case .recentlyClosed: [.recentlyClosed]36        case .openTabs: [.session]37        case .bookmarks: [.bookmarks]38        case .archives: [.archives, .snapshots]39        case .notes: [.notes]40        case .canvases: [.canvases]41        case .agentRuns: [.agentRuns]42        case .shieldStatistics, .cookiesAndSiteData, .cache: []43        }44    }4546    public var isWebsiteData: Bool { self == .cookiesAndSiteData || self == .cache }47}4849public enum DataTimeRange: Sendable, Hashable {50    case lastHour, last24Hours, last7Days, last4Weeks, allTime51    case custom(DateInterval)5253    /// The interval ending at `now` (`nil` = all time). The end is pushed one second past `now` because the54    /// deletion interval is half-open and must include what happened this very second.55    public func interval(now: Date) -> DateInterval? {56        let end = now.addingTimeInterval(1)57        switch self {58        case .lastHour: return DateInterval(start: now.addingTimeInterval(-3_600), end: end)59        case .last24Hours: return DateInterval(start: now.addingTimeInterval(-86_400), end: end)60        case .last7Days: return DateInterval(start: now.addingTimeInterval(-7 * 86_400), end: end)61        case .last4Weeks: return DateInterval(start: now.addingTimeInterval(-28 * 86_400), end: end)62        case .allTime: return nil63        case .custom(let interval): return interval64        }65    }66}6768public struct DataClearRequest: Sendable, Hashable {69    public var categories: Set<BrowsingDataCategory>70    public var range: DataTimeRange71    /// `nil` = every profile.72    public var profileID: ProfileID?7374    public init(categories: Set<BrowsingDataCategory>, range: DataTimeRange = .allTime, profileID: ProfileID? = nil) {75        self.categories = categories; self.range = range; self.profileID = profileID76    }77}7879/// What the web layer must remove from WebKit's own storage. This module cannot do it (no WebKit here): the80/// caller passes the instruction to WebRuntime, which maps it to `WKWebsiteDataStore.removeData`.81public struct WebsiteDataInstruction: Sendable, Hashable {82    /// Profiles whose data stores are concerned; empty = every profile.83    public var profileIDs: [ProfileID]84    public var cookiesAndSiteData: Bool85    public var cache: Bool86    /// Remove data modified since this date; `nil` = everything. WebKit only supports "modified since", so a87    /// custom range that does not end now removes everything from its start (documented in docs/SHIELD.md).88    public var modifiedSince: Date?89}9091public struct DataClearReport: Sendable {92    /// Rows deleted per category (history counts visits).93    public var deleted: [BrowsingDataCategory: Int] = [:]94    /// Archive files whose rows were deleted: the archive module removes the files.95    public var archiveFiles: [ArchiveFileReference] = []96    /// Present when cookies/site data or cache were requested.97    public var websiteData: WebsiteDataInstruction?9899    public var totalRows: Int { deleted.values.reduce(0, +) }100}101102/// The settings UI's entry point for deleting, keeping and exporting user data. A façade over103/// `database.lifecycle` plus the services that hold private state of their own (session permissions, Shield104/// statistics).105public struct DataControls: Sendable {106    private let database: NavigatorDatabase107    private let permissions: PermissionService?108    private let shield: ShieldService?109    private let now: @Sendable () -> Date110111    public init(database: NavigatorDatabase, permissions: PermissionService? = nil, shield: ShieldService? = nil,112                now: @escaping @Sendable () -> Date = { .now }) {113        self.database = database; self.permissions = permissions; self.shield = shield; self.now = now114    }115116    // MARK: Clearing117118    /// Deletes the requested categories for the time range and profile, in one database transaction, then the119    /// matching in-memory state. Website data is not touched here: the report says what to ask WebKit.120    @discardableResult121    public func clear(_ request: DataClearRequest) async throws -> DataClearReport {122        let interval = request.range.interval(now: now())123        var report = DataClearReport()124125        let types = request.categories.reduce(into: Set<UserDataType>()) { $0.formUnion($1.storedTypes) }126        if !types.isEmpty {127            let deletion = try await database.lifecycle.delete(DeletionRequest(types: types, profileID: request.profileID, range: interval))128            for category in request.categories {129                let count = category.storedTypes.reduce(0) { $0 + (deletion.deleted[$1] ?? 0) }130                if !category.storedTypes.isEmpty { report.deleted[category] = count }131            }132            report.archiveFiles = deletion.archiveFiles133        }134        if request.categories.contains(.permissions), let permissions {135            // Session decisions carry no usable date range semantics for the user: clearing permissions clears them all.136            if let profile = request.profileID { _ = try await permissions.revokeAllSessionDecisions(profile: profile) } else { await permissions.endSession() }137        }138        if request.categories.contains(.shieldStatistics) || request.categories.contains(.history), let shield {139            let removed = try await shield.clearStatistics(profile: request.profileID, range: interval)140            if request.categories.contains(.shieldStatistics) { report.deleted[.shieldStatistics] = removed }141        }142        if request.categories.contains(where: \.isWebsiteData) {143            report.websiteData = WebsiteDataInstruction(profileIDs: request.profileID.map { [$0] } ?? [],144                                                        cookiesAndSiteData: request.categories.contains(.cookiesAndSiteData),145                                                        cache: request.categories.contains(.cache),146                                                        modifiedSince: interval?.start)147        }148        if !types.isEmpty, interval == nil { try await database.lifecycle.compact() }149        return report150    }151152    /// Deletes everything the app stores — every profile, settings, sync state — and compacts the file. The153    /// report asks for all website data of all profiles to be removed too. Keychain items are not touched here.154    @discardableResult155    public func clearEverything() async throws -> DataClearReport {156        let deletion = try await database.lifecycle.deleteEverything()157        await permissions?.endSession()158        _ = try await shield?.clearStatistics()159        var report = DataClearReport()160        for category in BrowsingDataCategory.allCases where !category.storedTypes.isEmpty {161            report.deleted[category] = category.storedTypes.reduce(0) { $0 + (deletion.deleted[$1] ?? 0) }162        }163        report.archiveFiles = deletion.archiveFiles164        report.websiteData = WebsiteDataInstruction(profileIDs: [], cookiesAndSiteData: true, cache: true, modifiedSince: nil)165        return report166    }167168    // MARK: Retention169170    /// Days of history kept; 0 = forever.171    public func historyRetentionDays() async throws -> Int {172        try await database.settings.value(PersistenceSettings.historyRetentionDays)173    }174175    /// Stores the retention period and applies it immediately. Returns the number of visits deleted.176    @discardableResult177    public func setHistoryRetention(days: Int) async throws -> Int {178        try await database.settings.set(PersistenceSettings.historyRetentionDays, to: max(days, 0), at: now())179        return try await applyRetention()180    }181182    /// Applies the stored retention to history, Shield statistics (fixed 90 days) and expired permissions.183    /// Call at launch and once a day. Returns the number of history visits deleted.184    @discardableResult185    public func applyRetention() async throws -> Int {186        let visits = try await database.lifecycle.applyStoredRetentionPolicy(now: now())187        _ = try await shield?.pruneStatistics()188        _ = try await permissions?.purgeExpired()189        return visits190    }191192    // MARK: Export193194    /// The user's data as JSON (format in docs/PERSISTENCE.md). Contains no cookies or website storage, no195    /// secrets, no WebKit session state and no download resume data — and nothing of a private session, which196    /// is never stored in the first place.197    public func exportJSON(profile: ProfileID? = nil) async throws -> Data {198        if let shield { try await shield.flushStatistics() }199        return try await database.lifecycle.exportJSON(profile: profile, now: now())200    }201202    public func export(to url: URL, profile: ProfileID? = nil) async throws {203        if let shield { try await shield.flushStatistics() }204        try await database.lifecycle.exportJSON(to: url, profile: profile, now: now())205    }206}207
Files main
Menu

Theme