SPB Git

Repository Public

API.swift 10.4 KB 245 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Valo-Plex iOS9// File             : ValoPlex/Core/API.swift10// Description      : client de l'API publique du site11//                    (https://www.valo-plex.com/api/v1) : aucune clé, aucun12//                    compte.13// Module           : ValoPlex14// Repository       : https://git.spboucher.ai/valo-plex-ios15// Project Website  : https://www.valo-plex.com16// Created          : 2026-12-0117// 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: 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 Foundation9293struct ErreurAPI: Error, LocalizedError, Sendable, Equatable {94    let statut: Int95    let code: String96    let message: String9798    var errorDescription: String? { message }99    var introuvable: Bool { statut == 404 }100101    static let reseau = ErreurAPI(statut: 0, code: "reseau", message: "Le serveur de Valo-Plex ne répond pas. Vérifiez la connexion, puis réessayez.")102    static let lecture = ErreurAPI(statut: 0, code: "lecture", message: "La réponse du serveur n'a pas pu être lue. Mettez l'application à jour si le problème persiste.")103}104105enum API {106    static let base = "https://www.valo-plex.com"107    static let site = URL(string: base)!108109    static let decodeur: JSONDecoder = {110        let d = JSONDecoder()111        d.keyDecodingStrategy = .convertFromSnakeCase112        return d113    }()114115    private static let session: URLSession = {116        let c = URLSessionConfiguration.default117        c.timeoutIntervalForRequest = 20118        c.waitsForConnectivity = false119        c.httpAdditionalHeaders = ["Accept": "application/json", "User-Agent": "ValoPlex-iOS/1.0"]120        return URLSession(configuration: c)121    }()122123    private struct Enveloppe: Decodable {124        struct Corps: Decodable { let code: String?; let message: String? }125        let erreur: Corps126    }127128    static func url(_ chemin: String, _ requete: [String: String?] = [:]) -> URL {129        var c = URLComponents(string: base + chemin)!130        let q = requete.compactMap { k, v in v.flatMap { $0.isEmpty ? nil : URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }131        if !q.isEmpty { c.queryItems = q }132        return c.url!133    }134135    static func decoder<T: Decodable>(_ type: T.Type, _ donnees: Data) throws -> T {136        do { return try decodeur.decode(T.self, from: donnees) } catch { throw ErreurAPI.lecture }137    }138139    private static func envoyer<T: Decodable & Sendable>(_ requete: URLRequest) async throws -> T {140        let donnees: Data141        let reponse: URLResponse142        do {143            (donnees, reponse) = try await session.data(for: requete)144        } catch is CancellationError {145            throw CancellationError()146        } catch let e as URLError where e.code == .cancelled {147            throw CancellationError()148        } catch {149            throw ErreurAPI.reseau150        }151        let statut = (reponse as? HTTPURLResponse)?.statusCode ?? 0152        guard (200..<300).contains(statut) else {153            if let e = try? decodeur.decode(Enveloppe.self, from: donnees) {154                throw ErreurAPI(statut: statut, code: e.erreur.code ?? "erreur", message: e.erreur.message ?? "Erreur \(statut).")155            }156            throw ErreurAPI(statut: statut, code: "http", message: "Le serveur a répondu par une erreur (\(statut)).")157        }158        return try decoder(T.self, donnees)159    }160161    /// `frais` : ignore la copie gardée par l'appareil (le service autorise 30 minutes de cache sur le marché).162    static func get<T: Decodable & Sendable>(_ chemin: String, _ requete: [String: String?] = [:], frais: Bool = false) async throws -> T {163        var r = URLRequest(url: url(chemin, requete))164        if frais { r.cachePolicy = .reloadIgnoringLocalCacheData }165        return try await envoyer(r)166    }167168    static func post<T: Decodable & Sendable, C: Encodable>(_ chemin: String, _ corps: C) async throws -> T {169        var r = URLRequest(url: url(chemin))170        r.httpMethod = "POST"171        r.setValue("application/json", forHTTPHeaderField: "Content-Type")172        r.httpBody = try JSONEncoder().encode(corps)173        return try await envoyer(r)174    }175176    // MARK: routes177178    static func version() async throws -> VersionAPI { try await get("/api/v1/version") }179180    static func recherche(_ q: String, n: Int = 8) async throws -> [Resultat] {181        let r: ReponseRecherche = try await get("/api/v1/recherche", ["q": q, "n": String(n)])182        return r.resultats183    }184185    static func fiche(_ id: String) async throws -> Fiche {186        // même garde que le site : un identifiant du rôle est alphanumérique187        guard id.count >= 10, id.count <= 30, id.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }) else {188            throw ErreurAPI(statut: 404, code: "introuvable", message: "Aucun immeuble de 2 logements et plus ne porte cet identifiant au rôle.")189        }190        return try await get("/api/v1/immeubles/\(id)")191    }192193    struct FiltreAnnonces: Hashable, Sendable {194        var region: String = ""195        var classe: String = ""196        var tri: String = "ecart"197        var prixMax: Int = 0198        var revenuDeclare = false199200        var actifs: Int { [!region.isEmpty, !classe.isEmpty, prixMax > 0, revenuDeclare].filter { $0 }.count }201    }202203    static func annonces(_ f: FiltreAnnonces, page: Int, parPage: Int = 24) async throws -> ReponseAnnonces {204        try await get("/api/v1/annonces", [205            "region": f.region, "classe": f.classe, "tri": f.tri, "page": String(page), "par_page": String(parPage),206            "prix_max": f.prixMax > 0 ? String(f.prixMax) : nil, "revenu_declare": f.revenuDeclare ? "1" : nil,207        ])208    }209210    static func marche(frais: Bool = false) async throws -> Marche { try await get("/api/v1/marche", frais: frais) }211212    static func region(_ cle: String) async throws -> MarcheRegion {213        let net = cle.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(.init(charactersIn: "/"))) ?? cle214        return try await get("/api/v1/marche/region/\(net)")215    }216217    struct VueCarte: Hashable, Sendable {218        var ouest: Double219        var sud: Double220        var est: Double221        var nord: Double222        var zoom: Double223224        /// Arrondie : un frémissement de la caméra ne relance pas de requête.225        init(ouest: Double, sud: Double, est: Double, nord: Double, zoom: Double) {226            let r = { (x: Double) in (x * 20_000).rounded() / 20_000 }227            self.ouest = r(ouest); self.sud = r(sud); self.est = r(est); self.nord = r(nord)228            self.zoom = (zoom * 10).rounded() / 10229        }230    }231232    /// Sous le zoom 15 : cases agrégées ; à partir de 15 : immeubles un à un (9 000 au plus) ; `vendre` : toujours des points.233    static func carte(_ v: VueCarte, classe: String, vendre: Bool) async throws -> ReponseCarte {234        let f = { (x: Double) in String(format: "%.5f", x) }235        return try await get("/api/v1/carte", [236            "o": f(v.ouest), "s": f(v.sud), "e": f(v.est), "n": f(v.nord), "z": String(Int(max(0, v.zoom.rounded(.down)))),237            "classe": classe, "vendre": vendre ? "1" : nil,238        ])239    }240241    static func modele() async throws -> Modele { try await get("/api/v1/modele") }242243    static func proForma(_ e: EntreeProForma) async throws -> ProForma { try await post("/api/v1/proforma", e) }244}245
Files main
Menu

Theme