Repository Public
1// SP Music iOS2// File: Features/Account/AccountViews.swift3// Description: Sign-in (passkey, device link, enrolment link, recovery code) and account management.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import SPMusicCore9import SwiftUI10import UIKit1112@MainActor13func keyWindow() -> UIWindow {14 let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }15 return scenes.first { $0.activationState == .foregroundActive }?.keyWindow ?? scenes.first?.keyWindow ?? UIWindow()16}17@MainActor var deviceLabel: String { UIDevice.current.userInterfaceIdiom == .pad ? "SP Music — iPad" : "SP Music — iPhone" }1819/// Sign-in. A passkey of music.spboucher.ai is the normal way (Face ID / Touch ID, nothing to type). The others:20/// approving this device from a browser already signed in, an enrolment link from the administrator, a recovery code.21struct WelcomeView: View {22 @Environment(AppEnvironment.self) private var env23 @State private var busy = false24 @State private var error: String?25 @State private var sheet: Sheet?26 @State private var downloaded = 027 enum Sheet: String, Identifiable { case link, enrol, recovery; var id: String { rawValue } }2829 var body: some View {30 ZStack {31 Color.spBackground.ignoresSafeArea()32 RadialGradient(colors: [Color.spEmber.opacity(0.28), .clear], center: .top, startRadius: 10, endRadius: 520).ignoresSafeArea().accessibilityHidden(true)33 VStack(spacing: 22) {34 Spacer()35 LogoMark().frame(width: 112, height: 112)36 VStack(spacing: 8) {37 Text("SP Music").font(.system(size: 40, weight: .bold, design: .rounded))38 Text("Votre bibliothèque MacLustr,\nen diffusion et hors ligne.").font(.title3).multilineTextAlignment(.center).foregroundStyle(Color.spMuted)39 }40 Spacer()41 if let error { Text(error).font(.footnote).foregroundStyle(.yellow).multilineTextAlignment(.center).accessibilityIdentifier("login-error") }42 VStack(spacing: 12) {43 Button { passkey() } label: {44 HStack { if busy { ProgressView().tint(.black) } else { Image(systemName: "person.badge.key.fill") }; Text("Se connecter avec une clé d'accès") }45 }46 .buttonStyle(PrimaryButtonStyle()).disabled(busy || !env.isOnline).accessibilityIdentifier("login-passkey")47 Button { sheet = .link } label: { Label("Approuver depuis un autre appareil", systemImage: "qrcode") }48 .buttonStyle(SecondaryButtonStyle()).disabled(!env.isOnline).accessibilityIdentifier("login-device")49 HStack(spacing: 18) {50 Button("Lien d'inscription") { sheet = .enrol }51 Button("Code de récupération") { sheet = .recovery }.accessibilityIdentifier("login-recovery")52 }53 .font(.footnote.weight(.medium)).disabled(!env.isOnline)54 if downloaded > 0 {55 Button { env.auth.offlineGuest = true } label: { Label("Écouter la musique téléchargée (\(downloaded))", systemImage: "arrow.down.circle") }56 .font(.subheadline.weight(.semibold)).padding(.top, 6).accessibilityIdentifier("login-offline")57 }58 if !env.isOnline { Label("Hors ligne", systemImage: "wifi.slash").font(.footnote).foregroundStyle(Color.spMuted) }59 }60 .frame(maxWidth: 420)61 }62 .padding(24)63 }64 .tint(Color.spEmber)65 .sheet(item: $sheet) { s in66 switch s {67 case .link: DeviceLinkSheet()68 case .enrol: CodeEntrySheet(title: "Lien d'inscription", prompt: "Collez le lien reçu de l'administrateur", hint: "Le lien sert une seule fois. Une clé d'accès sera créée sur cet appareil et protégée par \(BiometricLock.kindName).", action: "Créer ma clé d'accès") { text in69 _ = try await env.auth.enrol(link: text, anchor: keyWindow(), deviceName: deviceLabel)70 }71 case .recovery: CodeEntrySheet(title: "Code de récupération", prompt: "xxxx-xxxx-xxxx", hint: "Chaque code ne fonctionne qu'une fois. Une fois connecté, ajoutez une clé d'accès depuis Réglages → Compte.", action: "Se connecter") { text in72 try await env.auth.signIn(recoveryCode: text)73 }74 }75 }76 .task { downloaded = await env.db.counts().downloadedTracks }77 }7879 private func passkey() {80 busy = true; error = nil81 Task {82 do { try await env.auth.signInWithPasskey(anchor: keyWindow()) }83 catch PasskeyError.cancelled {}84 catch { self.error = (error as? LocalizedError)?.errorDescription ?? "Connexion impossible." }85 busy = false86 }87 }88}8990/// The mark of the app: a broken ring around a play triangle, on the ember gradient (same drawing as the icon).91struct LogoMark: View {92 var body: some View {93 GeometryReader { g in94 let s = g.size.width95 ZStack {96 RoundedRectangle(cornerRadius: s * 0.24, style: .continuous).fill(.spBrand)97 Circle().trim(from: 0, to: 0.76).stroke(Color.spOnAccent, style: StrokeStyle(lineWidth: s * 0.066, lineCap: .round)).rotationEffect(.degrees(-38)).frame(width: s * 0.56, height: s * 0.56)98 Image(systemName: "play.fill").font(.system(size: s * 0.22, weight: .black)).foregroundStyle(Color.spOnAccent).offset(x: s * 0.015)99 }100 }101 .aspectRatio(1, contentMode: .fit).accessibilityHidden(true)102 }103}104105struct DeviceLinkSheet: View {106 @Environment(AppEnvironment.self) private var env107 @Environment(\.dismiss) private var dismiss108 @Environment(\.openURL) private var openURL109 @State private var link: DeviceLinkStart?110 @State private var error: String?111112 var body: some View {113 NavigationStack {114 VStack(spacing: 22) {115 if let link {116 Text("Sur un appareil déjà connecté à Music SP, ouvrez music.spboucher.ai/appareil et saisissez ce code :").multilineTextAlignment(.center).foregroundStyle(Color.spMuted)117 Text(link.userCode).font(.system(size: 44, weight: .bold, design: .monospaced)).textSelection(.enabled).accessibilityIdentifier("device-code")118 HStack { ProgressView(); Text("En attente de l'approbation…").foregroundStyle(Color.spMuted) }119 if let url = URL(string: link.verificationUrl) { Button("Ouvrir la page d'approbation dans Safari") { openURL(url) }.font(.subheadline) }120 Text("Le code est valable 10 minutes et ne sert qu'une fois. Cet appareil reçoit sa propre session, révocable depuis « Compte ».").font(.footnote).foregroundStyle(Color.spMuted).multilineTextAlignment(.center)121 } else if let error { ContentUnavailableView("Association impossible", systemImage: "exclamationmark.triangle", description: Text(error)) }122 else { ProgressView() }123 Spacer()124 }125 .padding(24)126 .navigationTitle("Approuver cet appareil").navigationBarTitleDisplayMode(.inline)127 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } }128 .task {129 do {130 let l = try await env.auth.startDeviceLink(deviceName: deviceLabel)131 link = l132 try await env.auth.awaitDeviceLink(l)133 dismiss()134 } catch is CancellationError {}135 catch { link = nil; self.error = (error as? LocalizedError)?.errorDescription ?? "Réessayez." }136 }137 }138 .presentationDetents([.medium, .large])139 }140}141142struct CodeEntrySheet: View {143 @Environment(\.dismiss) private var dismiss144 let title: String, prompt: String, hint: String, action: String145 let submit: @MainActor (String) async throws -> Void146 @State private var text = ""147 @State private var busy = false148 @State private var error: String?149150 var body: some View {151 NavigationStack {152 Form {153 Section { TextField(prompt, text: $text, axis: .vertical).textInputAutocapitalization(.never).autocorrectionDisabled().font(.body.monospaced()).accessibilityIdentifier("code-field") } footer: { Text(hint) }154 if let error { Section { Text(error).foregroundStyle(.yellow).accessibilityIdentifier("code-error") } }155 Section {156 Button { run() } label: { HStack { Text(action); Spacer(); if busy { ProgressView() } } }157 .disabled(busy || text.trimmingCharacters(in: .whitespacesAndNewlines).count < 8).accessibilityIdentifier("code-submit")158 }159 }160 .navigationTitle(title).navigationBarTitleDisplayMode(.inline)161 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } }162 }163 .presentationDetents([.medium, .large])164 }165 private func run() {166 busy = true; error = nil167 Task {168 do { try await submit(text); dismiss() }169 catch PasskeyError.cancelled {}170 catch { self.error = (error as? LocalizedError)?.errorDescription ?? "Refusé." }171 busy = false172 }173 }174}175176struct AccountView: View {177 @Environment(AppEnvironment.self) private var env178 @State private var passkeys: [PasskeyInfo] = []179 @State private var sessions: [SessionRow] = []180 @State private var message: String?181 @State private var confirmSignOut = false182183 var body: some View {184 List {185 if let me = env.auth.me, env.auth.state == .signedIn {186 Section("Compte") {187 row("Nom", me.displayName); row("Courriel", me.email); row("Rôle", me.role == "admin" ? (me.isOwner ? "Propriétaire" : "Administrateur") : "Auditeur")188 }189 Section {190 ForEach(passkeys) { k in191 VStack(alignment: .leading, spacing: 2) {192 Label(k.name, systemImage: "person.badge.key")193 Text("Créée \(k.createdAt?.formatted(date: .abbreviated, time: .omitted) ?? "—")" + (k.backedUp ? " · synchronisée" : "")).font(.footnote).foregroundStyle(Color.spMuted)194 }195 }196 Button { addPasskey() } label: { Label("Ajouter une clé d'accès sur cet appareil", systemImage: "plus") }.disabled(!env.isOnline)197 } header: { Text("Clés d'accès") } footer: { Text("Une clé d'accès remplace le mot de passe. \(BiometricLock.kindName) reste sur l'appareil : le serveur ne reçoit qu'une signature.") }198 Section("Sessions ouvertes") {199 ForEach(sessions) { s in200 VStack(alignment: .leading, spacing: 2) {201 HStack { Text(Self.client(s.userAgent)).lineLimit(1); if s.current { Text("cet appareil").font(.caption.weight(.semibold)).foregroundStyle(Color.spEmber) } }202 Text("Vue \(s.lastSeenAt?.formatted(.relative(presentation: .named)) ?? "—") · expire le \(s.expiresAt?.formatted(date: .abbreviated, time: .omitted) ?? "—")").font(.footnote).foregroundStyle(Color.spMuted)203 }204 .swipeActions { if !s.current { Button("Fermer", role: .destructive) { Task { try? await env.api.revokeSession(id: s.id); await load() } } } }205 }206 }207 if let message { Section { Text(message).font(.footnote) } }208 Section {209 Button("Se déconnecter", role: .destructive) { confirmSignOut = true }.accessibilityIdentifier("sign-out")210 } footer: { Text("La musique téléchargée reste sur l'appareil et se lit sans connexion. Vos listes et favoris reviennent à la prochaine connexion.") }211 } else {212 Section { Text("Vous n'êtes pas connecté.") }213 Section { Button("Se connecter") { env.auth.offlineGuest = false } }214 }215 }216 .scrollContentBackground(.hidden).background(Color.spBackground)217 .navigationTitle("Compte")218 .confirmationDialog("Se déconnecter de SP Music ?", isPresented: $confirmSignOut, titleVisibility: .visible) {219 Button("Se déconnecter", role: .destructive) { Task { await env.auth.signOut() } }220 }221 .task { await load() }222 }223 private func row(_ k: String, _ v: String) -> some View { HStack { Text(k); Spacer(); Text(v).foregroundStyle(Color.spMuted).lineLimit(1) } }224 private func load() async {225 guard env.isOnline, env.auth.state == .signedIn else { return }226 passkeys = (try? await env.api.passkeys()) ?? []227 sessions = (try? await env.api.sessions()) ?? []228 }229 private func addPasskey() {230 Task {231 do { try await env.auth.addPasskey(anchor: keyWindow(), deviceName: deviceLabel); message = "Clé d'accès ajoutée."; await load() }232 catch PasskeyError.cancelled {}233 catch { message = (error as? LocalizedError)?.errorDescription ?? "Ajout impossible." }234 }235 }236 static func client(_ ua: String) -> String {237 if ua.hasPrefix("SPMusic-iOS") { return ua.contains("iPad") ? "SP Music — iPad" : "SP Music — iPhone" }238 if ua.hasPrefix("SPMusic") { return "SP Music — Mac" }239 if ua.contains("iPhone") { return "Safari — iPhone" }240 if ua.contains("iPad") { return "Safari — iPad" }241 if ua.contains("Macintosh") { return "Navigateur — Mac" }242 return ua.isEmpty ? "Appareil inconnu" : String(ua.prefix(40))243 }244}245