SPB Git

Repository Public

V3Client.swift 13.3 KB 309 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/V3Client.swift10// Description      : accès à l'API `/api/v3` — ETag et `If-None-Match`, erreurs11//                    structurées, inscriptions retirées (410), limite de débit12//                    (429), dernières réponses gardées pour le hors ligne.13// Module           : ImmoKa14// Repository       : https://git.spboucher.ai/immo-ka-ios-v315// Project Website  : https://www.immo-ka.com16// Created          : 2026-11-2817// Last Modified    : 2026-11-3018//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: support@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 Foundation9293/// Corps d'erreur de la v3 : `{"error": {"code", "message", "param", "request_id"}}`.94struct V3ErrorBody: Decodable, Sendable, Equatable {95    var code: String96    var message: String97    var param: String?98    var requestID: String?99100    init(code: String, message: String, param: String? = nil, requestID: String? = nil) {101        self.code = code; self.message = message; self.param = param; self.requestID = requestID102    }103104    init(from decoder: Decoder) throws {105        let root = try decoder.container(keyedBy: AnyKey.self)106        let c = try root.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("error"))107        code = c.text(AnyKey("code")) ?? "unknown"108        message = c.text(AnyKey("message")) ?? ""109        param = c.text(AnyKey("param"))110        requestID = c.text(AnyKey("request_id"))111    }112}113114/// Ce que le service dit encore d'une inscription retirée (réponse 410).115struct GoneListing: Decodable, Sendable, Equatable {116    var uid: String117    var title: String?118    var city: String?119    var type: String?120    var lastSeen: Double?121    /// statut donné par la source (`vendu`, `retire`, `loue`) ; nul : disparue sans statut, ce qui n'est pas une vente122    var status: String?123    var statusObservedAt: Double?124125    init(uid: String, title: String? = nil, city: String? = nil, type: String? = nil, lastSeen: Double? = nil,126         status: String? = nil, statusObservedAt: Double? = nil) {127        self.uid = uid; self.title = title; self.city = city; self.type = type128        self.lastSeen = lastSeen; self.status = status; self.statusObservedAt = statusObservedAt129    }130131    init(from decoder: Decoder) throws {132        let root = try decoder.container(keyedBy: AnyKey.self)133        let c = try root.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("listing"))134        uid = c.text(AnyKey("uid")) ?? ""135        title = c.text(AnyKey("title"))136        city = c.text(AnyKey("city"))137        type = c.text(AnyKey("type"))138        lastSeen = c.dbl(AnyKey("last_seen"))139        status = c.text(AnyKey("status"))140        statusObservedAt = c.dbl(AnyKey("status_observed_at"))141    }142143    /// Phrase honnête : un retrait n'est pas une vente.144    var sentence: String {145        switch status {146        case "vendu": "La source indique que cette propriété est vendue."147        case "loue": "La source indique que cette propriété est louée."148        case "retire": "La source a retiré cette inscription."149        default: "Cette inscription n'est plus affichée par sa source. Cela ne veut pas dire qu'elle est vendue."150        }151    }152}153154/// Version de l'API v3 et de son index (`/api/v3/version`).155struct V3Version: Codable, Sendable, Equatable {156    var api: Int157    var version: String158    var builtAt: Double?159    var listings: Int?160    var municipalities: Int?161162    init(api: Int, version: String, builtAt: Double? = nil, listings: Int? = nil, municipalities: Int? = nil) {163        self.api = api; self.version = version; self.builtAt = builtAt; self.listings = listings; self.municipalities = municipalities164    }165166    private enum StoreKeys: String, CodingKey { case api, version, builtAt, listings, municipalities }167168    init(from decoder: Decoder) throws {169        let c = try decoder.container(keyedBy: AnyKey.self)170        api = c.int(AnyKey("api")) ?? 0171        version = c.text(AnyKey("version")) ?? ""172        if let i = try? c.nestedContainer(keyedBy: AnyKey.self, forKey: AnyKey("index")) {173            builtAt = i.dbl(AnyKey("built_at"))174            listings = i.int(AnyKey("listings"))175            municipalities = i.int(AnyKey("municipalities"))176        } else {177            // forme gardée dans les réglages178            builtAt = c.dbl(AnyKey("builtAt"))179            listings = c.int(AnyKey("listings"))180            municipalities = c.int(AnyKey("municipalities"))181        }182    }183184    func encode(to encoder: Encoder) throws {185        var c = encoder.container(keyedBy: StoreKeys.self)186        try c.encode(api, forKey: .api)187        try c.encode(version, forKey: .version)188        try c.encodeIfPresent(builtAt, forKey: .builtAt)189        try c.encodeIfPresent(listings, forKey: .listings)190        try c.encodeIfPresent(municipalities, forKey: .municipalities)191    }192193    private static let key = "api.v3version"194    /// Dernière version reçue (aussi hors ligne).195    static var current: V3Version? {196        UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(V3Version.self, from: $0) }197    }198    static func store(_ v: V3Version) {199        if let d = try? JSONEncoder().encode(v) { UserDefaults.standard.set(d, forKey: key) }200    }201}202203/// Résultat brut d'un appel v3 : utile aux tests et au diagnostic.204struct V3Fetch: Sendable {205    var data: Data206    /// 200 : réponse fraîche ; 304 : copie locale revalidée ; 0 : copie locale servie hors ligne207    var status: Int208    var etag: String?209    var requestID: String?210    var fromCache: Bool { status != 200 }211}212213extension APIClient {214    /// Interprète une réponse HTTP de la v3 (fonction pure, testée) : corps à décoder ou erreur typée.215    /// `cached` est la copie locale rendue sur un 304.216    static func interpretV3(status: Int, data: Data, headers: [String: String], cached: Data?) throws -> Data {217        switch status {218        case 200..<300: return data219        case 304:220            guard let cached else { throw APIError.http(304) }221            return cached222        case 410:223            if let g = try? JSONDecoder().decode(GoneListing.self, from: data) { throw APIError.goneListing(g) }224            throw APIError.gone225        case 429:226            let retry = headers.first { $0.key.lowercased() == "retry-after" }.flatMap { Int($0.value) }227            throw APIError.rateLimited(retryAfter: retry)228        default:229            if let e = try? JSONDecoder().decode(V3ErrorBody.self, from: data) {230                // inscription regroupée : l'en-tête Location nomme la fiche gardée (`/api/v3/listings/<uid>`)231                if status == 404, e.code == "duplicate", let to = APIClient.regroupedUID(headers: headers) { throw APIError.regrouped(to) }232                if status == 404 { throw APIError.notFound }233                throw APIError.server(e, status: status)234            }235            if status == 404 { throw APIError.notFound }236            throw APIError.http(status)237        }238    }239240    /// Identifiant porté par l'en-tête `Location` d'un 404 `duplicate` (fonction pure, testée).241    static func regroupedUID(headers: [String: String]) -> String? {242        guard let loc = headers.first(where: { $0.key.lowercased() == "location" })?.value,243              let r = loc.range(of: "/api/v3/listings/") else { return nil }244        let raw = String(loc[r.upperBound...])245        let uid = raw.removingPercentEncoding ?? raw246        return uid.isEmpty ? nil : uid247    }248249    /// GET d'une route `/api/v3/<path>` : envoie l'ETag de la copie locale, accepte le 304, garde la réponse.250    func fetchV3(_ path: String, query: [String: String?] = [:]) async throws -> V3Fetch {251        guard let u = await url("api/v3/" + path, query: query) else { throw APIError.invalidURL }252        var req = URLRequest(url: u)253        req.httpMethod = "GET"254        // la revalidation est faite ici, pas par le cache d'URLSession255        req.cachePolicy = .reloadIgnoringLocalCacheData256        let cached = ResponseCache.read(u)257        let tag = cached == nil ? nil : ResponseCache.etag(u)258        if let tag { req.setValue(tag, forHTTPHeaderField: "If-None-Match") }259        do {260            let (d, resp) = try await session.data(for: req)261            let http = resp as? HTTPURLResponse262            let status = http?.statusCode ?? 0263            var headers: [String: String] = [:]264            for (k, v) in http?.allHeaderFields ?? [:] { if let k = k as? String, let v = v as? String { headers[k] = v } }265            let body = try APIClient.interpretV3(status: status, data: d, headers: headers, cached: cached)266            let etag = http?.value(forHTTPHeaderField: "ETag")267            if status != 304 { ResponseCache.write(u, body, etag: etag) }268            return V3Fetch(data: body, status: status == 304 ? 304 : 200, etag: etag ?? tag,269                           requestID: http?.value(forHTTPHeaderField: "X-Request-Id"))270        } catch let e as APIError {271            throw e272        } catch is CancellationError {273            throw CancellationError()274        } catch let e as URLError where e.code == .cancelled {275            throw CancellationError()276        } catch {277            // hors ligne : dernière réponse connue pour cette adresse278            if let cached { return V3Fetch(data: cached, status: 0, etag: tag, requestID: nil) }279            throw APIError.offline280        }281    }282283    /// GET JSON d'une route v3, décodé.284    func getV3<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {285        let r = try await fetchV3(path, query: query)286        do {287            return try JSONDecoder().decode(T.self, from: r.data)288        } catch {289            throw APIError.decoding(String(describing: error).prefix(300).description)290        }291    }292}293294extension ResponseCache {295    /// ETag de la copie locale d'une adresse.296    static func etag(_ url: URL) -> String? {297        (try? String(contentsOf: sidecar(url), encoding: .utf8)).flatMap { $0.isEmpty ? nil : $0 }298    }299300    static func write(_ url: URL, _ data: Data, etag: String?) {301        write(url, data)302        if let etag, !etag.isEmpty, data.count < 3_000_000 {303            try? etag.write(to: sidecar(url), atomically: true, encoding: .utf8)304        } else {305            try? FileManager.default.removeItem(at: sidecar(url))306        }307    }308}309
Files main
Menu

Theme