SPB Git

Repository Public

SettingsScreen.swift 15.4 KB 302 lines swift

1// SP Drive iOS2// File: Features/Settings/SettingsScreen.swift3// Description: Settings: account, storage, synchronisation, app lock, Files app location, notifications, about, and sign-out.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import UIKit9import UserNotifications1011/// Whether the user turned notifications off for SP Drive in iOS settings (in which case the in-app toggles have no effect).12private func systemNotificationsDenied() async -> Bool {13    await UNUserNotificationCenter.current().notificationSettings().authorizationStatus == .denied14}1516struct SettingsScreen: View {17    @Environment(AppModel.self) private var model18    @Environment(\.scenePhase) private var scenePhase19    /// Read by the sync engine's policy (`DeviceConditions.policy`): a change applies to the queue at once.20    @AppStorage("transfers.cellular") private var cellularTransfers = true21    @AppStorage("transfers.lowData") private var backgroundInLowData = false22    @AppStorage("transfers.lowPower") private var pauseInLowPower = true23    /// Bandwidth cap in kB/s, 0 = none (contract §3).24    @AppStorage("transfers.bandwidthKB") private var bandwidthKB = 025    @State private var syncing = false26    @State private var filesRegistered: Bool?27    @State private var notificationsDenied = false28    @State private var confirmSignOut = false29    @State private var signingOut = false3031    var body: some View {32        let pending = model.pendingWorkCount33        let lockKind = model.lock.kind3435        List {36            accountSection37            storageSection38            syncSection(pending: pending)39            securitySection(kind: lockKind)40            AISettingsSection()41            nextSection42            filesSection43            notificationsSection44            aboutSection45            Section {46                Button(role: .destructive) { confirmSignOut = true } label: {47                    HStack {48                        Label("Se déconnecter", systemImage: "rectangle.portrait.and.arrow.right")49                        if signingOut { Spacer(); ProgressView() }50                    }51                }52                .disabled(signingOut)53                .accessibilityIdentifier("settings.signOut")54            } footer: {55                Text("Se déconnecter retire de \(DeviceWording.thisDevice) les copies hors ligne et les données de SP Drive. Rien n’est supprimé du Drive.")56            }57        }58        .listStyle(.insetGrouped)59        .navigationTitle("Paramètres")60        .accessibilityIdentifier("settings.list")61        .task(id: scenePhase) {62            guard scenePhase == .active else { return }63            filesRegistered = await model.filesLocationRegistered64            notificationsDenied = await systemNotificationsDenied()65        }66        .confirmationDialog("Se déconnecter de SP Drive ?", isPresented: $confirmSignOut, titleVisibility: .visible) {67            Button(pending > 0 ? "Se déconnecter et perdre \(pending) changement\(pending > 1 ? "s" : "")" : "Se déconnecter", role: .destructive) {68                signingOut = true69                Task { await model.signOut(); signingOut = false }70            }71            .accessibilityIdentifier("settings.confirmSignOut")72            Button("Annuler", role: .cancel) {}73        } message: {74            if pending > 0 {75                Text("Attention : \(pending) changement\(pending > 1 ? "s" : "") fait\(pending > 1 ? "s" : "") sur \(DeviceWording.thisDevice) \(pending > 1 ? "n’ont" : "n’a") pas encore été envoyé\(pending > 1 ? "s" : "") au Drive et \(pending > 1 ? "seront perdus" : "sera perdu"). Toutes les copies hors ligne seront aussi retirées de cet appareil. Pour ne rien perdre, annule et laisse la synchronisation se terminer.")76            } else {77                Text("Toutes les copies hors ligne seront retirées de \(DeviceWording.thisDevice). Tes fichiers restent sur le Drive.")78            }79        }80    }8182    // MARK: Sections8384    private var accountSection: some View {85        Section("Compte") {86            NavigationLink(destination: AccountScreen()) {87                HStack(spacing: 12) {88                    Image(systemName: "person.crop.circle.fill")89                        .font(.system(size: 40))90                        .foregroundStyle(Theme.gradient)91                        .accessibilityHidden(true)92                    if let user = model.account?.user {93                        VStack(alignment: .leading, spacing: 2) {94                            Text(user.displayName.isEmpty ? user.email : user.displayName).font(.headline)95                            Text(user.email).font(.subheadline).foregroundStyle(.secondary)96                            Text(RoleWording.label(user.role)).font(.caption).foregroundStyle(.secondary)97                        }98                    } else {99                        VStack(alignment: .leading, spacing: 2) {100                            Text("Compte").font(.headline)101                            Text(model.network.online ? "Chargement…" : "Détails indisponibles hors ligne").font(.subheadline).foregroundStyle(.secondary)102                        }103                    }104                }105                .padding(.vertical, 2)106                .accessibilityElement(children: .combine)107            }108            .accessibilityIdentifier("settings.account")109        }110    }111112    private var storageSection: some View {113        Section("Stockage") {114            NavigationLink(destination: StorageScreen()) {115                VStack(alignment: .leading, spacing: 6) {116                    Label("Stockage", systemImage: "internaldrive")117                    if let q = model.account?.quota, q.limit > 0 {118                        ProgressView(value: min(1, Double(q.used) / Double(q.limit)))119                            .tint(q.used >= q.limit ? .red : Color("AccentColor"))120                            .accessibilityHidden(true)121                        Text("\(q.used.byteString) utilisés sur \(q.limit.byteString)").font(.caption).foregroundStyle(.secondary)122                    } else {123                        Text("Espace du Drive et de cet appareil").font(.caption).foregroundStyle(.secondary)124                    }125                }126                .accessibilityElement(children: .combine)127            }128            .accessibilityIdentifier("settings.storage")129        }130    }131132    private func syncSection(pending: Int) -> some View {133        Section {134            SyncStatusLabel()135            Button {136                syncing = true137                Task { await model.refresh(); syncing = false }138            } label: {139                HStack {140                    Label("Synchroniser maintenant", systemImage: "arrow.triangle.2.circlepath")141                    if syncing { Spacer(); ProgressView() }142                }143            }144            .disabled(syncing || !model.network.online)145            .accessibilityIdentifier("settings.syncNow")146            LabeledContent {147                Text(pending == 0 ? "Aucune" : "\(pending)").monospacedDigit()148            } label: {149                Label("Changements en attente d’envoi", systemImage: "clock.arrow.2.circlepath")150            }151            .accessibilityIdentifier("settings.pending")152            Toggle(isOn: $cellularTransfers) { Label("Transferts sur réseau cellulaire", systemImage: "antenna.radiowaves.left.and.right") }153                .accessibilityIdentifier("settings.cellular")154            Toggle(isOn: $pauseInLowPower) { Label("Suspendre les copies hors ligne en mode économie d’énergie", systemImage: "battery.25percent") }155                .accessibilityIdentifier("settings.lowPower")156            Toggle(isOn: $backgroundInLowData) { Label("Copies hors ligne en mode données réduites", systemImage: "antenna.radiowaves.left.and.right.slash") }157                .accessibilityIdentifier("settings.lowData")158            Picker(selection: $bandwidthKB) {159                Text("Aucune").tag(0)160                ForEach([256, 512, 1024, 2048, 5120, 10240], id: \.self) { Text(Int64($0 * 1024).byteString + "/s").tag($0) }161            } label: { Label("Limite de débit des transferts", systemImage: "speedometer") }162            .accessibilityIdentifier("settings.bandwidth")163            LabeledContent { Text(model.listenerMode == .streaming ? "En direct (flux du serveur)" : "Toutes les 30 secondes") } label: { Label("Arrivée des changements", systemImage: "dot.radiowaves.left.and.right") }164                .accessibilityIdentifier("settings.listener")165                .task(id: model.itemsVersion) { await model.refreshListenerMode() }166            if let hold = model.dominantHold, model.network.online {167                Label(hold.explanation, systemImage: hold.symbol).font(.footnote).foregroundStyle(SPDTheme.Palette.warning).accessibilityIdentifier("settings.hold")168            }169        } header: {170            Text("Synchronisation")171        } footer: {172            Text(model.network.online173                 ? "Les changements faits ici partent tout de suite ; ceux des autres appareils arrivent en quelques secondes quand l’app est ouverte."174                 : "Hors ligne : tes changements sont gardés sur cet appareil et partiront au retour du réseau.")175        }176    }177178    private func securitySection(kind: BiometricLock.Kind) -> some View {179        Section {180            Toggle(isOn: Binding(get: { model.lock.isEnabled }, set: { on in Task { await model.lock.setEnabled(on) } })) {181                Label(kind == .none ? "Verrouiller l’app" : "Verrouiller avec \(model.lock.kindLabel)", systemImage: lockSymbol(kind))182            }183            .disabled(kind == .none)184            .accessibilityIdentifier("settings.lock")185        } header: {186            Text("Sécurité")187        } footer: {188            Text(kind == .none189                 ? "Indisponible : cet appareil n’a ni code ni biométrie configurés. Ajoute un code dans Réglages pour pouvoir verrouiller SP Drive."190                 : "SP Drive demandera \(model.lock.kindLabel) à l’ouverture et après une minute en arrière-plan. La vérification est faite par iOS ; l’app ne voit jamais tes données biométriques.")191        }192    }193194    private func lockSymbol(_ kind: BiometricLock.Kind) -> String {195        switch kind {196        case .faceID: "faceid"; case .touchID: "touchid"; case .opticID: "opticid"; case .passcode: "lock.fill"; case .none: "lock.slash"197        }198    }199200    private var filesSection: some View {201        Section {202            LabeledContent {203                switch filesRegistered {204                case .some(true): Label("Active", systemImage: "checkmark.circle.fill").foregroundStyle(.green).labelStyle(.titleAndIcon)205                case .some(false): Label("Inactive", systemImage: "exclamationmark.circle").foregroundStyle(.orange).labelStyle(.titleAndIcon)206                case .none: ProgressView()207                }208            } label: {209                Label("Emplacement SP Drive", systemImage: "folder.badge.gearshape")210            }211            .accessibilityElement(children: .combine)212            .accessibilityIdentifier("settings.filesLocation")213        } header: {214            Text("App Fichiers")215        } footer: {216            Text(filesRegistered == false217                 ? "L’emplacement n’est pas enregistré auprès d’iOS. Il est recréé à la prochaine connexion ; s’il reste absent, déconnecte-toi puis reconnecte-toi."218                 : "Ton Drive apparaît dans l’app Fichiers, sous Emplacements. À la première ouverture, Fichiers demande d’activer SP Drive : touche « Activer ». S’il n’apparaît pas, touche « ⋯ » puis « Modifier » et active SP Drive.")219        }220    }221222    private var notificationsSection: some View {223        Section {224            ForEach(Notifier.Family.allCases, id: \.rawValue) { NotificationFamilyToggle(family: $0) }225            Button {226                if let url = URL(string: UIApplication.openNotificationSettingsURLString) { UIApplication.shared.open(url) }227            } label: {228                Label("Réglages de notification d’iOS", systemImage: "arrow.up.forward.app")229            }230            .accessibilityIdentifier("settings.notifications.system")231        } header: {232            Text("Notifications")233        } footer: {234            Text(notificationsDenied235                 ? "Les notifications de SP Drive sont désactivées dans les réglages d’iOS : ces choix n’auront d’effet qu’une fois réactivées."236                 : "Peu de notifications, seulement utiles. Les réglages d’iOS ont toujours le dernier mot.")237        }238    }239240    /// Screens of SP Drive 2.0 that live in Settings; each only when the server supports it.241    @ViewBuilder private var nextSection: some View {242        Section("Compte et serveur") {243            NavigationLink { DevicesScreen() } label: { Label("Appareils connectés", systemImage: "laptopcomputer.and.iphone") }.accessibilityIdentifier("settings.devices")244            if model.next.has(.storage) { NavigationLink { StorageCenter() } label: { Label("Centre de stockage", systemImage: "chart.pie") }.accessibilityIdentifier("settings.storageCenter") }245            if model.next.has(.activity) { NavigationLink { ActivityScreen(source: .account) } label: { Label("Activité du compte", systemImage: "clock.arrow.circlepath") } }246            if model.account?.user?.role == "admin", model.next.meta.api >= 2 { NavigationLink { AdminScreen() } label: { Label("Infrastructure (administration)", systemImage: "server.rack") }.accessibilityIdentifier("settings.admin") }247            LabeledContent("Serveur") { Text(model.next.meta.api >= 2 ? "SP Drive \(model.next.meta.version)" : "SP Drive 1.0").foregroundStyle(.secondary) }.accessibilityIdentifier("settings.serverVersion")248        }249    }250251    private var aboutSection: some View {252        Section {253            LabeledContent("Version", value: Self.versionString)254                .accessibilityIdentifier("settings.version")255            LabeledContent("Serveur", value: AppGroup.baseURL.host ?? AppGroup.baseURL.absoluteString)256                .accessibilityIdentifier("settings.server")257        } header: {258            Text("À propos")259        } footer: {260            Text("Tes fichiers sont chiffrés pendant leur transport (TLS) et au repos sur le serveur. Ce n’est pas un chiffrement de bout en bout : le serveur détient les clés et peut techniquement lire les contenus.")261        }262    }263264    private static var versionString: String {265        let info = Bundle.main.infoDictionary266        let version = info?["CFBundleShortVersionString"] as? String ?? "?"267        let build = info?["CFBundleVersion"] as? String ?? "?"268        return "\(version) (\(build))"269    }270}271272/// One notification family, stored under the key `Notifier` reads.273private struct NotificationFamilyToggle: View {274    let family: Notifier.Family275    @State private var isOn: Bool276277    init(family: Notifier.Family) {278        self.family = family279        _isOn = State(initialValue: family.isEnabled)280    }281282    var body: some View {283        Toggle(family.label, isOn: $isOn)284            .onChange(of: isOn) { _, on in UserDefaults.standard.set(on, forKey: family.defaultsKey) }285            .accessibilityIdentifier("settings.notify.\(family.rawValue)")286    }287}288289/// Role names sent by the server, in plain French.290enum RoleWording {291    static func label(_ role: String) -> String {292        switch role.lowercased() {293        case "owner": "Propriétaire"294        case "admin": "Administrateur"295        case "member", "user": "Membre"296        case "guest": "Invité"297        case "": "Compte"298        default: role.capitalized299        }300    }301}302
Files main
Menu

Theme