SPB Git

Repository Public

AdminAndDevices.swift 10.1 KB 133 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/AdminAndDevices.swift3// Description: The devices dashboard (every session of the account with its platform, app version and last activity, revocable) and, for administrators only, the infrastructure view of the server: worker, job queue, conversions, antivirus signatures, content index, event streams, backups. Read-only: no control surface.4import SPDriveCore5import SPDriveNext6import SwiftUI78struct DevicesSection: View {9    let model: AppModel10    @State private var sessions: Loadable<[NextSession]> = .loading11    var body: some View {12        Section("Appareils connectés") {13            switch sessions {14            case .loading: Text("Chargement…").foregroundStyle(.secondary)15            case .failed(let m): Text(m).foregroundStyle(.secondary)16            case .ready(let list):17                ForEach(list) { d in18                    HStack(spacing: SPDTheme.Space.md) {19                        Image(systemName: symbol(d)).font(.title3).foregroundStyle(d.current ? SPDTheme.brand : SPDTheme.textSecondary).frame(width: 26)20                        VStack(alignment: .leading, spacing: 1) {21                            HStack(spacing: 6) {22                                Text(d.deviceName?.isEmpty == false ? d.deviceName! : (d.kind == "device" ? "Application" : "Navigateur")).lineLimit(1)23                                if d.current { SPDPill(text: "Cet appareil", tint: SPDTheme.brand) }24                            }25                            Text([platform(d), d.client.map { "SP Drive \($0.version)" }, "vu \(Fmt.relative(d.lastSeenAt))", d.ip].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)26                            Text("Connecté le \(Fmt.date(d.createdAt)) par \(d.method == "passkey" ? "passkey" : d.method)").font(.caption2).foregroundStyle(.tertiary)27                        }28                        Spacer()29                        if !d.current { Button("Révoquer") { Task { try? await model.next?.revokeSession(d.id); await load() } }.controlSize(.small).help("Ferme cette session immédiatement") }30                    }31                    .accessibilityElement(children: .contain).accessibilityIdentifier("device-row")32                }33            }34        }35        .task { await load() }36    }37    private func symbol(_ d: NextSession) -> String {38        switch d.client?.platform { case "macos": "laptopcomputer"; case "ios": "iphone"; case "ipados": "ipad"; default: d.kind == "device" ? "desktopcomputer" : "globe" }39    }40    private func platform(_ d: NextSession) -> String? {41        guard let c = d.client else { return d.kind == "device" ? "Application (version non déclarée)" : "Navigateur web" }42        let name = ["macos": "macOS", "ios": "iOS", "ipados": "iPadOS"][c.platform] ?? c.platform43        return c.os.map { "\(name) \($0)" } ?? name44    }45    private func load() async {46        guard let next = model.next else { return }47        do { sessions = .ready(try await next.sessions()) } catch { sessions = .failed(NextText.error(error)) }48    }49}5051struct AdminView: View {52    @Environment(AppModel.self) private var model53    @State private var system: Loadable<AdminSystem> = .loading54    var body: some View {55        ScrollView {56            switch system {57            case .loading: ProgressView().padding(40)58            case .failed(let m): SPDEmptyState(symbol: "server.rack", title: "Vue indisponible", message: m) { Button("Réessayer") { Task { await load() } } }59            case .ready(let s): content(s).padding(20).frame(maxWidth: 860, alignment: .leading)60            }61        }62        .background(SPDTheme.surface)63        .navigationTitle("Administration").navigationSubtitle("Infrastructure du serveur — lecture seule")64        .toolbar { ToolbarItem { Button { Task { await load() } } label: { Label("Actualiser", systemImage: "arrow.clockwise") } } }65        .task { await load() }66        .accessibilityIdentifier("admin-view")67    }68    @ViewBuilder private func content(_ s: AdminSystem) -> some View {69        let raw = s.raw70        VStack(alignment: .leading, spacing: 18) {71            card("Serveur", "server.rack") {72                line("Version", s.version ?? "—")73                line("Fonctions actives", s.features.joined(separator: ", "))74                if let e = raw["events"]?.object { line("Flux d’événements ouverts", "\(e["streams"]?.int ?? 0) pour \(e["owners"]?.int ?? 0) compte(s)") }75            }76            card("Traitements", "gearshape.2") {77                state("Processus de traitement", s.worker?.alive, yes: "actif\(s.worker?.heartbeatAgeS.map { " · dernier signe de vie il y a \(Fmt.duration($0))" } ?? "")", no: "aucun signe de vie depuis plus de 3 minutes", unknown: "jamais vu")78                if s.jobs.isEmpty { Text("Aucune tâche en file ni terminée depuis 24 h.").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary) }79                ForEach(s.jobs) { j in80                    HStack { Text(j.kind).font(SPDTheme.Typo.mono); SPDPill(text: j.status, tint: j.status == "failed" ? SPDTheme.critical : j.status == "done" ? SPDTheme.positive : SPDTheme.warning); Spacer(); Text("\(j.count)\(j.oldestAgeS.map { " · la plus ancienne attend depuis \(Fmt.duration($0))" } ?? "")").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit() }81                }82                ForEach(s.previewFailures) { f in Label("Aperçus « \(f.kind) » en échec : \(f.count)\(f.lastError.map { " — \($0)" } ?? "")", systemImage: "exclamationmark.triangle").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.warning).lineLimit(2) }83            }84            card("Outils du nœud", "wrench.and.screwdriver") {85                state("Convertisseur de documents", raw["converter"]?["available"]?.bool, yes: raw["converter"]?["path"]?.string ?? "disponible", no: "absent : pas d’aperçu ni d’indexation des anciens formats Office", unknown: "pas encore rapporté")86                state("Extraction de texte et OCR", raw["textkit"]?["available"]?.bool, yes: raw["textkit"]?["contextual"]?.bool == true ? "disponible, avec le modèle de phrases" : "disponible, sans modèle de phrases", no: "absent", unknown: "pas encore rapporté")87                if let av = raw["antivirusSignatures"]?.object { line("Antivirus", "moteur \(av["engine"]?.string ?? "?") · \(av["signatures"]?.int ?? 0) signatures\(av["ageS"]?.double.map { " · mises à jour il y a \(Fmt.duration($0))" } ?? "")") }88                else { line("Antivirus", "aucune information rapportée") }89            }90            if let index = raw["index"]?.object {91                card("Index du contenu", "text.magnifyingglass") {92                    state("Indexation", index["enabled"]?.bool, yes: index["ocr"]?.bool == true ? "active, avec OCR" : "active, sans OCR", no: "désactivée", unknown: "?")93                    if let by = index["byStatus"]?.object, !by.isEmpty { line("Contenus", by.sorted { $0.key < $1.key }.map { "\($0.key) : \($0.value.int ?? 0)" }.joined(separator: " · ")) }94                    if let sem = index["semantic"]?.object { state("Recherche par le sens", sem["available"]?.bool, yes: "\(sem["model"]?.string ?? "modèle") · \(sem["dim"]?.int ?? 0) dimensions", no: "indisponible", unknown: "?") }95                }96            }97            if let b = raw["backup"]?.object {98                card("Sauvegardes", "externaldrive.badge.timemachine") {99                    line("Dossier", b["dir"]?.string ?? "—")100                    backup("Dernière sauvegarde", b["last"]) { o in "\(Fmt.bytes(Int64(o["dumpBytes"]?.double ?? 0))) de base, \(o["blobs"]?.int ?? 0) objets" }101                    backup("Essai de restauration", b["restoreTest"]) { o in "\(o["files"]?.int ?? 0) fichiers relus" }102                    backup("Vérification", b["verify"]) { o in "\(o["sampled"]?.int ?? 0) objets contrôlés, \(o["mismatched"]?.int ?? 0) différents, \(o["missing"]?.int ?? 0) manquants" }103                    backup("Copie hors du nœud", b["offNode"]) { o in o["host"]?.string ?? "" }104                }105            }106        }107    }108    private func backup(_ title: String, _ v: NextJSON?, detail: ([String: NextJSON]) -> String) -> some View {109        Group {110            if let o = v?.object { state(title, o["ok"]?.bool, yes: "\(detail(o))\(o["ageS"]?.double.map { " · il y a \(Fmt.duration($0))" } ?? "")", no: o["error"]?.string ?? "échec", unknown: "état inconnu") }111            else { state(title, nil, yes: "", no: "", unknown: "jamais exécuté sur ce serveur") }112        }113    }114    private func state(_ title: String, _ ok: Bool?, yes: String, no: String, unknown: String) -> some View {115        HStack(alignment: .firstTextBaseline) {116            Image(systemName: ok == true ? "checkmark.circle.fill" : ok == false ? "xmark.octagon.fill" : "questionmark.circle").foregroundStyle(ok == true ? SPDTheme.positive : ok == false ? SPDTheme.critical : SPDTheme.textTertiary)117            Text(title).font(SPDTheme.Typo.callout)118            Spacer(minLength: 12)119            Text(ok == true ? yes : ok == false ? no : unknown).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).multilineTextAlignment(.trailing).lineLimit(2)120        }.accessibilityElement(children: .combine)121    }122    private func line(_ label: String, _ value: String) -> some View {123        HStack(alignment: .firstTextBaseline) { Text(label).font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary); Spacer(minLength: 12); Text(value).font(SPDTheme.Typo.callout).multilineTextAlignment(.trailing).textSelection(.enabled) }124    }125    private func card<C: View>(_ title: String, _ symbol: String, @ViewBuilder _ content: () -> C) -> some View {126        VStack(alignment: .leading, spacing: 10) { Label(title, systemImage: symbol).font(SPDTheme.Typo.headline); content() }.frame(maxWidth: .infinity, alignment: .leading).spdCard()127    }128    private func load() async {129        guard let next = model.next else { return }130        do { system = .ready(try await next.adminSystem()) } catch { system = .failed(NextError.wrap(error).isNotFound ? "Cette vue est réservée aux administrateurs du serveur." : NextText.error(error)) }131    }132}133
Files main
Menu

Theme