SPB Git

Repository Public

AppEnvironment.swift 21.4 KB 421 lines swift

1// SP Drive iOS2// File: App/AppEnvironment.swift3// Description: The app's single source of truth for the interface: session, sync engine, network, lock, File Provider domain, notifications.4//              Views read the local store (instant, works offline) and re-read it when the engine says something changed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import FileProvider9import Foundation10import Observation11import SwiftUI12import UIKit13import UserNotifications1415struct Toast: Identifiable, Equatable {16    enum Style { case info, success, error }17    let id = UUID()18    var text: String19    var style: Style = .info20}2122@MainActor @Observable23final class AppModel {24    enum Phase: Equatable { case launching, signedOut, signedIn }2526    let api: DriveAPI27    let store: DriveStore28    let files: LocalFiles29    let engine: SyncEngine30    let background: BackgroundSession31    let lock = BiometricLock()32    let passkeys = PasskeyController()33    /// SP Drive 2.0: the shared client and what the server announced.34    let next: NextCenter3536    private(set) var phase: Phase = .launching37    private(set) var account: AccountState?38    private(set) var network: NetworkStatus = .unknown39    private(set) var syncStatus: SyncStatus = .idle(lastSync: nil)40    /// Bumped whenever the corresponding part of the local store changed; views that read the store depend on these.41    private(set) var itemsVersion = 042    private(set) var transfersVersion = 043    private(set) var conflictsVersion = 044    var toast: Toast?45    var signInError: String?46    var isSigningIn = false4748    /// Why queued transfers wait, by transfer (policy holds: Wi-Fi only, Low Data Mode, Low Power Mode, battery).49    private(set) var transferHolds: [String: TransferPolicy.Hold] = [:]50    /// A request coming from outside a screen (deep link, widget, keyboard shortcut): the front screen consumes it.51    var pendingRoute: AppRoute?5253    @ObservationIgnored private var tasks: [Task<Void, Never>] = []54    /// Learns that the Drive changed: polling today, the server's event stream when the 2.0 backend is linked (see ChangeListener).55    @ObservationIgnored private var listener: ChangeListener?56    /// Phase 2 sets this before sign-in to plug the SSE stream; nil = polling only.57    @ObservationIgnored var eventSource: ChangeEventSource?58    @ObservationIgnored private var widgetTask: Task<Void, Never>?59    @ObservationIgnored private var seenNotifications: Set<String> = []6061    init() {62        if AppConfiguration.resetOnLaunch {63            try? FileManager.default.removeItem(at: AppGroup.appSupport)64            try? FileManager.default.removeItem(at: AppGroup.fileProviderState)65        }66        #if DEBUG67        // the extensions run in their own processes: they learn the test server's address through the group's defaults68        if let url = ProcessInfo.processInfo.environment["SPDRIVE_BASE_URL"], !url.isEmpty { AppGroup.sharedDefaults.set(url, forKey: "debug.baseURL") }69        else { AppGroup.sharedDefaults.removeObject(forKey: "debug.baseURL") }70        #endif71        let tokens = KeychainTokenStore()72        if AppConfiguration.resetOnLaunch { tokens.setToken(nil) }73        if let injected = AppConfiguration.injectedToken { tokens.setToken(injected) }74        api = DriveAPI(tokens: tokens)75        files = LocalFiles.app()76        // a database that cannot be opened is a programming or disk error the app cannot work around77        store = try! DriveStore(path: AppGroup.appSupport.appendingPathComponent("drive.sqlite").path)78        background = BackgroundSession(identifier: AppConfiguration.backgroundSessionID, staging: files.staging)79        // sync engine 2.0: the policy (Wi-Fi only, Low Data Mode, Low Power Mode, battery) and the adaptive controller decide what runs80        engine = SyncEngine(store: store, files: files, remote: api, driver: background, concurrency: { TransferPolicy.default.maxConcurrency },81                            conditions: { DeviceConditions.shared.current }, policy: { DeviceConditions.policy })82        next = NextCenter(api: api)83        DragSupport.engine = engine84        if let last = store.meta("lastSync").flatMap(Double.init) { syncStatus = .idle(lastSync: Date(timeIntervalSince1970: last)) }85    }8687    // MARK: Launch8889    func start() async {90        guard tasks.isEmpty else { return }91        await engine.start()92        let events = await engine.events()93        tasks.append(Task { [weak self] in for await e in events { self?.handle(e) } })94        DeviceConditions.shared.start()95        AppGroup.sharedDefaults.set(DeviceConditions.policy.allowCellular, forKey: "transfers.cellular")96        tasks.append(Task { [weak self] in97            var wasOnline = true98            for await status in NetworkMonitor.shared.updates() {99                guard let self else { return }100                self.network = status101                if status.online, !wasOnline, self.phase == .signedIn { self.resolveFileProviderErrors(); await self.engine.networkBecameAvailable() }102                else { await self.engine.conditionsChanged() } // Wi-Fi ↔ cellular, Low Data Mode103                wasOnline = status.online104            }105        })106        tasks.append(Task { [weak self] in107            for await _ in DeviceConditions.shared.changes() { await self?.engine.conditionsChanged() } // Low Power Mode, battery, charger108        })109        tasks.append(Task { [weak self] in110            // a preference changed in Settings (Wi-Fi only…): the queue is re-evaluated at once111            for await _ in NotificationCenter.default.notifications(named: UserDefaults.didChangeNotification).map({ _ in () }) { await self?.policyMayHaveChanged() }112        })113        if api.isSignedIn {114            phase = .signedIn115            await engine.reconcileLocalCopies()116            await didSignIn(fresh: false)117        } else {118            phase = .signedOut119        }120    }121122    private func handle(_ e: EngineEvent) {123        switch e {124        case .itemsChanged: itemsVersion &+= 1; signalFileProvider(); scheduleWidgetSnapshot()125        case .transfersChanged:126            transfersVersion &+= 1127            scheduleWidgetSnapshot()128            Task { let h = await engine.currentHolds(); if h != transferHolds { transferHolds = h } }129        case .conflictsChanged: conflictsVersion &+= 1130        case .status(let s): syncStatus = s131        case .signedOut: Task { await sessionLost() }132        case .conflictDetected(let name):133            Haptics.warning()134            Notifier.post(.conflict, title: "Conflit de versions", body: "« \(name) » a été modifié sur un autre appareil. Tes modifications sont conservées : choisis quoi garder.")135        case .transferFinished(let t):136            guard t.state == .failed else { return }137            switch t.errorCode {138            case "quota": Notifier.post(.quota, title: "Espace insuffisant", body: "« \(t.name) » n’a pas pu être envoyé : ton Drive est plein.")139            case "conflict", "unauthenticated": break140            default: Notifier.post(.failure, title: "Transfert interrompu", body: "« \(t.name) » n’a pas pu être \(t.kind == .upload ? "envoyé" : "téléchargé"). Ouvre SP Drive pour réessayer.")141            }142        }143    }144145    // MARK: Session146147    func signInWithPasskey() async {148        guard !isSigningIn else { return }149        isSigningIn = true150        signInError = nil151        defer { isSigningIn = false }152        do {153            let (challenge, options) = try await api.loginOptions()154            let response = try await passkeys.assert(optionsJSON: options)155            try await api.loginVerify(challengeID: challenge, response: response, deviceName: AppConfiguration.deviceName)156            await didSignIn(fresh: true)157        } catch PasskeyError.cancelled {158        } catch {159            signInError = Self.describe(error)160        }161    }162163    /// Called once a device-link code was approved in a browser (the token is already stored).164    func deviceLinkApproved() async { await didSignIn(fresh: true) }165166    private func didSignIn(fresh: Bool) async {167        phase = .signedIn168        if fresh { Haptics.success() }169        await refreshAccount()170        await next.refresh()171        await rebuildListener()172        // another account than the one this device's records belong to: start clean rather than mix two Drives173        if let user = account?.user?.id {174            if let known = store.meta("user"), known != user { await engine.wipe() }175            store.setMeta("user", user)176        }177        await registerFileProviderDomain()178        resolveFileProviderErrors()179        await drainShareInbox()180        await engine.sync()181        await drainShareInbox() // on a first launch the root folder is only known after the first sync182        Notifier.requestAuthorizationIfNeeded()183        BackgroundWork.schedule()184        startForegroundLoop()185    }186187    /// What the share extension parked in the group container joins the upload queue (files it already sent itself are skipped).188    private func drainShareInbox() async {189        let engine = engine, store = store190        await ShareInbox().drain(remote: api) { url, entry in191            guard let parent = entry.folderID.flatMap({ store.item($0)?.id }) ?? store.rootID else { throw EngineError.notFound }192            _ = try await engine.importFile(at: url, named: entry.displayName, into: parent, move: false)193        }194    }195196    func refreshAccount() async {197        do { account = try await api.accountState() } catch RemoteError.unauthenticated { await sessionLost() } catch {}198    }199200    /// The server refused the session (revoked from another device, or silent for too long). Local data stays; the user signs in again.201    private func sessionLost() async {202        guard phase == .signedIn else { return }203        api.tokens.setToken(nil)204        phase = .signedOut205        await listener?.stop()206        signInError = "Ta session a pris fin. Connecte-toi à nouveau : tes fichiers hors ligne et tes modifications en attente sont conservés."207    }208209    /// Signs out. Unsent changes would be lost with the local data, so the caller asks first (see `pendingWorkCount`).210    func signOut() async {211        await listener?.stop()212        listener = nil213        next.forget()214        WidgetBridge.clear()215        await api.logout()216        await engine.wipe()217        await removeFileProviderDomains()218        account = nil219        phase = .signedOut220        signInError = nil221    }222223    var pendingWorkCount: Int { _ = itemsVersion; return store.ops().filter { $0.state != .failed }.count + store.allLocalStates().filter(\.dirty).count }224225    // MARK: Sync226227    func refresh() async { await engine.sync(); await refreshAccount() }228229    private func startForegroundLoop() {230        if listener == nil {231            // the server's event stream when it has one (2.0); polling alone otherwise. Events are hints: the change feed stays the truth.232            let source: ChangeEventSource? = eventSource ?? (next.has(.events) && !AppConfiguration.eventsDisabled ? SSEChangeSource(client: next.client) : nil)233            listener = ChangeListener(source: source, configuration: .init(pollInterval: AppConfiguration.foregroundSyncInterval)) { [weak self] kind in234                _ = kind235                await self?.checkServerNotifications()236            } onChange: { [weak self] in237                guard let self, await self.phase == .signedIn else { return }238                await self.engine.sync()239                await self.checkServerNotifications()240            }241        }242        Task { await listener?.start(); listenerMode = await listener?.mode ?? .stopped }243    }244245    /// The server's capabilities changed (first sign-in, server upgraded): the listener is rebuilt with or without the stream.246    private func rebuildListener() async {247        await listener?.stop()248        listener = nil249    }250251    /// How changes are learnt right now (diagnostics in Settings).252    private(set) var listenerMode: ChangeListener.Mode = .stopped253    func refreshListenerMode() async { listenerMode = await listener?.mode ?? .stopped }254255    @ObservationIgnored private var lastPolicy = DeviceConditions.policy256    private func policyMayHaveChanged() async {257        let p = DeviceConditions.policy258        // the share extension runs in its own process: it reads the « Wi-Fi only » choice from the group's defaults259        if AppGroup.sharedDefaults.object(forKey: "transfers.cellular") as? Bool != p.allowCellular { AppGroup.sharedDefaults.set(p.allowCellular, forKey: "transfers.cellular") }260        guard p != lastPolicy else { return }261        lastPolicy = p262        await engine.conditionsChanged()263    }264265    /// The widgets read a small snapshot in the group container; it is rewritten (at most every two seconds) when something they show changes.266    private func scheduleWidgetSnapshot() {267        guard widgetTask == nil else { return }268        widgetTask = Task { [weak self] in269            try? await Task.sleep(for: .seconds(2))270            guard let self else { return }271            self.widgetTask = nil272            guard self.phase == .signedIn else { return }273            WidgetBridge.publish(store: self.store, files: self.files, quota: self.account?.quota.map { ($0.used, $0.limit) }, holds: self.transferHolds)274        }275    }276277    /// Handles `spdrive://…` links (widgets, quick actions).278    func open(url: URL) {279        guard let route = AppRoute(url: url) else { return }280        pendingRoute = route281    }282283    func sceneBecameActive() async {284        lock.willEnterForeground()285        guard phase == .signedIn else { return }286        startForegroundLoop()287        await engine.reconcileLocalCopies()288        await drainShareInbox()289        if await next.refresh() { await rebuildListener(); startForegroundLoop() }290        await refresh()291        await checkServerNotifications()292    }293294    func sceneEnteredBackground() {295        lock.didEnterBackground()296        Task { await listener?.stop() }297        if phase == .signedIn { WidgetBridge.publish(store: store, files: files, quota: account?.quota.map { ($0.used, $0.limit) }, holds: transferHolds) }298        BackgroundWork.schedule()299    }300301    /// New deposits and security events announced by the server become local notifications (once each).302    func checkServerNotifications() async {303        guard phase == .signedIn, let list = try? await api.notifications() else { return }304        if seenNotifications.isEmpty, let saved = store.meta("seenNotifications") { seenNotifications = Set(saved.split(separator: ",").map(String.init)) }305        let firstRun = store.meta("seenNotifications") == nil306        for n in list where !n.read && !seenNotifications.contains(n.id) {307            seenNotifications.insert(n.id)308            if firstRun { continue } // do not replay the account's history on a new device309            if n.kind.hasPrefix("request.") { Notifier.post(.deposit, title: "Nouveau dépôt reçu", body: n.data["title"].map { "Des fichiers ont été déposés par le lien « \($0) »." } ?? "Des fichiers ont été déposés dans ton Drive.") }310        }311        store.setMeta("seenNotifications", seenNotifications.suffix(300).joined(separator: ","))312    }313314    // MARK: Files app315316    private var domainIdentifier: NSFileProviderDomainIdentifier? { account?.user.map { NSFileProviderDomainIdentifier($0.id) } ?? store.meta("user").map { NSFileProviderDomainIdentifier($0) } }317318    private func registerFileProviderDomain() async {319        guard let id = domainIdentifier else { return }320        let existing = (try? await NSFileProviderManager.domains()) ?? []321        for d in existing where d.identifier != id { try? await NSFileProviderManager.remove(d) }322        if !existing.contains(where: { $0.identifier == id }) {323            do { try await NSFileProviderManager.add(NSFileProviderDomain(identifier: id, displayName: "SP Drive")) }324            catch { Log.provider.error("could not register the Files location: \(error.localizedDescription, privacy: .public)") }325        }326    }327328    private func removeFileProviderDomains() async {329        for d in (try? await NSFileProviderManager.domains()) ?? [] { try? await NSFileProviderManager.remove(d) }330        try? FileManager.default.removeItem(at: AppGroup.fileProviderState)331    }332333    /// After a new sign-in or the return of the network, tells the system that what stopped the Files location is over;334    /// without this, Files keeps showing the location in error until the system retries on its own.335    private func resolveFileProviderErrors() {336        guard let id = domainIdentifier, let manager = NSFileProviderManager(for: NSFileProviderDomain(identifier: id, displayName: "SP Drive")) else { return }337        for code in [NSFileProviderError.notAuthenticated, .serverUnreachable, .cannotSynchronize] {338            manager.signalErrorResolved(NSFileProviderError(code)) { _ in }339        }340        manager.signalEnumerator(for: .workingSet) { _ in }341    }342343    /// Tells the Files app that the Drive changed, so its listing follows what the app just learnt.344    private func signalFileProvider() {345        guard let id = domainIdentifier, let manager = NSFileProviderManager(for: NSFileProviderDomain(identifier: id, displayName: "SP Drive")) else { return }346        manager.signalEnumerator(for: .workingSet) { _ in }347    }348349    var filesLocationRegistered: Bool { get async { !((try? await NSFileProviderManager.domains()) ?? []).isEmpty } }350351    // MARK: Helpers for views352353    /// Runs a user action; a failure is shown instead of being swallowed.354    func perform(success: String? = nil, _ action: () async throws -> Void) async {355        do {356            try await action()357            if let success { toast = Toast(text: success, style: .success) }358        } catch is CancellationError {359        } catch {360            Haptics.error()361            toast = Toast(text: Self.describe(error), style: .error)362        }363    }364365    static func describe(_ error: Error) -> String {366        if let e = error as? RemoteError {367            switch e {368            case .unauthenticated: return "Session expirée. Connecte-toi à nouveau."369            case .notFound: return "Cet élément n’existe plus sur le Drive."370            case .nameConflict(let name): return "Un élément nommé « \(name) » existe déjà ici."371            case .versionConflict: return "Le fichier a changé sur le serveur."372            case .quotaExceeded: return "Espace de stockage insuffisant sur le Drive."373            case .fileTooLarge: return "Ce fichier dépasse la taille maximale acceptée."374            case .infected: return "Ce fichier a été signalé par l’antivirus."375            case .rateLimited: return "Trop de requêtes. Réessaie dans un instant."376            case .offline: return "MacLustr est injoignable. Vérifie ta connexion."377            case .server(_, let code, let message):378                switch code {379                case "reauth_required": return "Cette opération demande une confirmation récente par clé d’accès."380                case "bad_expiry": return "La date d’expiration doit être dans le futur."381                case "authentication_failed": return "Cette clé d’accès n’est pas reconnue par SP Drive."382                case "infected": return "Un fichier signalé par l’antivirus ne peut pas être partagé."383                default: return message.isEmpty ? "Le serveur a refusé l’opération." : "Le serveur a refusé l’opération (\(message))."384                }385            default: return "L’opération a échoué."386            }387        }388        if let e = error as? EngineError {389            switch e {390            case .invalidName: return "Ce nom n’est pas valide."391            case .notAvailableOffline: return "Ce fichier n’est pas sur cet appareil. Connecte-toi à Internet pour l’ouvrir."392            case .notFound: return "Élément introuvable."393            case .cancelled: return "Annulé."394            case .transferFailed(let code): return code == "infected" ? "Ce fichier a été signalé par l’antivirus." : "Le transfert a échoué."395            }396        }397        if let e = error as? LocalizedError, let d = e.errorDescription { return d }398        return "L’opération a échoué."399    }400401    func badge(_ item: DriveItem) -> SyncBadge { _ = itemsVersion; _ = transfersVersion; _ = conflictsVersion; return engine.badge(for: item, online: network.online) }402    /// The reason shared by held transfers, most blocking first (for the transfer pill and the banner of the transfer centre).403    var dominantHold: TransferPolicy.Hold? {404        let all = Set(transferHolds.values)405        return TransferPolicy.Hold.allCases.first { all.contains($0) }406    }407    var rootID: String? { _ = itemsVersion; return store.rootID }408    var conflictCount: Int { _ = conflictsVersion; return store.conflicts().count }409    var problemCount: Int { _ = itemsVersion; _ = conflictsVersion; return store.conflicts().count + store.ops().filter { $0.state == .failed }.count }410    var activeTransferCount: Int { _ = transfersVersion; return store.transfers(states: [.queued, .running]).count }411}412413enum Haptics {414    @MainActor static func tap() { UIImpactFeedbackGenerator(style: .light).impactOccurred() }415    @MainActor static func selection() { UISelectionFeedbackGenerator().selectionChanged() }416    @MainActor static func lift() { UIImpactFeedbackGenerator(style: .medium).impactOccurred() }417    @MainActor static func success() { UINotificationFeedbackGenerator().notificationOccurred(.success) }418    @MainActor static func warning() { UINotificationFeedbackGenerator().notificationOccurred(.warning) }419    @MainActor static func error() { UINotificationFeedbackGenerator().notificationOccurred(.error) }420}421
Files main
Menu

Theme