SPB Git

Repository Public

AccountModel.swift 5.1 KB 103 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Account/AccountModel.swift3// Description: Observable account state: local-only use, passkey sign-in, session ended by the server, sign-out with an explicit choice about the local copy.4import SwiftUI5import SPNotesAPI6import SPNotesStore78/// The application is fully usable without an account (notes stay on this Mac). Signing in adds synchronisation.9/// A session that ends (expiry, revocation) never erases anything: notes stay readable and editable, and are sent10/// after the next sign-in.11@Observable final class AccountModel {12    enum Phase: Equatable { case local, signedIn, expired }13    private(set) var phase: Phase14    private(set) var isWorking = false15    var message: String?16    private(set) var displayName: String?17    /// The stored state has been read: the interface can decide between the welcome screen and the library.18    private(set) var isReady = false19    @ObservationIgnored weak var env: AppEnvironment?20    @ObservationIgnored private let http: HTTPClient21    @ObservationIgnored private let api: NotesAPI22    @ObservationIgnored private let auth: AuthService23    @ObservationIgnored private var watcher: Task<Void, Never>?2425    init(http: HTTPClient, api: NotesAPI, auth: AuthService, hasToken: Bool) {26        self.http = http; self.api = api; self.auth = auth27        phase = hasToken ? .signedIn : .local28    }2930    var isSignedIn: Bool { phase == .signedIn }3132    func start() async {33        if let meta = try? await env?.store.meta("account.everSignedIn"), meta == "1", phase == .local { phase = .expired }34        displayName = (try? await env?.store.meta("account.displayName")) ?? nil35        isReady = true36        watcher = Task { [weak self] in37            guard let self else { return }38            for await event in await self.http.sessionEvents() {39                switch event {40                case .signedIn, .tokenRotated: break41                case .signedOut(let reason): if reason != .local { self.sessionEnded() }42                }43            }44        }45    }4647    private func sessionEnded() {48        guard phase == .signedIn else { return }49        phase = .expired50        message = "Session terminée (expirée ou révoquée). Tes notes restent sur ce Mac ; reconnecte-toi pour reprendre la synchronisation."51        env?.syncMonitor.refresh()52    }5354    func signIn() async {55        guard !isWorking else { return }56        isWorking = true; message = nil57        defer { isWorking = false }58        do {59            _ = try await auth.signIn()60            phase = .signedIn61            try? await env?.store.setMeta("account.everSignedIn", "1")62            env?.syncMonitor.syncNow()63        } catch let e as PasskeyError { message = Self.describe(e) }64        catch let e as APIError { message = e.isOffline ? "Hors ligne : la connexion demande Internet. Tes notes locales restent disponibles." : e.message }65        catch { message = "La vérification n'a pas abouti." }66    }6768    static func describe(_ e: PasskeyError) -> String? {69        switch e {70        case .cancelled: return nil71        case .noCredentials: return "Aucune clé d'accès pour note.spboucher.ai n'est disponible sur ce Mac. Ajoute-en une depuis un appareil déjà connecté (Réglages → Sécurité du site), ou utilise le trousseau iCloud."72        case .alreadyRegistered: return "Ce Mac possède déjà une clé d'accès pour ce compte."73        case .notInteractive: return "La vérification demande une fenêtre active."74        case .inProgress: return "Une vérification est déjà en cours."75        case .notAssociated: return "macOS n'a pas (encore) validé l'association entre cette application et note.spboucher.ai. Vérifie la connexion Internet, puis réessaie dans quelques minutes."76        case .invalidOptions, .failed: return "La vérification par clé d'accès n'a pas abouti. Vérifie que Touch ID ou le trousseau iCloud est disponible."77        }78    }7980    /// Ends the session on the server and on this Mac. `eraseLocal` also removes the local copy (notes, files, index);81    /// the caller has confirmed it with the owner and warned about changes that were never sent.82    func signOut(eraseLocal: Bool) async {83        await env?.flushAll()84        await auth.signOut()85        phase = .local; displayName = nil; message = nil86        if eraseLocal, let env {87            for s in env.openSessions { env.forget(noteId: s.id) }88            try? await env.store.wipeAll()89            try? FileManager.default.removeItem(at: env.files.directory); try? FileManager.default.createDirectory(at: env.files.directory, withIntermediateDirectories: true)90            ImageCache.shared.clear()91            await env.platform.clearIndex()   // nothing of the erased notes stays in Spotlight92            await env.library.reload()93        } else { try? await env?.store.setMeta("account.everSignedIn", "1"); phase = .expired }94        env?.syncMonitor.refresh()95    }9697    func noteWorkspace(displayName: String?) async {98        guard let displayName, displayName != self.displayName else { return }99        self.displayName = displayName100        try? await env?.store.setMeta("account.displayName", displayName)101    }102}103
Files main
Menu

Theme