SPB Git

Repository Public

AppModel.swift 12.1 KB 257 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/Core/AppModel.swift10// Description      : État de l'application : session, passerelle (téléphones,11//                    SIM, réglages), flux temps réel, verrou local.12// Module           : ios13// Repository       : https://git.spboucher.ai/maclustr-sms14// Project Website  : https://sms.spboucher.ai15// Created          : 2026-11-3016// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: admin@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import LocalAuthentication92import Observation93import UIKit9495struct ComposeDraft: Equatable { var to: String = ""; var text: String = ""; var simId: String? = nil }9697@MainActor @Observable98final class AppModel {99    enum Phase { case launching, signedOut, signedIn }100    var phase: Phase = .launching101    var api: API102    var me: Me?103    var overview: Overview?104    var devices: [Device] = []105    var sims: [Sim] = []106    var defaultSimId: String?107    var allowed: [AllowedRecipient] = []108    var gatewayError: String?109    /// Incrémentés à chaque signal du serveur : les vues qui en dépendent se rechargent.110    var messagesRevision = 0111    var liveConnected = false112    var selectedTab = 0113    var pendingDraft: ComposeDraft?114    var locked = false115    var busy = false116    var authError: String?117118    var lockEnabled: Bool { didSet { UserDefaults.standard.set(lockEnabled, forKey: "lockEnabled") } }119    var signature: String { didSet { UserDefaults.standard.set(signature, forKey: "signature") } }120    var signatureEnabled: Bool { didSet { UserDefaults.standard.set(signatureEnabled, forKey: "signatureEnabled") } }121122    private let passkeys = PasskeyCoordinator()123    private var eventsTask: Task<Void, Never>?124    private var backgroundedAt: Date?125126    init() {127        let d = UserDefaults.standard128        lockEnabled = d.bool(forKey: "lockEnabled")129        signature = d.string(forKey: "signature") ?? ""130        signatureEnabled = d.bool(forKey: "signatureEnabled")131        api = API()132        #if DEBUG133        // Mise au point seulement : pile locale et session injectée par arguments de lancement (-serverURL, -sessionToken).134        // Ce bloc n'existe pas dans le build de distribution.135        if let s = d.string(forKey: "serverURL"), let url = URL(string: s) {136            api = API(base: url)137            if let token = d.string(forKey: "sessionToken"), let host = url.host,138               let cookie = HTTPCookie(properties: [.name: API.cookieName, .value: token, .domain: host, .path: "/", .expires: Date.now.addingTimeInterval(86400)]) {139                HTTPCookieStorage.shared.setCookie(cookie)140            }141        }142        #endif143    }144145    var usableSims: [Sim] { sims.filter(\.usable) }146    var primaryDevice: Device? { devices.first(where: { !$0.revoked }) }147    var killSwitch: Bool { overview?.killSwitch ?? false }148    var allowlistMode: Bool { (overview?.sendMode ?? "allowlist") != "open" }149    /// Raison pour laquelle un envoi n'aboutirait pas tout de suite (nil = tout est prêt).150    var sendBlocker: String? {151        if killSwitch { return "Arrêt d'urgence actif : aucun SMS n'est accepté." }152        guard let d = primaryDevice else { return devices.isEmpty && overview != nil ? "Aucun téléphone passerelle n'est associé." : nil }153        if usableSims.isEmpty && !sims.isEmpty { return "Aucune SIM n'est autorisée à envoyer." }154        if !d.online { return "Téléphone passerelle hors ligne : le message attendra en file." }155        if d.smsPermissionsMissing == true { return "Le téléphone n'a pas l'autorisation SMS : le message attendra en file." }156        if !d.available { return "\(d.stateLabel) : le message attendra en file." }157        return nil158    }159160    // MARK: Session161    func bootstrap() async {162        do { me = try await api.me(); await enter() } catch let e as APIError where e.isUnauthenticated { phase = .signedOut } catch {163            // Hors ligne au lancement : on ne déconnecte pas, l'écran de connexion propose de réessayer.164            authError = (error as? APIError)?.message; phase = .signedOut165        }166    }167    private func enter() async {168        phase = .signedIn; authError = nil169        await refreshGateway()170        startEvents()171    }172    func login() async {173        busy = true; authError = nil; defer { busy = false }174        do {175            let o = try await api.object("POST", "/api/auth/login/options", json: [:])176            guard let options = o["options"] as? [String: Any], let challengeId = o["challenge_id"] as? String else { throw PasskeyError.malformedOptions }177            let response = try await passkeys.assertion(options: options)178            _ = try await api.raw("POST", "/api/auth/login/verify", json: ["challenge_id": challengeId, "response": response])179            me = try await api.me(); await enter()180        } catch PasskeyError.cancelled {} catch { authError = error.localizedDescription }181    }182    func enroll(link: String) async {183        guard let token = EnrollmentLink.token(from: link) else { authError = "Ce lien d'enrôlement n'est pas reconnu. Collez le lien complet (https://sms.spboucher.ai/enroll#…)."; return }184        busy = true; authError = nil; defer { busy = false }185        do {186            let o = try await api.object("POST", "/api/auth/enroll/options", json: ["token": token])187            guard let options = o["options"] as? [String: Any], let challengeId = o["challenge_id"] as? String else { throw PasskeyError.malformedOptions }188            let response = try await passkeys.registration(options: options)189            _ = try await api.raw("POST", "/api/auth/enroll/verify", json: ["token": token, "challenge_id": challengeId, "response": response, "label": UIDevice.current.name.prefix(60).description])190            me = try await api.me(); await enter()191        } catch PasskeyError.cancelled {} catch { authError = error.localizedDescription }192    }193    func logout() async {194        try? await api.logout()195        signOutLocally()196    }197    func signOutLocally() {198        eventsTask?.cancel(); eventsTask = nil; liveConnected = false199        for c in HTTPCookieStorage.shared.cookies ?? [] where c.name == API.cookieName { HTTPCookieStorage.shared.deleteCookie(c) }200        me = nil; overview = nil; devices = []; sims = []; allowed = []; phase = .signedOut201    }202    /// À appeler sur toute erreur d'API : une session expirée ramène à l'écran de connexion.203    @discardableResult func handle(_ error: Error) -> String {204        if let e = error as? APIError, e.isUnauthenticated { signOutLocally(); authError = "Session expirée : reconnectez-vous."; return "Session expirée." }205        return error.localizedDescription206    }207208    // MARK: Passerelle209    func refreshGateway() async {210        do {211            async let o = api.overview(), d = api.devices(), s = api.sims(), a = api.allowedRecipients()212            let (ov, dv, sl, al) = try await (o, d, s, a)213            overview = ov; devices = dv; sims = sl.data; defaultSimId = sl.defaultSimId; allowed = al; gatewayError = nil214        } catch { gatewayError = handle(error) }215    }216    private func startEvents() {217        eventsTask?.cancel()218        eventsTask = Task { [weak self] in219            var delay: UInt64 = 1220            while !Task.isCancelled {221                guard let self else { return }222                do {223                    for try await topics in self.api.events() {224                        // Premier élément vide = connexion établie : on rattrape ce qui a pu changer pendant la coupure.225                        if !self.liveConnected { self.liveConnected = true; self.messagesRevision += 1 }226                        delay = 1227                        if topics.isEmpty { continue }228                        if topics.contains("messages") || topics.contains("queue") { self.messagesRevision += 1 }229                        if !topics.isDisjoint(with: ["devices", "settings", "queue", "messages"]) { await self.refreshGateway() }230                    }231                } catch let e as APIError where e.status == 401 { self.signOutLocally(); return } catch {}232                self.liveConnected = false233                try? await Task.sleep(nanoseconds: delay * 1_000_000_000)234                delay = min(delay * 2, 30)235                if self.phase != .signedIn { return }236            }237        }238    }239240    /// Retour au premier plan : tout est rechargé et le flux temps réel est relancé (iOS le suspend en arrière-plan).241    func becameActive() async {242        guard phase == .signedIn else { return }243        messagesRevision += 1244        startEvents()245        await refreshGateway()246    }247248    // MARK: Verrou local249    func didEnterBackground() { backgroundedAt = .now; if lockEnabled && phase == .signedIn { locked = true } }250    func unlock() async {251        let ctx = LAContext()252        var err: NSError?253        guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: &err) else { locked = false; return }254        if (try? await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Déverrouiller MacLustr SMS")) == true { locked = false }255    }256}257
Files main
Menu

Theme