Repository Public
1// SP Drive iOS2// File: Features/Account/AccountScreen.swift3// Description: The account: profile, passkeys (read-only) and the devices currently signed in, with the possibility to sign another device out.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI89struct AccountScreen: View {10 @Environment(AppModel.self) private var model11 @State private var passkeys: [PasskeyInfo]?12 @State private var sessions: [SessionInfo]?13 @State private var loadError: String?14 @State private var loading = false15 @State private var revokeCandidate: SessionInfo?16 @State private var revoking: Set<String> = []1718 var body: some View {19 let online = model.network.online20 List {21 profileSection22 if let loadError, passkeys == nil || sessions == nil {23 Section {24 VStack(alignment: .leading, spacing: 8) {25 Label(online ? loadError : "Hors ligne : les clés d’accès et les appareils connectés s’affichent quand le réseau revient.", systemImage: online ? "exclamationmark.triangle" : "wifi.slash")26 .foregroundStyle(.secondary)27 Button("Réessayer") { Task { await load() } }28 .buttonStyle(.bordered)29 .disabled(loading)30 .accessibilityIdentifier("account.retry")31 }32 .padding(.vertical, 4)33 .accessibilityIdentifier("account.loadError")34 }35 }36 passkeysSection37 sessionsSection38 }39 .listStyle(.insetGrouped)40 .navigationTitle("Compte")41 .accessibilityIdentifier("account.list")42 .refreshable { await load() }43 .task(id: online) { if online || (passkeys == nil && sessions == nil) { await load() } }44 .confirmationDialog("Déconnecter cet appareil ?", isPresented: revokeDialogShown, titleVisibility: .visible, presenting: revokeCandidate) { s in45 Button("Déconnecter « \(Self.title(of: s)) »", role: .destructive) { revoke(s) }46 .accessibilityIdentifier("account.confirmRevoke")47 Button("Annuler", role: .cancel) {}48 } message: { _ in49 Text("Cet appareil devra se reconnecter avec une clé d’accès pour retrouver ton Drive. Ses fichiers déjà téléchargés ne sont pas effacés à distance.")50 }51 }5253 private var revokeDialogShown: Binding<Bool> {54 Binding(get: { revokeCandidate != nil }, set: { if !$0 { revokeCandidate = nil } })55 }5657 // MARK: Loading5859 private func load() async {60 guard !loading else { return }61 loading = true62 defer { loading = false }63 await model.refreshAccount()64 do {65 async let keys = model.api.passkeys()66 async let devices = model.api.sessions()67 let (k, d) = try await (keys, devices)68 passkeys = k.sorted { $0.createdAt > $1.createdAt }69 // this device first, then the most recently seen70 sessions = d.sorted { $0.current != $1.current ? $0.current : $0.lastSeenAt > $1.lastSeenAt }71 loadError = nil72 } catch is CancellationError {73 } catch {74 loadError = AppModel.describe(error)75 }76 }7778 private func revoke(_ s: SessionInfo) {79 revoking.insert(s.id)80 Task {81 await model.perform(success: "« \(Self.title(of: s)) » a été déconnecté") {82 try await model.api.revokeSession(id: s.id)83 sessions?.removeAll { $0.id == s.id }84 }85 revoking.remove(s.id)86 }87 }8889 // MARK: Sections9091 private var profileSection: some View {92 Section("Profil") {93 if let user = model.account?.user {94 LabeledContent("Nom", value: user.displayName.isEmpty ? "—" : user.displayName)95 LabeledContent("Courriel", value: user.email)96 LabeledContent("Rôle", value: RoleWording.label(user.role))97 } else {98 Label(model.network.online ? "Chargement du profil…" : "Profil indisponible hors ligne", systemImage: model.network.online ? "hourglass" : "wifi.slash")99 .foregroundStyle(.secondary)100 }101 }102 }103104 private var passkeysSection: some View {105 Section {106 if let passkeys {107 if passkeys.isEmpty {108 Text("Aucune clé d’accès enregistrée.").foregroundStyle(.secondary)109 } else {110 ForEach(passkeys) { key in111 HStack(alignment: .top, spacing: 12) {112 Image(systemName: "person.badge.key.fill").font(.title3).foregroundStyle(Theme.gradient).frame(width: 32).accessibilityHidden(true)113 VStack(alignment: .leading, spacing: 3) {114 Text(key.label.isEmpty ? "Clé d’accès" : key.label).font(.body)115 Text(Self.passkeyKind(key)).font(.caption).foregroundStyle(.secondary)116 Text("Créée le \(key.createdAt.formatted(date: .abbreviated, time: .omitted)) · " + (key.lastUsedAt.map { "utilisée \($0.shortRelative)" } ?? "jamais utilisée"))117 .font(.caption).foregroundStyle(.secondary)118 }119 }120 .padding(.vertical, 2)121 .accessibilityElement(children: .combine)122 .accessibilityIdentifier("account.passkey.\(key.id)")123 }124 }125 } else if loadError == nil {126 loadingRow127 }128 } header: {129 Text("Clés d’accès")130 } footer: {131 Text("Lecture seule ici : les clés d’accès se gèrent sur drive.spboucher.ai.")132 }133 }134135 private var sessionsSection: some View {136 Section {137 if let sessions {138 if sessions.isEmpty {139 Text("Aucun appareil connecté.").foregroundStyle(.secondary)140 } else {141 ForEach(sessions) { s in142 sessionRow(s)143 .swipeActions(edge: .trailing, allowsFullSwipe: false) {144 if !s.current {145 Button(role: .destructive) { revokeCandidate = s } label: { Label("Déconnecter", systemImage: "rectangle.portrait.and.arrow.right") }146 }147 }148 .contextMenu {149 if !s.current {150 Button(role: .destructive) { revokeCandidate = s } label: { Label("Déconnecter cet appareil", systemImage: "rectangle.portrait.and.arrow.right") }151 }152 }153 .disabled(revoking.contains(s.id))154 .accessibilityIdentifier("account.session.\(s.id)")155 }156 }157 } else if loadError == nil {158 loadingRow159 }160 } header: {161 Text("Appareils connectés")162 } footer: {163 Text("Balaie un appareil vers la gauche pour le déconnecter. Pour déconnecter \(DeviceWording.thisDevice), utilise « Se déconnecter » dans les paramètres.")164 }165 }166167 private var loadingRow: some View {168 HStack(spacing: 10) { ProgressView(); Text("Chargement…").foregroundStyle(.secondary) }169 }170171 private func sessionRow(_ s: SessionInfo) -> some View {172 HStack(alignment: .top, spacing: 12) {173 Image(systemName: Self.symbol(of: s)).font(.title3).foregroundStyle(.secondary).frame(width: 32).accessibilityHidden(true)174 VStack(alignment: .leading, spacing: 3) {175 HStack(spacing: 8) {176 Text(Self.title(of: s)).font(.body).lineLimit(2)177 if s.current {178 Text("cet appareil")179 .font(.caption2.weight(.semibold))180 .padding(.horizontal, 7).padding(.vertical, 2)181 .background(Color("AccentColor").opacity(0.15), in: Capsule())182 .foregroundStyle(Color("AccentColor"))183 }184 }185 Text("\(Self.kindLabel(of: s)) · vu \(s.lastSeenAt.shortRelative)").font(.caption).foregroundStyle(.secondary)186 Text("IP \(s.ip.isEmpty ? "inconnue" : s.ip) · connecté le \(s.createdAt.formatted(date: .abbreviated, time: .omitted))")187 .font(.caption).foregroundStyle(.secondary)188 }189 if revoking.contains(s.id) { Spacer(minLength: 4); ProgressView() }190 }191 .padding(.vertical, 2)192 .accessibilityElement(children: .combine)193 }194195 // MARK: Wording196197 /// The name the device gave itself, or a readable summary of its user agent.198 static func title(of s: SessionInfo) -> String {199 if let n = s.deviceName?.trimmingCharacters(in: .whitespaces), !n.isEmpty { return n }200 let ua = s.userAgent201 if ua.isEmpty { return "Appareil inconnu" }202 let system: String? = ua.contains("iPhone") ? "iPhone" : ua.contains("iPad") ? "iPad" : ua.contains("Android") ? "Android" : ua.contains("Macintosh") || ua.contains("Mac OS") ? "Mac"203 : ua.contains("Windows") ? "Windows" : ua.contains("Linux") ? "Linux" : nil204 let browser: String? = ua.contains("Edg/") ? "Edge" : ua.contains("Firefox/") ? "Firefox" : ua.contains("Chrome/") ? "Chrome" : ua.contains("Safari/") ? "Safari" : nil205 switch (browser, system) {206 case let (b?, os?): return "\(b) sur \(os)"207 case let (b?, nil): return b208 case let (nil, os?): return os209 default: return String(ua.prefix(60))210 }211 }212213 static func kindLabel(of s: SessionInfo) -> String {214 switch s.kind?.lowercased() {215 case "native": "Application"216 case "web", "browser", "cookie": "Navigateur"217 case .some(let other) where !other.isEmpty: other.capitalized218 default: s.deviceName == nil ? "Navigateur" : "Application"219 }220 }221222 static func symbol(of s: SessionInfo) -> String {223 let text = (s.deviceName ?? "") + " " + s.userAgent224 if text.contains("iPad") { return "ipad" }225 if text.contains("iPhone") || text.contains("Android") { return "iphone" }226 if s.kind?.lowercased() == "native" { return "apps.iphone" }227 return "desktopcomputer"228 }229230 static func passkeyKind(_ key: PasskeyInfo) -> String {231 let type: String232 switch key.deviceType {233 case "multiDevice": type = "Synchronisée entre tes appareils"234 case "singleDevice": type = "Liée à un seul appareil"235 case "": type = "Clé d’accès"236 default: type = key.deviceType237 }238 return key.backedUp ? "\(type) · sauvegardée" : type239 }240}241