SPB Git

Repository Public

NotificationSettings.swift 15.4 KB 238 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/NotificationSettings.swift3// Description: Settings › Notifications — the account-wide push preferences kept by the server (enable, preview privacy, quiet hours with4// time zone, priority senders, per-mailbox switches, badge), this device (on / off, system permission), the list of the user's devices with5// removal, « send a test notification » and the server's push status. Every change is saved at once; what the server answers is shown.6import SPMailCore7import SPMailSystem8import SwiftUI9import UserNotifications10#if os(iOS)11import UIKit12#else13import AppKit14#endif1516struct NotificationSettings: View {17    @Bindable var model: AppModel18    @State private var newSender = ""19    @State private var senderError: String?20    @State private var testResult: String?21    @State private var removing: PushDevice?22    @State private var busy = false2324    private var push: PushRegistrar { model.system.push }25    private var prefs: PushPrefs { push.prefs ?? PushPrefs() }26    private var loaded: Bool { push.prefs != nil }2728    /// A binding on one field of the server preferences: the change is saved immediately.29    private func pref<T>(_ get: @escaping (PushPrefs) -> T, _ set: @escaping (inout PushPrefs, T) -> Void) -> Binding<T> {30        Binding(get: { get(prefs) }, set: { value in var p = prefs; set(&p, value); Task { await push.save(p) } })31    }3233    var body: some View {34        @Bindable var s = model.settings35        Form {36            Section {37                Toggle("Signaler les nouveaux messages", isOn: $s.notificationsEnabled)38                    .onChange(of: s.notificationsEnabled) { _, on in if on { Task { await push.userEnabledNotifications() } } }39                LabeledContent("Cet appareil") { Text(deviceStatus).foregroundStyle(deviceStatusIsProblem ? AnyShapeStyle(SPColor.danger) : AnyShapeStyle(.secondary)).multilineTextAlignment(.trailing) }40                if push.authorization == .denied {41                    Button("Ouvrir les réglages du système") { openSystemSettings() }42                }43                if let device = push.thisDevice {44                    Toggle("Recevoir les notifications sur cet appareil", isOn: Binding(get: { device.enabled }, set: { on in Task { await push.setDevice(device, enabled: on) } }))45                }46                Toggle("Suspendre les notifications", isOn: $s.notificationsPaused).disabled(!s.notificationsEnabled)47            } header: { Text("Cet appareil") } footer: {48                Text("Les notifications arrivent quand le serveur les envoie et que le système les remet ; SP Mail ne reste pas actif en arrière-plan. L’actualisation en arrière-plan dépend du système, de la batterie et du réseau.")49            }5051            if model.phase == .ready {52                Section {53                    Toggle("Notifications du compte", isOn: pref(\.enabled) { $0.enabled = $1 })54                    Picker("Aperçu", selection: pref({ $0.preview == .unknown ? .sender : $0.preview }) { $0.preview = $1 }) {55                        Text("Aucun — « Nouveau message »").tag(PushPreview.none)56                        Text("Expéditeur seulement").tag(PushPreview.sender)57                        Text("Expéditeur, objet et début du message").tag(PushPreview.full)58                    }59                    Toggle("Masquer l’expéditeur et l’objet sur cet appareil", isOn: $s.hideNotificationContent)60                    Picker("Pastille de l’icône", selection: pref({ $0.badge == .unknown ? .inbox : $0.badge }) { $0.badge = $1 }) {61                        Text("Non lus des boîtes de réception").tag(PushBadge.inbox)62                        Text("Aucune").tag(PushBadge.none)63                    }64                } header: { Text("Compte") } footer: {65                    Text("L’aperçu s’applique à tous vos appareils, aux widgets et à Spotlight. Quand SP Mail est verrouillé, les notifications et les widgets ne montrent jamais l’expéditeur ni l’objet.")66                }67                .disabled(!loaded)6869                Section {70                    Toggle("Heures calmes", isOn: Binding(get: { prefs.quietHours != nil }, set: { on in71                        var p = prefs; p.quietHours = on ? QuietHours(start: "22:00", end: "07:00", timeZone: TimeZone.current.identifier) : nil72                        Task { await push.save(p) }73                    }))74                    if let q = prefs.quietHours {75                        DatePicker("Commencent à", selection: time(q.start) { v in var p = prefs; p.quietHours?.start = v; return p }, displayedComponents: .hourAndMinute)76                        DatePicker("Se terminent à", selection: time(q.end) { v in var p = prefs; p.quietHours?.end = v; return p }, displayedComponents: .hourAndMinute)77                        Picker("Fuseau horaire", selection: Binding(get: { q.timeZone }, set: { tz in var p = prefs; p.quietHours?.timeZone = tz; Task { await push.save(p) } })) {78                            ForEach(timeZones(including: q.timeZone), id: \.self) { Text(Self.zoneLabel($0)).tag($0) }79                        }80                        if q.contains(Date()) { Label("Heures calmes en cours", systemImage: "moon.fill").font(.footnote).foregroundStyle(.secondary) }81                    }82                    Toggle("Expéditeurs prioritaires seulement", isOn: pref(\.priorityOnly) { $0.priorityOnly = $1 })83                } header: { Text("Heures calmes et priorités") } footer: {84                    Text("Pendant les heures calmes, un nouveau message met seulement la pastille à jour. Les expéditeurs prioritaires passent toujours.")85                }86                .disabled(!loaded)8788                Section {89                    ForEach(prefs.prioritySenders, id: \.self) { sender in90                        HStack {91                            Image(systemName: sender.hasPrefix("@") ? "building.2" : "star.fill").foregroundStyle(.secondary).accessibilityHidden(true)92                            Text(sender)93                            Spacer()94                            Button(role: .destructive) { var p = prefs; p.prioritySenders.removeAll { $0 == sender }; Task { await push.save(p) } } label: { Image(systemName: "minus.circle") }95                                .buttonStyle(.borderless).accessibilityLabel(Text("Retirer \(sender)"))96                        }97                    }98                    HStack {99                        TextField("adresse@exemple.com ou @domaine.com", text: $newSender).autocorrectionDisabled().onSubmit(addSender)100                            #if os(iOS)101                            .textInputAutocapitalization(.never).keyboardType(.emailAddress)102                            #endif103                        Button("Ajouter", action: addSender).disabled(newSender.trimmingCharacters(in: .whitespaces).isEmpty)104                    }105                    if let senderError { Text(senderError).font(.footnote).foregroundStyle(SPColor.danger) }106                } header: { Text("Expéditeurs prioritaires") } footer: {107                    Text("Leurs messages sont signalés même pendant les heures calmes. Les contacts marqués VIP sont prioritaires d’office.")108                }109                .disabled(!loaded)110111                if model.accounts.count > 0 {112                    Section("Boîtes") {113                        ForEach(model.accounts) { box in114                            Toggle(box.address, isOn: Binding(get: { !prefs.isMuted(mailbox: box.id) }, set: { on in115                                var p = prefs; if on { p.mailboxes[box.id] = nil } else { p.mailboxes[box.id] = false }116                                Task { await push.save(p) }117                            }))118                        }119                    }120                    .disabled(!loaded)121                }122123                Section {124                    ForEach(push.devices) { d in125                        HStack(alignment: .top) {126                            Image(systemName: d.bundleId.contains(".ios") ? "iphone" : "laptopcomputer").foregroundStyle(.secondary).accessibilityHidden(true)127                            VStack(alignment: .leading, spacing: 2) {128                                Text(d.deviceName.isEmpty ? L("Appareil") : d.deviceName) + Text(d.current ? L(" — cet appareil") : "").foregroundStyle(.secondary)129                                Text(Self.deviceDetail(d)).font(.footnote).foregroundStyle(.secondary)130                                if let e = d.lastError, !e.isEmpty { Text(e).font(.footnote).foregroundStyle(SPColor.danger) }131                            }132                            Spacer()133                            Button("Retirer", role: .destructive) { removing = d }.buttonStyle(.borderless)134                        }135                    }136                    if push.devices.isEmpty { Text("Aucun appareil enregistré pour les notifications.").foregroundStyle(.secondary) }137                    Button { Task { await test() } } label: { Label("Envoyer une notification d’essai", systemImage: "paperplane") }.disabled(busy || push.devices.isEmpty)138                    if let testResult { Text(testResult).font(.footnote).foregroundStyle(.secondary) }139                } header: { Text("Appareils") }140141                Section {142                    if let status = push.serverStatus {143                        LabeledContent("Service de notifications") { Text(status.configured ? L("Actif") : L("Non configuré sur le serveur")).foregroundStyle(status.configured ? AnyShapeStyle(.secondary) : AnyShapeStyle(SPColor.danger)) }144                        if status.configured {145                            LabeledContent("Dernières 24 heures", value: L("\(status.sent24h) envoyées, \(status.failed24h) en échec, \(status.pending) en attente"))146                        }147                        if let e = status.lastError, !e.isEmpty { Text(e).font(.footnote).foregroundStyle(.secondary) }148                        if !status.configured {149                            Text("Tant que le serveur n’envoie pas de notifications, SP Mail signale les nouveaux messages quand il est ouvert ou lors d’une actualisation en arrière-plan, si le système en accorde une.").font(.footnote).foregroundStyle(.secondary)150                        }151                    } else {152                        Text(push.lastError ?? L("État du serveur indisponible.")).foregroundStyle(.secondary)153                    }154                    if let e = push.lastError, push.serverStatus != nil { Text(e).font(.footnote).foregroundStyle(SPColor.danger) }155                } header: { Text("Serveur") }156            }157        }158        .formStyle(.grouped)159        .task { await push.refreshAuthorization(); await push.refreshServerState() }160        .confirmationDialog("Retirer cet appareil ?", isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }), presenting: removing) { d in161            Button("Retirer", role: .destructive) { Task { await push.remove(d) } }162        } message: { _ in Text("Il ne recevra plus de notifications tant qu’il ne se sera pas reconnecté.") }163    }164165    // MARK: this device166167    private var deviceStatusIsProblem: Bool {168        switch push.registration { case .denied, .failed: true; default: false }169    }170    private var deviceStatus: String {171        if !model.settings.notificationsEnabled { return L("Désactivées dans SP Mail") }172        switch push.registration {173        case .idle: return push.authorization == .notDetermined ? L("Autorisation non demandée") : L("Non enregistré")174        case .denied: return L("Refusées dans les réglages du système")175        case .unavailable(let reason): return reason176        case .registering: return L("Enregistrement…")177        case .registered: return push.pipelineActive ? L("Enregistré — notifications poussées actives") : L("Appareil enregistré")178        case .failed(let reason): return L("Enregistrement refusé : ") + reason179        }180    }181    private func openSystemSettings() {182        #if os(iOS)183        if let url = URL(string: UIApplication.openNotificationSettingsURLString) { UIApplication.shared.open(url) }184        #else185        if let url = URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension?id=\(AppConfig.bundleId)") { NSWorkspace.shared.open(url) }186        #endif187    }188189    // MARK: helpers190191    private static func deviceDetail(_ d: PushDevice) -> String {192        var parts: [String] = []193        if let v = d.appVersion, !v.isEmpty { parts.append("SP Mail \(v)") }194        if d.environment == .sandbox { parts.append(L("développement")) }195        if !d.enabled { parts.append(L("désactivé")) }196        if let last = d.lastPushAt { parts.append(L("dernière notification ") + last.formatted(date: .abbreviated, time: .shortened)) }197        else if let reg = d.lastRegisteredAt { parts.append(L("enregistré ") + reg.formatted(date: .abbreviated, time: .omitted)) }198        return parts.joined(separator: " · ")199    }200201    /// `HH:mm` ↔ a date today, for the time pickers. The time is a wall-clock time in the chosen zone; the picker only edits its digits.202    private func time(_ value: String, _ apply: @escaping (String) -> PushPrefs) -> Binding<Date> {203        Binding(get: {204            let p = value.split(separator: ":").compactMap { Int($0) }205            return Calendar.current.date(bySettingHour: p.first ?? 0, minute: p.count > 1 ? p[1] : 0, second: 0, of: Date()) ?? Date()206        }, set: { date in207            let c = Calendar.current.dateComponents([.hour, .minute], from: date)208            let text = String(format: "%02d:%02d", c.hour ?? 0, c.minute ?? 0)209            Task { await push.save(apply(text)) }210        })211    }212    private func timeZones(including current: String) -> [String] {213        let common = ["America/Toronto", "America/Vancouver", "America/Edmonton", "America/Winnipeg", "America/Halifax", "America/St_Johns", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles",214                      "Europe/Paris", "Europe/London", "Europe/Berlin", "Asia/Tokyo", "Australia/Sydney", "UTC"]215        var list = [TimeZone.current.identifier]216        for z in [current] + common where !list.contains(z) { list.append(z) }217        return list218    }219    private static func zoneLabel(_ id: String) -> String {220        guard let tz = TimeZone(identifier: id) else { return id }221        let offset = tz.secondsFromGMT() / 60222        return "\(id.replacingOccurrences(of: "_", with: " ")) (UTC\(offset >= 0 ? "+" : "−")\(abs(offset) / 60)\(offset % 60 == 0 ? "" : String(format: ":%02d", abs(offset) % 60)))"223    }224    private func addSender() {225        let value = newSender.trimmingCharacters(in: .whitespaces).lowercased()226        guard value.range(of: "^(@[a-z0-9.-]+\\.[a-z0-9-]+|[^@\\s]+@[a-z0-9.-]+\\.[a-z0-9-]+)$", options: .regularExpression) != nil else { senderError = L("Entrez une adresse complète ou un domaine précédé de @."); return }227        senderError = nil; newSender = ""228        guard !prefs.prioritySenders.contains(value) else { return }229        var p = prefs; p.prioritySenders.append(value)230        Task { await push.save(p) }231    }232    private func test() async {233        busy = true; defer { busy = false }234        guard let n = await push.sendTest() else { testResult = push.lastError; return }235        testResult = n == 0 ? L("Rien n’a été envoyé : le serveur n’a pas de service de notifications actif, ou aucun appareil n’est activé.") : L("Notification d’essai mise en file pour \(n) appareil(s).")236    }237}238
Files main
Menu

Theme