SPB Git

Repository Public

BrowserServices.swift 6.9 KB 139 lines swift

1import Foundation2import Observation34/// The services both apps share: SP Search client, account, the synced library and the sync scheduler.5/// Each app creates one, pointing at its own data folder and keychain.6@MainActor7@Observable8final class BrowserServices {9    let account: AccountService10    let mirror: SyncDatabase11    let library: SyncedLibrary12    let sync: SyncCoordinator13    let search: SearchClient14    let device: DeviceDescription15    /// AURA Peek: fetches link previews without cookies or scripts.16    let peek = LinkPreviewLoader()17    /// Bumped whenever favorites, reading list, search history, preferences or other devices' tabs change, so views reload.18    private(set) var libraryRevision = 019    /// Set by the app: called when history or bookmarks were changed by another device.20    @ObservationIgnored var onRemoteProfileChange: (@MainActor (Set<String>) -> Void)?21    /// Set by the app: the open and recently closed tabs of regular (never private) windows.22    @ObservationIgnored var tabsProvider: (@MainActor () -> (open: [RemoteTab], closed: [RemoteTab]))?23    @ObservationIgnored private var historyBridge: HistorySyncBridge?24    @ObservationIgnored private var bookmarkBridge: BookmarkSyncBridge?25    @ObservationIgnored private var canvasBridge: CanvasSyncBridge?26    /// Set by the app: called when synced Canvas boards were changed by another device.27    @ObservationIgnored var onRemoteCanvasChange: (@MainActor () -> Void)?2829    init(root: URL?, secrets: SecretStore, authorizer: PasskeyAuthorizer, device: DeviceDescription,30         configuration: BackendConfiguration = .current(), syncEnabled: @escaping @MainActor () -> Bool) {31        self.device = device32        // If the mirror cannot be opened on disk the app still works, with an in-memory one for this run.33        let database = (try? SyncDatabase(url: root?.appendingPathComponent("sync.sqlite"))) ?? (try! SyncDatabase(url: nil))34        mirror = database35        library = SyncedLibrary(mirror: database)36        account = AccountService(configuration: configuration, secrets: secrets, authorizer: authorizer, device: { device })37        search = SearchClient(backend: account.backend)38        sync = SyncCoordinator(account: account, mirror: database, isEnabled: syncEnabled)39        account.onStateChange = { [weak self] in self?.sync.accountStateChanged(); self?.libraryRevision += 1 }40        sync.captureLocalChanges = { [weak self] in self?.capture() }41        sync.applyRemoteChanges = { [weak self] changed in self?.apply(changed) }42    }4344    /// Connects the default profile's history and bookmarks to sync. Private contexts are never attached.45    func attach(history: HistoryStore, bookmarks: BookmarkStore) {46        historyBridge = HistorySyncBridge(history: history, mirror: mirror)47        bookmarkBridge = BookmarkSyncBridge(bookmarks: bookmarks, mirror: mirror)48    }4950    /// Connects the default profile's Canvas boards to sync. Only boards the user opted in are ever sent.51    func attach(canvas: CanvasStore) { canvasBridge = CanvasSyncBridge(store: canvas, mirror: mirror) }5253    private func capture() {54        historyBridge?.captureLocalChanges()55        bookmarkBridge?.captureLocalChanges()56        canvasBridge?.captureLocalChanges()57        library.purgeExpiredHandoffs()58        if let deviceID = account.currentDeviceID, let tabs = tabsProvider?() {59            library.publishTabs(tabs.open, closed: tabs.closed, deviceID: deviceID, deviceName: device.name, platform: device.platform)60        }61    }6263    private func apply(_ changed: Set<String>) {64        if changed.contains(SyncCollection.history) { historyBridge?.applyRemoteChanges() }65        if changed.contains(SyncCollection.bookmarks) { bookmarkBridge?.applyRemoteChanges() }66        if changed.contains(SyncCollection.canvas) { canvasBridge?.applyRemoteChanges(); onRemoteCanvasChange?() }67        libraryRevision += 168        onRemoteProfileChange?(changed)69    }7071    /// Something synchronized changed on this device (visit, bookmark, tab, favorite…): refresh views and sync soon.72    func localChange(syncAfter delay: TimeInterval = 4) {73        libraryRevision += 174        sync.requestSync(after: delay)75    }7677    var searchPreferences: SearchPreferences {78        get { library.preferences().search }79        set {80            var prefs = library.preferences()81            guard prefs.search != newValue else { return }82            prefs.search = newValue83            library.setPreferences(prefs)84            localChange()85        }86    }8788    func searchContext(isPrivate: Bool) -> SearchContext {89        SearchContext(client: search, library: isPrivate ? nil : library, isPrivate: isPrivate,90                      preferences: { [weak self] in self?.searchPreferences ?? SearchPreferences() },91                      historyChanged: { [weak self] in self?.localChange(syncAfter: 8) })92    }9394    /// Tabs open on the user's other devices ("continue browsing from another device").95    var otherDevices: [DeviceTabs] { library.otherDevicesTabs(excluding: account.currentDeviceID) }9697    // MARK: Portal9899    /// Other devices with their tabs, for Portal.100    var portalDevices: [PortalDevice] { library.portalDevices(excluding: account.currentDeviceID) }101    /// Hand-offs other devices addressed to this one.102    var pendingHandoffs: [HandoffItem] { account.isSignedIn ? library.pendingHandoffs(for: account.currentDeviceID) : [] }103104    /// Sends tabs of regular browsing to another device (nil = any of them). Returns false when there was nothing to send.105    @discardableResult106    func sendHandoff(_ tabs: [RemoteTab], title: String = "", to target: PortalDevice?) -> Bool {107        guard let deviceID = account.currentDeviceID,108              library.sendHandoff(tabs: tabs, title: title, to: target?.id, fromDeviceID: deviceID, fromDeviceName: device.name, fromPlatform: device.platform) != nil else { return false }109        localChange(syncAfter: 0.5)110        return true111    }112113    func consumeHandoff(_ item: HandoffItem) {114        library.consumeHandoff(item)115        localChange(syncAfter: 0.5)116    }117118    /// A one-line description of the sync state for Portal and the start page.119    var syncDescription: String {120        switch sync.phase {121        case .off: return L("Synchronization is off")122        case .signedOut: return L("Not signed in")123        case .waitingForKey: return L("Waiting for approval from another device")124        case .offline: return L("Offline")125        case .failed: return L("Synchronization failed — will retry")126        case .syncing: return L("Synchronizing…")127        case .idle: return sync.lastSync.map { L("Synchronized %@", $0.formatted(.relative(presentation: .named))) } ?? L("Not synchronized yet")128        }129    }130131    /// Clearing browsing data also clears search history and the in-memory search cache.132    func clearSearchData() {133        library.clearSearches()134        Task { await search.clearCache() }135        RemoteImageLoader.shared.clear()136        localChange()137    }138}139
Files main
Menu

Theme