SPB Git

Repository Public

GatewayView.swift 16.4 KB 258 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/UI/GatewayView.swift10// Description      : État de la passerelle (téléphone, SIM, file, mode11//                    d'envoi), arrêt d'urgence, destinataires autorisés ;12//                    réglages de l'app.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct GatewayView: View {94    @Environment(AppModel.self) private var model95    @State private var confirmKill = false96    @State private var newNumber = ""97    @State private var newLabel = ""98    @State private var error: String?99100    var body: some View {101        NavigationStack {102            Screen {103                if let e = model.gatewayError ?? error { Banner(text: e, tone: .bad) }104                if model.killSwitch { Banner(text: "Arrêt d'urgence actif : aucun SMS n'est accepté ni transmis. La réception continue.", tone: .bad, symbol: "exclamationmark.octagon").accessibilityIdentifier("killBanner") }105                SectionLabel("Téléphone")106                if model.devices.filter({ !$0.revoked }).isEmpty { Card { Text(model.overview == nil ? "Chargement…" : "Aucun téléphone associé.").foregroundStyle(Theme.muted) } }107                ForEach(model.devices.filter { !$0.revoked }) { d in deviceCard(d) }108                SectionLabel("Lignes")109                ForEach(model.sims.filter(\.active)) { s in simCard(s) }110                if let o = model.overview {111                    SectionLabel("Activité")112                    Card {113                        HStack(spacing: 0) {114                            stat("\(o.messages.sentToday)", "envoyés aujourd'hui"); stat("\(o.queue.pending + o.queue.inFlight)", "en file"); stat("\(o.messages.failed24H)", "échecs 24 h")115                        }116                    }117                    Card {118                        HStack(alignment: .top, spacing: 10) {119                            Image(systemName: model.allowlistMode ? "checklist" : "globe").foregroundStyle(model.allowlistMode ? Theme.warn : Theme.ok)120                            VStack(alignment: .leading, spacing: 2) {121                                Text(model.allowlistMode ? "Mode liste autorisée" : "Mode ouvert").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.text)122                                Text(model.allowlistMode ? "Seuls les numéros ci-dessous peuvent recevoir un SMS." : "Tout numéro valide est accepté, sauf les désinscrits. Le mode se change dans le tableau de bord web.").font(.footnote).foregroundStyle(Theme.muted)123                            }124                        }125                    }126                }127                SectionLabel("Destinataires autorisés (\(model.allowed.count))")128                Card {129                    VStack(alignment: .leading, spacing: 10) {130                        ForEach(model.allowed) { a in131                            HStack {132                                VStack(alignment: .leading) { Text(PhoneNumber.pretty(a.number)).font(.subheadline.monospacedDigit()).foregroundStyle(Theme.text); if let l = a.label, !l.isEmpty { Text(l).font(.caption).foregroundStyle(Theme.muted) } }133                                Spacer()134                                Button { Task { await act { try await model.api.disallow(a.number) } } } label: { Image(systemName: "minus.circle").foregroundStyle(Theme.bad) }.accessibilityLabel("Retirer \(a.number)")135                            }136                        }137                        HStack {138                            TextField("418 555-0123", text: $newNumber).keyboardType(.phonePad).font(.subheadline.monospacedDigit()).accessibilityIdentifier("allowNumberField")139                            TextField("Libellé", text: $newLabel).font(.subheadline)140                            Button("Ajouter") { let n = PhoneNumber.e164(newNumber)!; Task { await act { try await model.api.allow(n, label: newLabel) }; newNumber = ""; newLabel = "" } }.disabled(PhoneNumber.e164(newNumber) == nil)141                        }142                    }143                }144                SectionLabel("Arrêt d'urgence")145                Card {146                    VStack(alignment: .leading, spacing: 10) {147                        Text(model.killSwitch ? "Les envois sont coupés. Les messages encore valides repartiront à la levée." : "Coupe immédiatement tous les envois : l'API refuse les demandes, la file est figée, le téléphone cesse toute remise au modem.").font(.footnote).foregroundStyle(Theme.muted)148                        Button(model.killSwitch ? "Lever l'arrêt d'urgence" : "Déclencher l'arrêt d'urgence") { confirmKill = true }149                            .buttonStyle(QuietButtonStyle(tone: model.killSwitch ? Theme.accent : Theme.bad)).accessibilityIdentifier("killSwitchButton")150                    }151                }152                HStack(spacing: 6) { StatusDot(tone: model.liveConnected ? .ok : .warn); Text(model.liveConnected ? "Mise à jour en direct" : "Reconnexion au flux en direct…").font(.caption).foregroundStyle(Theme.faint) }.frame(maxWidth: .infinity)153            }154            .navigationTitle("Passerelle")155            .refreshable { await model.refreshGateway() }156            .confirmationDialog(model.killSwitch ? "Reprendre les envois ?" : "Couper tous les envois ?", isPresented: $confirmKill, titleVisibility: .visible) {157                Button(model.killSwitch ? "Lever l'arrêt" : "Tout arrêter", role: model.killSwitch ? nil : .destructive) { let on = !model.killSwitch; Task { await act { try await model.api.setKillSwitch(on) } } }158                    .accessibilityIdentifier("killConfirm")159                Button("Annuler", role: .cancel) {}160            } message: { Text(model.killSwitch ? "Les messages encore valides dans la file seront transmis au téléphone." : "Plus aucun SMS ne partira tant que l'arrêt ne sera pas levé, y compris ceux de vos applications.") }161        }162    }163164    private func deviceCard(_ d: Device) -> some View {165        Card {166            VStack(alignment: .leading, spacing: 10) {167                HStack { VStack(alignment: .leading, spacing: 1) { Text(d.name).font(.headline).foregroundStyle(Theme.text); Text("\(d.id) · Android \(d.androidVersion ?? "?") · app \(d.appVersion ?? "?")").font(.caption.monospaced()).foregroundStyle(Theme.faint) }; Spacer() }168                HStack(spacing: 6) { StatusDot(tone: d.tone); Text(d.stateLabel).font(.subheadline.weight(.medium)).foregroundStyle(Theme.tone(d.tone)).accessibilityIdentifier("deviceState") }169                HStack(spacing: 16) {170                    Label(d.batteryPct.map { "\($0) %" } ?? "—", systemImage: d.charging == true ? "battery.100.bolt" : "battery.75")171                    Label(network(d.network), systemImage: d.network == "wifi" ? "wifi" : "antenna.radiowaves.left.and.right")172                    Label(d.lastSeenAt?.ago ?? "jamais", systemImage: "clock")173                }.font(.caption).foregroundStyle(Theme.muted).labelStyle(.titleAndIcon)174                if d.smsPermissionsMissing == true {175                    Banner(text: "Android bloque l'autorisation SMS d'une application installée hors Play Store. Sur le téléphone : Paramètres → Applications → MacLustr SMS → ⋮ → Autoriser les paramètres restreints, puis Autorisations → SMS → Autoriser.", tone: .warn)176                }177            }178        }179    }180    private func network(_ n: String?) -> String { switch n { case "wifi": "Wi-Fi"; case "cellular": "Cellulaire"; case "none": "Hors réseau"; case .none: "—"; default: n! } }181    private func simCard(_ s: Sim) -> some View {182        Card {183            HStack(alignment: .center, spacing: 12) {184                SignalBars(level: s.signalLevel)185                VStack(alignment: .leading, spacing: 2) {186                    Text(s.number.map(PhoneNumber.pretty) ?? s.id).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Theme.text).lineLimit(1).minimumScaleFactor(0.8)187                    if !s.carrierName.isEmpty { Text(s.carrierName).font(.caption).foregroundStyle(Theme.muted) }188                    Text("\(s.id) · \(s.type == "esim" ? "eSIM" : s.type == "physical" ? "SIM physique" : "SIM")\(model.defaultSimId == s.id ? " · par défaut" : "")").font(.caption).foregroundStyle(Theme.muted)189                    if let t = s.sentToday, let l = s.dailyLimit { Text("\(t) / \(l) aujourd'hui").font(.caption.monospacedDigit()).foregroundStyle(Theme.faint) }190                }191                Spacer()192                Text(s.sendEnabled ? "Envoi autorisé" : "Envoi interdit").font(.caption.weight(.medium)).foregroundStyle(s.sendEnabled ? Theme.ok : Theme.muted)193            }194        }195    }196    private func stat(_ v: String, _ k: String) -> some View {197        VStack(spacing: 2) { Text(v).font(.title2.weight(.semibold).monospacedDigit()).foregroundStyle(Theme.text); Text(k).font(.caption2).foregroundStyle(Theme.muted) }.frame(maxWidth: .infinity)198    }199    private func act(_ f: () async throws -> Void) async { do { try await f(); await model.refreshGateway(); error = nil } catch { self.error = model.handle(error) } }200}201202struct SignalBars: View {203    let level: Int?204    var body: some View {205        HStack(alignment: .bottom, spacing: 2) {206            ForEach(0..<4, id: \.self) { i in RoundedRectangle(cornerRadius: 1).fill(i < (level ?? 0) ? Theme.accent : Theme.line).frame(width: 4, height: CGFloat(6 + i * 4)) }207        }208        .accessibilityLabel(level.map { "Signal \($0) sur 4" } ?? "Signal inconnu")209    }210}211212struct SettingsView: View {213    @Environment(AppModel.self) private var model214    @State private var showTemplates = false215    @State private var confirmLogout = false216    var body: some View {217        @Bindable var model = model218        NavigationStack {219            Form {220                Section("Compte") {221                    LabeledContent("Administrateur", value: model.me?.user.displayName ?? "—")222                    LabeledContent("Serveur", value: model.api.base.host ?? "—")223                    Toggle("Verrouiller avec Face ID", isOn: $model.lockEnabled)224                    LabeledContent("Temps réel") { HStack(spacing: 6) { StatusDot(tone: model.liveConnected ? .ok : .warn); Text(model.liveConnected ? "connecté" : "reconnexion…") } }225                        .accessibilityIdentifier("liveStatus")226                }227                Section { Toggle("Ajouter une signature", isOn: $model.signatureEnabled); TextField("— Simon-Pierre", text: $model.signature).disabled(!model.signatureEnabled) } header: { Text("Signature") } footer: { Text("Ajoutée à la fin de chaque message ; elle compte dans les segments.") }228                Section { RememberedField(name: "marque", prompt: "Lou-Ka, Immo-Ka…"); RememberedField(name: "signature", prompt: "Simon-Pierre") } header: { Text("Valeurs mémorisées") } footer: { Text("Remplissent d'office les variables {{marque}} et {{signature}} de tous les modèles.") }229                Section("Modèles") { Button("Ouvrir la galerie de modèles") { showTemplates = true } }230                Section { Text("Un SMS est du texte brut. Il ne peut contenir ni logo, ni image, ni gras, ni couleur : cela demanderait du MMS, que la passerelle ne prend pas en charge. Le soin apporté ici porte sur la rédaction, les modèles, l'aperçu et le suivi.").font(.footnote).foregroundStyle(Theme.muted)231                    Text("« Remis au réseau » signifie que le modem du téléphone a accepté le SMS. « Livré » n'apparaît que si l'opérateur renvoie un rapport de livraison.").font(.footnote).foregroundStyle(Theme.muted)232                    Text("Aucune télémétrie. Les modèles et les destinataires récents restent sur cet iPhone.").font(.footnote).foregroundStyle(Theme.muted)233                } header: { Text("À savoir") }234                Section { Button("Se déconnecter", role: .destructive) { confirmLogout = true } } footer: {235                    Text("MacLustr SMS \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "") (\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "")) · passerelle \(model.overview?.version ?? "—")").frame(maxWidth: .infinity)236                }237            }238            .scrollContentBackground(.hidden).background(Theme.bg)239            .navigationTitle("Réglages")240            .sheet(isPresented: $showTemplates) { TemplateLibrary() }241            .confirmationDialog("Se déconnecter de cet iPhone ?", isPresented: $confirmLogout, titleVisibility: .visible) { Button("Se déconnecter", role: .destructive) { Task { await model.logout() } } }242        }243    }244}245246/// Champ d'une valeur mémorisée (Réglages) : enregistrée à chaque modification, gardée sur l'appareil.247struct RememberedField: View {248    let name: String; let prompt: String249    @State private var value = ""250    var body: some View {251        LabeledContent(name.capitalized) {252            TextField(prompt, text: $value).multilineTextAlignment(.trailing).autocorrectionDisabled().accessibilityIdentifier("remembered-\(name)")253                .onChange(of: value) { _, v in RememberedValues.set(v, for: name) }254        }255        .onAppear { value = RememberedValues.value(for: name) ?? "" }256    }257}258
Files main
Menu

Theme