SPB Git

Repository Public

APIClient.swift 16.6 KB 353 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Core/API/APIClient.swift10// Description      : client de l'API Immo-Ka — acteur, sonde du service (v2,11//                    repli v1), cache de réponses, repli hors ligne.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-3017//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: support@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 Foundation9192enum APIError: Error, LocalizedError, Sendable {93    case notFound94    case gone95    case http(Int)96    case offline97    case decoding(String)98    case invalidURL99    /// erreur structurée de l'API v3 : `{"error": {"code", "message", "param", "request_id"}}`100    case server(V3ErrorBody, status: Int)101    /// inscription retirée (410 de la v3) : le strict nécessaire que le service en dit encore102    case goneListing(GoneListing)103    /// limite de débit atteinte ; délai conseillé en secondes104    case rateLimited(retryAfter: Int?)105    /// inscription regroupée avec une autre (404 `duplicate` de la v3) : identifiant de l'inscription gardée106    case regrouped(String)107108    var errorDescription: String? {109        switch self {110        case .notFound: "Introuvable."111        case .gone: "Cette inscription a été retirée."112        case .http(let code): "Le serveur a répondu \(code)."113        case .offline: "Connexion impossible. Vérifiez votre accès à Internet."114        case .decoding: "Réponse illisible."115        case .invalidURL: "Adresse invalide."116        case .server(let e, _): e.message.isEmpty ? "Le service a refusé la demande." : e.message117        case .goneListing: "Cette inscription n'est plus affichée par sa source."118        case .regrouped: "Cette inscription est regroupée avec une autre."119        case .rateLimited(let s): s.map { "Trop de demandes. Réessayez dans \($0) s." } ?? "Trop de demandes. Réessayez dans un instant."120        }121    }122123    var isOffline: Bool { if case .offline = self { return true }; return false }124}125126/// Client HTTP de l'API. Une seule instance (`APIClient.shared`).127///128/// L'app parle à la v2 du service (`/api/version` → `{"api": 2}`) : recherche unifiée, points de carte compacts.129/// Tant que la v2 n'est en ligne nulle part, elle se replie sur les routes de lecture de la v1 (génération 1) :130/// la carte et les listes passent alors par `/api/listings` et `/api/listings.geojson` (voir `Endpoints.swift`).131///132/// Depuis la 3.0.0, l'app préfère la **v3** (`/api/v3/version` → `{"api": 3}`) : recherche à curseur, carte par133/// emprise, prix de vente attendu, comparables, coût de possession, marché (voir `V3Client.swift`). Les routes134/// `/api/*` de la v2 restent utilisées pour ce que la v3 ne sert pas (annuaires, quartier de la fiche, taux).135actor APIClient {136    static let shared = APIClient()137138    /// Adresse de production, puis repli de préproduction tant que la v2 n'y est pas en ligne.139    static let primary = URL(string: "https://www.immo-ka.com")!140    static let fallback = URL(string: "https://immoka-v2.51-161-112-61.sslip.io")!141    private static let baseKey = "api.base"142    private static let genKey = "api.gen"143144    struct Backend: Sendable, Equatable {145        var url: URL146        /// 3 : service v3 ; 2 : service v2 ; 1 : routes de lecture de la v1147        var generation: Int148    }149150    let session: URLSession151    private var backend: Backend152    private var resolved = false153    private var resolving: Task<Backend, Never>?154    /// dernière collection de points par requête (v1) : la pagination d'une zone ne refait pas l'appel155    var geoCache: (key: String, value: GeoCollection)?156    /// variantes d'écriture d'une ville (« Montréal », « Montreal », « City of Montréal ») : valeur du filtre `city`157    var cityVariants: [String: String] = [:]158159    init() {160        let cfg = URLSessionConfiguration.default161        cfg.timeoutIntervalForRequest = 25162        cfg.timeoutIntervalForResource = 90163        cfg.waitsForConnectivity = false164        cfg.requestCachePolicy = .useProtocolCachePolicy165        cfg.urlCache = URLCache(memoryCapacity: 16 << 20, diskCapacity: 96 << 20, directory: nil)166        cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]167        session = URLSession(configuration: cfg)168        let saved = UserDefaults.standard.string(forKey: APIClient.baseKey).flatMap(URL.init(string:))169        let gen = UserDefaults.standard.integer(forKey: APIClient.genKey)170        backend = Backend(url: APIClient.forcedBase ?? saved ?? APIClient.primary, generation: (1...3).contains(gen) ? gen : 1)171    }172173    /// Adresse imposée par argument de lancement ou variable d'environnement (tests et développement).174    private static var forcedBase: URL? {175        (UserDefaults.standard.string(forKey: "IKBaseURL") ?? ProcessInfo.processInfo.environment["IMMOKA_BASE_URL"]).flatMap(URL.init(string:))176    }177178    /// Adresses à sonder, dans l'ordre. `-IKBaseURL <url>` ou `IMMOKA_BASE_URL` impose une adresse (tests, développement).179    private static var candidates: [URL] {180        if let f = forcedBase { return [f] }181        return [primary, fallback]182    }183184    /// La v3 répond-elle à cette adresse ? (`/api/v3/version` → `{"api": 3}`)185    private static func probeV3(_ url: URL, session: URLSession) async -> Bool {186        var req = URLRequest(url: url.appending(path: "api/v3/version"))187        req.timeoutInterval = 6188        req.cachePolicy = .reloadIgnoringLocalCacheData189        // deux essais : une sonde ratée ferait retomber tout le lancement sur les routes de la v2190        for attempt in 0..<2 {191            if attempt > 0 { try? await Task.sleep(for: .milliseconds(350)) }192            guard let (data, resp) = try? await session.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200,193                  let v = try? JSONDecoder().decode(V3Version.self, from: data) else { continue }194            guard v.api >= 3 else { return false }195            V3Version.store(v)196            return true197        }198        return false199    }200201    private static func probe(_ url: URL, session: URLSession) async -> Bool {202        var req = URLRequest(url: url.appending(path: "api/version"))203        req.timeoutInterval = 6204        req.cachePolicy = .reloadIgnoringLocalCacheData205        guard let (data, resp) = try? await session.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200,206              let v = try? JSONDecoder().decode(APIVersion.self, from: data) else { return false }207        guard v.api >= 2 else { return false }208        // seuils du verdict : ceux du service, jamais recodés dans l'app209        if let t = v.thresholds { VerdictThresholds.store(t) }210        return true211    }212213    /// Service retenu ; sondé une fois par lancement (`/api/version` doit répondre api ≥ 2).214    func resolve() async -> Backend {215        if resolved { return backend }216        if let t = resolving { return await t.value }217        let session = self.session218        let current = backend219        let t = Task<Backend, Never> {220            for candidate in APIClient.candidates where await APIClient.probe(candidate, session: session) {221                // la v3 déjà vue à cette adresse est gardée si sa sonde échoue (panne passagère) : resondée au lancement suivant222                let v3 = await APIClient.probeV3(candidate, session: session) || (current.generation >= 3 && current.url == candidate)223                return Backend(url: candidate, generation: v3 ? 3 : 2)224            }225            // aucune v2 en ligne : adresse imposée telle quelle, sinon lecture de la v1 en production.226            // Hors ligne, on garde le dernier service connu (le cache de réponses porte la même forme).227            if let f = APIClient.forcedBase { return Backend(url: f, generation: 1) }228            var req = URLRequest(url: APIClient.primary.appending(path: "api/facets"))229            req.httpMethod = "HEAD"; req.timeoutInterval = 6230            if (try? await session.data(for: req)) == nil { return current }231            return Backend(url: APIClient.primary, generation: 1)232        }233        resolving = t234        let b = await t.value235        backend = b236        ServiceGeneration.set(b.generation)237        resolved = true238        resolving = nil239        if APIClient.forcedBase == nil { UserDefaults.standard.set(b.url.absoluteString, forKey: APIClient.baseKey) }240        UserDefaults.standard.set(b.generation, forKey: APIClient.genKey)241        return b242    }243244    func baseURL() async -> URL { await resolve().url }245    /// La recherche unifiée de la v2 est-elle disponible ?246    func isV2() async -> Bool { await resolve().generation >= 2 }247    /// L'API v3 (recherche à curseur, carte par emprise, prix de vente attendu) est-elle disponible ?248    func isV3() async -> Bool { await resolve().generation >= 3 }249250    /// URL absolue d'un chemin de l'API (liens PDF, images).251    func url(_ path: String, query: [String: String?] = [:]) async -> URL? {252        let b = await baseURL()253        guard var comps = URLComponents(url: b.appending(path: path), resolvingAgainstBaseURL: false) else { return nil }254        let items = query.compactMap { k, v -> URLQueryItem? in255            guard let v, !v.isEmpty else { return nil }256            return URLQueryItem(name: k, value: v)257        }.sorted { $0.name < $1.name }258        if !items.isEmpty { comps.queryItems = items }259        // « + » doit être encodé260        comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")261        return comps.url262    }263264    /// GET JSON. En cas de panne réseau, sert la dernière réponse en cache si elle existe.265    func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {266        guard let u = await url(path, query: query) else { throw APIError.invalidURL }267        var req = URLRequest(url: u)268        req.httpMethod = "GET"269        let data: Data270        do {271            let (d, resp) = try await session.data(for: req)272            let code = (resp as? HTTPURLResponse)?.statusCode ?? 0273            switch code {274            case 200..<300: data = d275            case 404: throw APIError.notFound276            case 410: throw APIError.gone277            default: throw APIError.http(code)278            }279        } catch let e as APIError {280            throw e281        } catch is CancellationError {282            throw CancellationError()283        } catch let e as URLError where e.code == .cancelled {284            throw CancellationError()285        } catch {286            // hors ligne : dernière réponse connue pour cette adresse287            if let cached = ResponseCache.read(u) {288                data = cached289            } else {290                throw APIError.offline291            }292        }293        do {294            let value = try JSONDecoder().decode(T.self, from: data)295            ResponseCache.write(u, data)296            return value297        } catch {298            throw APIError.decoding(String(describing: error).prefix(300).description)299        }300    }301}302303/// Génération du service retenu, lisible hors de l'acteur (les modèles s'en servent pour ne pas présenter une304/// estimation de la v2 comme un prix de vente attendu de la v3).305enum ServiceGeneration {306    private static let lock = NSLock()307    nonisolated(unsafe) private static var value = UserDefaults.standard.integer(forKey: "api.gen")308    nonisolated(unsafe) private static var pinned: Int?309    static var current: Int { lock.lock(); defer { lock.unlock() }; return pinned ?? value }310    static func set(_ g: Int) { lock.lock(); value = g; lock.unlock() }311    /// Tests : fige la génération vue par les modèles, quoi que réponde le service pendant l'essai.312    static func pin(_ g: Int?) { lock.lock(); pinned = g; lock.unlock() }313}314315/// Dernières réponses JSON gardées sur disque : favoris et fiches récentes restent lisibles hors ligne.316enum ResponseCache {317    private static let dir: URL = {318        let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "api", directoryHint: .isDirectory)319        try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)320        return d321    }()322323    private static func name(_ url: URL) -> String {324        // clé stable indépendante de l'hôte (préproduction ou production)325        let key = url.path + "?" + (url.query ?? "")326        var h: UInt64 = 1469598103934665603327        for b in key.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }328        return String(h, radix: 36)329    }330331    private static func file(_ url: URL) -> URL { dir.appending(path: name(url) + ".json") }332    /// ETag de la réponse gardée (routes v3).333    static func sidecar(_ url: URL) -> URL { dir.appending(path: name(url) + ".etag") }334335    static func write(_ url: URL, _ data: Data) {336        guard data.count < 3_000_000 else { return }337        try? data.write(to: file(url), options: .atomic)338    }339340    static func read(_ url: URL) -> Data? { try? Data(contentsOf: file(url)) }341342    /// Purge les entrées de plus de 30 jours (appelée au lancement).343    static func prune() {344        let limit = Date().addingTimeInterval(-30 * 86400)345        let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []346        for f in items {347            if let d = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, d < limit {348                try? FileManager.default.removeItem(at: f)349            }350        }351    }352}353
Files main
Menu

Theme