SPB Git

Repository Public

API.swift 17.2 KB 348 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : Groupe Ka — app iOS native7// File             : Shared/API.swift8// Module           : Utilities9// Repository       : https://git.spboucher.ai/groupe-ka-ios10// Project Website  : Not specified11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CryptoKit42import Foundation4344/// D'où vient une réponse affichée.45enum Provenance: Sendable, Equatable {46    /// lue à l'instant sur le réseau47    case reseau48    /// le serveur a confirmé que la copie gardée est toujours la bonne (304)49    case confirmee50    /// le réseau n'a pas répondu : c'est la dernière réponse gardée sur l'appareil51    case horsLigne52}5354struct Reponse<T: Sendable>: Sendable {55    let valeur: T56    let meta: Meta?57    /// instant où cette réponse a été reçue du serveur58    let recueA: Date59    let provenance: Provenance6061    /// la dernière lecture du serveur dans l'instance du site a échoué : dernière valeur connue62    var perime: Bool { meta?.perime == true }63}6465enum APIErreur: Error, Sendable, LocalizedError {66    case http(Int, Probleme?)67    case reseau(String)68    case decodage(String)6970    var errorDescription: String? {71        switch self {72        case .http(let code, let p):73            if let d = p?.detail ?? p?.title { return "\(code) — \(d)" }74            return "Le serveur a répondu \(code)."75        case .reseau(let m): return m76        case .decodage: return "La réponse du serveur n'a pas la forme attendue."77        }78    }7980    var estReseau: Bool { if case .reseau = self { true } else { false } }81}8283/// Réponse brute d'un appel, pour la console de requêtes.84struct ReponseBrute: Sendable {85    let url: URL86    let statut: Int87    let dureeMs: Int88    let entetes: [(nom: String, valeur: String)]89    let corps: Data9091    func entete(_ nom: String) -> String? {92        entetes.first { $0.nom.caseInsensitiveCompare(nom) == .orderedSame }?.valeur93    }94}9596/// Petit client typé de l'API du Groupe Ka : async/await, ETag (`If-None-Match`), dernière réponse gardée sur disque.97///98/// Adresse : `https://www.groupe-ka.com` quand il sert `/api/v1` ; sinon, automatiquement, l'adresse de préproduction99/// (les apps sœurs font de même : sonder, puis l'alias).100actor API {101    static let partagee = API()102103    static let production = URL(string: "https://www.groupe-ka.com")!104    static let alias = URL(string: "https://groupeka-ovh.51-161-112-61.sslip.io")!105106    private let session: URLSession107    private let dossier: URL108    private var baseConnue: (url: URL, a: Date)?109    private var sonde: Task<URL, Never>?110    private let baseImposee: URL?111    private let dossierEchantillons: URL?112113    init(base: URL? = nil, echantillons: URL? = nil, session: URLSession? = nil, cache: URL? = nil) {114        var imposee = base115        var dossierEch = echantillons116        #if DEBUG117        // Réglages de développement et de test, absents d'un binaire Release.118        let env = ProcessInfo.processInfo.environment119        if imposee == nil, let t = UserDefaults.standard.string(forKey: "GKBaseURL") ?? env["GK_BASE_URL"], let u = URL(string: t) { imposee = u }120        if dossierEch == nil, let d = env["GK_FIXTURES_DIR"], !d.isEmpty { dossierEch = URL(fileURLWithPath: d, isDirectory: true) }121        #endif122        baseImposee = imposee123        dossierEchantillons = dossierEch124        if let session { self.session = session } else {125            let c = URLSessionConfiguration.ephemeral126            c.requestCachePolicy = .reloadIgnoringLocalCacheData127            c.timeoutIntervalForRequest = 20128            c.timeoutIntervalForResource = 40129            c.httpAdditionalHeaders = ["Accept": "application/json", "User-Agent": "GroupeKa-iOS/\(Self.versionApp)"]130            self.session = URLSession(configuration: c)131        }132        let racine = cache ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("api-v1", isDirectory: true)133        try? FileManager.default.createDirectory(at: racine, withIntermediateDirectories: true)134        dossier = racine135    }136137    static var versionApp: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0.0" }138139    /// vrai quand l'app lit des échantillons locaux (tests d'interface hors ligne)140    var modeEchantillons: Bool { dossierEchantillons != nil }141142    // ── Adresse de base ────────────────────────────────────────────────────143144    /// L'adresse qui sert l'API en ce moment. La décision est gardée 30 minutes.145    func base() async -> URL {146        if let baseImposee { return baseImposee }147        if let b = baseConnue, Date().timeIntervalSince(b.a) < 1800 { return b.url }148        if let sonde { return await sonde.value }149        let session = session150        let t = Task<URL, Never> {151            await Self.sertLAPI(Self.production, session: session) ? Self.production : Self.alias152        }153        sonde = t154        let url = await t.value155        sonde = nil156        baseConnue = (url, Date())157        return url158    }159160    /// `www` sert-il `/api/v1` ? (200, JSON, une version dans `donnees`)161    private static func sertLAPI(_ origine: URL, session: URLSession) async -> Bool {162        var r = URLRequest(url: origine.appendingPathComponent("api/v1"))163        r.timeoutInterval = 6164        guard let (d, rep) = try? await session.data(for: r), (rep as? HTTPURLResponse)?.statusCode == 200,165              let j = JSONValeur.lire(d), j["donnees"]?["version"]?.chaine != nil else { return false }166        return true167    }168169    // ── Lecture typée ──────────────────────────────────────────────────────170171    /// Lit une route de `/api/v1` (réponse `{ donnees, meta }`).172    func lire<T: Decodable & Sendable>(_ type: T.Type = T.self, _ chemin: String, _ params: [(String, String)] = []) async throws -> Reponse<T> {173        let (donnees, recueA, provenance) = try await charger(chemin, params)174        do {175            let e = try JSONDecoder().decode(Enveloppe<T>.self, from: donnees)176            return Reponse(valeur: e.donnees, meta: e.meta, recueA: recueA, provenance: provenance)177        } catch {178            throw APIErreur.decodage(String(describing: error))179        }180    }181182    /// Lit une réponse sans enveloppe (`/api/version`, `/api/v1/openapi.json`).183    func lireNu<T: Decodable & Sendable>(_ type: T.Type = T.self, _ chemin: String, _ params: [(String, String)] = []) async throws -> Reponse<T> {184        let (donnees, recueA, provenance) = try await charger(chemin, params)185        do {186            return Reponse(valeur: try JSONDecoder().decode(T.self, from: donnees), meta: nil, recueA: recueA, provenance: provenance)187        } catch {188            throw APIErreur.decodage(String(describing: error))189        }190    }191192    /// La dernière réponse gardée sur l'appareil, sans réseau (affichage immédiat avant la relecture).193    func enCache<T: Decodable & Sendable>(_ type: T.Type = T.self, _ chemin: String, _ params: [(String, String)] = []) -> Reponse<T>? {194        guard let g = garde(Self.cle(chemin, params)), let e = try? JSONDecoder().decode(Enveloppe<T>.self, from: g.corps) else { return nil }195        return Reponse(valeur: e.donnees, meta: e.meta, recueA: g.fiche.recueA, provenance: .horsLigne)196    }197198    static func requete(_ chemin: String, _ params: [(String, String)]) -> String {199        guard !params.isEmpty else { return chemin }200        var c = URLComponents()201        c.queryItems = params.map { URLQueryItem(name: $0.0, value: $0.1) }202        // « + » et « : » sont encodés : un identifiant d'annonce (« otogo:123 ») ou une recherche les contient souvent203        let q = (c.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B")204        return chemin + "?" + q205    }206207    private func charger(_ chemin: String, _ params: [(String, String)]) async throws -> (Data, Date, Provenance) {208        if let dossierEchantillons {209            guard let nom = Self.echantillon(chemin), let d = try? Data(contentsOf: dossierEchantillons.appendingPathComponent(nom)) else {210                throw APIErreur.http(404, nil)211            }212            let date = (try? FileManager.default.attributesOfItem(atPath: dossierEchantillons.appendingPathComponent(nom).path)[.modificationDate] as? Date) ?? Date()213            return (d, date, .reseau)214        }215        let cle = Self.cle(chemin, params)216        let gardee = garde(cle)217        let origine = await base()218        guard let url = URL(string: origine.absoluteString + Self.requete(chemin, params)) else { throw APIErreur.reseau("Adresse invalide.") }219        var r = URLRequest(url: url)220        if let etag = gardee?.fiche.etag { r.setValue(etag, forHTTPHeaderField: "If-None-Match") }221        do {222            let (d, rep) = try await session.data(for: r)223            let code = (rep as? HTTPURLResponse)?.statusCode ?? 0224            if code == 304, let gardee {225                garder(cle, corps: nil, fiche: Fiche(etag: gardee.fiche.etag, recueA: Date()))226                return (gardee.corps, Date(), .confirmee)227            }228            guard code == 200 else {229                // 5xx : le serveur est là mais ne peut pas répondre ; la dernière réponse gardée vaut mieux que rien230                if code >= 500, let gardee { return (gardee.corps, gardee.fiche.recueA, .horsLigne) }231                throw APIErreur.http(code, try? JSONDecoder().decode(Probleme.self, from: d))232            }233            let etag = (rep as? HTTPURLResponse)?.value(forHTTPHeaderField: "ETag")234            garder(cle, corps: d, fiche: Fiche(etag: etag, recueA: Date()))235            return (d, Date(), .reseau)236        } catch let e as APIErreur {237            throw e238        } catch {239            if let gardee { return (gardee.corps, gardee.fiche.recueA, .horsLigne) }240            throw APIErreur.reseau(Self.messageReseau(error))241        }242    }243244    static func messageReseau(_ e: Error) -> String {245        switch (e as? URLError)?.code {246        case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed: "L'appareil n'est pas connecté à Internet."247        case .timedOut: "Le serveur n'a pas répondu à temps."248        case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed: "Le serveur est injoignable."249        case .cancelled: "La lecture a été interrompue."250        default: "La lecture a échoué."251        }252    }253254    // ── Appel brut (console) ───────────────────────────────────────────────255256    /// Appelle une adresse relative telle quelle et rend tout ce que le serveur a répondu. Rien n'est gardé.257    func brut(_ cheminEtRequete: String) async throws -> ReponseBrute {258        if let dossierEchantillons {259            let chemin = cheminEtRequete.split(separator: "?").first.map(String.init) ?? cheminEtRequete260            guard let nom = Self.echantillon(chemin), let d = try? Data(contentsOf: dossierEchantillons.appendingPathComponent(nom)) else {261                throw APIErreur.http(404, nil)262            }263            return ReponseBrute(url: URL(string: "https://www.groupe-ka.com" + cheminEtRequete) ?? Self.production, statut: 200, dureeMs: 12,264                                entetes: [("content-type", "application/json; charset=utf-8"), ("ratelimit-limit", "120"), ("ratelimit-remaining", "119"), ("ratelimit-reset", "60")], corps: d)265        }266        let origine = await base()267        guard let url = URL(string: origine.absoluteString + cheminEtRequete) else { throw APIErreur.reseau("Adresse invalide.") }268        let debut = ContinuousClock.now269        do {270            let (d, rep) = try await session.data(for: URLRequest(url: url))271            let ecoule = ContinuousClock.now - debut272            let ms = Int(ecoule.components.seconds * 1000 + ecoule.components.attoseconds / 1_000_000_000_000_000)273            let http = rep as? HTTPURLResponse274            let entetes = (http?.allHeaderFields ?? [:]).compactMap { k, v -> (nom: String, valeur: String)? in275                guard let k = k as? String else { return nil }276                return (k.lowercased(), String(describing: v))277            }.sorted { $0.nom < $1.nom }278            return ReponseBrute(url: url, statut: http?.statusCode ?? 0, dureeMs: ms, entetes: entetes, corps: d)279        } catch {280            throw APIErreur.reseau(Self.messageReseau(error))281        }282    }283284    /// Lit une adresse absolue hors de l'API du groupe (le chiffre de Valo-Plex, tant que le site ne le relaie pas).285    func externe<T: Decodable & Sendable>(_ type: T.Type = T.self, _ url: URL) async throws -> T {286        if modeEchantillons { throw APIErreur.http(404, nil) }287        var r = URLRequest(url: url)288        r.timeoutInterval = 10289        do {290            let (d, rep) = try await session.data(for: r)291            guard (rep as? HTTPURLResponse)?.statusCode == 200 else { throw APIErreur.http((rep as? HTTPURLResponse)?.statusCode ?? 0, nil) }292            guard let v = try? JSONDecoder().decode(T.self, from: d) else { throw APIErreur.decodage("externe") }293            return v294        } catch let e as APIErreur { throw e } catch { throw APIErreur.reseau(Self.messageReseau(error)) }295    }296297    // ── Garde sur disque ───────────────────────────────────────────────────298299    private struct Fiche: Codable { var etag: String?; var recueA: Date }300301    private static func cle(_ chemin: String, _ params: [(String, String)]) -> String {302        SHA256.hash(data: Data(requete(chemin, params).utf8)).prefix(16).map { String(format: "%02x", $0) }.joined()303    }304305    private func garde(_ cle: String) -> (corps: Data, fiche: Fiche)? {306        guard let corps = try? Data(contentsOf: dossier.appendingPathComponent(cle + ".json")),307              let f = try? Data(contentsOf: dossier.appendingPathComponent(cle + ".fiche")),308              let fiche = try? JSONDecoder().decode(Fiche.self, from: f) else { return nil }309        return (corps, fiche)310    }311312    private func garder(_ cle: String, corps: Data?, fiche: Fiche) {313        if let corps { try? corps.write(to: dossier.appendingPathComponent(cle + ".json"), options: .atomic) }314        if let f = try? JSONEncoder().encode(fiche) { try? f.write(to: dossier.appendingPathComponent(cle + ".fiche"), options: .atomic) }315    }316317    /// Efface les réponses gardées (réglages).318    func vider() {319        try? FileManager.default.removeItem(at: dossier)320        try? FileManager.default.createDirectory(at: dossier, withIntermediateDirectories: true)321    }322323    // ── Échantillons (tests) ───────────────────────────────────────────────324325    /// Nom de l'échantillon (réponse réelle capturée) qui répond à un chemin.326    static func echantillon(_ chemin: String) -> String? {327        let c = chemin.hasSuffix("/") ? String(chemin.dropLast()) : chemin328        switch c {329        case "/api/v1": return "index.json"330        case "/api/version": return "version.json"331        case "/api/v1/observatoire": return "observatoire-30j.json"332        case "/api/v1/series": return "series.json"333        case "/api/v1/etat": return "etat.json"334        case "/api/v1/collectes": return "collectes.json"335        case "/api/v1/recherche": return "recherche-sherbrooke.json"336        case "/api/v1/openapi.json": return "openapi.json"337        case "/api/v1/sites": return "sites.json"338        case "/api/v1/marche": return "marche.json"339        case "/api/v1/usage": return "usage.json"340        default: break341        }342        let p = c.split(separator: "/").map(String.init)343        if p.count == 5, p[2] == "sites", p[4] == "tableau", let s = KaSite.trouver(p[3]), s.id.estMesure { return "tableau-\(s.id.rawValue)-30j.json" }344        if p.count == 4, p[2] == "series" { return "serie-louka-annonces.json" }345        return nil346    }347}348
Files main
Menu

Theme