Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Core/V3/V3Client.swift10// Description : niveau du service (API 2 ou API v3) et routes de l'API v3.11// L'app sonde `/api/v3/version` : tant que le service ne12// sert pas la v3 avec un moteur lisible, elle reste13// entièrement sur les routes de l'API 2.14// Module : VraiPrix15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2818// Last Modified : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394/// Ce que sert l'adresse retenue. `v3` : `/api/v3/version` répond `api: 3` et le moteur de valeur se lit.95enum ServiceLevel: String, Sendable, Codable {96 case v2, v39798 private static let key = "service.level"99 nonisolated(unsafe) private static var cached: ServiceLevel?100 private static let lock = NSLock()101102 /// Niveau imposé au lancement (`-VPLevel v2|v3`) : tests et captures, en Debug seulement.103 static var forced: ServiceLevel? {104 #if DEBUG105 UserDefaults.standard.string(forKey: "VPLevel").flatMap(ServiceLevel.init(rawValue:))106 #else107 nil108 #endif109 }110111 /// Dernier niveau connu (API 2 avant la première sonde).112 static var current: ServiceLevel {113 if let f = forced { return f }114 lock.lock(); defer { lock.unlock() }115 if let c = cached { return c }116 let v = UserDefaults.standard.string(forKey: key).flatMap(ServiceLevel.init(rawValue:)) ?? .v2117 cached = v118 return v119 }120121 static func store(_ level: ServiceLevel) {122 lock.lock(); cached = level; lock.unlock()123 UserDefaults.standard.set(level.rawValue, forKey: key)124 }125126 /// Lecture de `GET /api/v3/version`. Tout ce qui n'est pas un JSON `api: 3` avec un moteur lisible vaut API 2127 /// (la page HTML du site quand la route n'existe pas, un moteur en migration).128 static func read(versionBody data: Data) -> (level: ServiceLevel, info: V3ServiceInfo?) {129 guard let j = JSONValue.parse(data), j["api"].int == 3 else { return (.v2, nil) }130 let info = V3ServiceInfo(json: j)131 return (info.routesAvailable ? .v3 : .v2, info)132 }133}134135/// `GET /api/v3/version`.136struct V3ServiceInfo: JSONModel, Equatable {137 var routesAvailable: Bool138 var model: String?139 var valueDate: String?140 var legacyValueSource: String?141 var listings: Int?142143 init(json j: JSONValue) {144 let e = j["engine"]145 routesAvailable = e["routes_available"].bool ?? false146 model = e["model"].text; valueDate = e["value_date"].text; legacyValueSource = e["legacy_value_source"].text147 listings = j["web_index"]["listings"].int148 }149}150151extension APIClient {152 /// Sonde le niveau du service à l'adresse retenue ; mémorise la réponse. Hors ligne : le dernier niveau connu.153 @discardableResult154 func probeLevel() async -> ServiceLevel {155 if let f = ServiceLevel.forced { return f }156 guard let u = await url("api/v3/version") else { return ServiceLevel.current }157 var req = URLRequest(url: u)158 req.timeoutInterval = 8159 req.cachePolicy = .reloadIgnoringLocalCacheData160 guard let (data, resp) = try? await URLSession.shared.data(for: req) else { return ServiceLevel.current }161 let code = (resp as? HTTPURLResponse)?.statusCode ?? 0162 // 5xx : panne passagère, on garde le dernier niveau connu ; toute autre réponse se lit163 if code >= 500 { return ServiceLevel.current }164 let level = code == 200 ? ServiceLevel.read(versionBody: data).level : .v2165 ServiceLevel.store(level)166 return level167 }168169 private func seg(_ s: String) -> String {170 var allowed = CharacterSet.alphanumerics171 allowed.insert(charactersIn: "-_.~")172 return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s173 }174175 private func v3<T: JSONModel>(_ path: String, _ query: [String: String?] = [:]) async throws -> Fetched<T> {176 try await fetch("api/v3/" + path, query: query)177 }178179 // MARK: Recherche, propriétés180181 func v3Search(_ q: String, limit: Int = 8) async throws -> SearchV3 {182 try await v3("recherche", ["q": String(q.trimmingCharacters(in: .whitespacesAndNewlines).prefix(120)), "limit": String(limit)]).value183 }184185 func v3Property(_ id: String) async throws -> Fetched<PropertyV3> { try await v3("proprietes/" + seg(id)) }186187 func v3Comparables(_ id: String, k: Int = 8) async throws -> ComparablesV3 {188 try await v3("proprietes/" + seg(id) + "/comparables", ["k": String(k)]).value189 }190191 func v3Position(id: String, price: Double, asked: Bool) async throws -> PositionV3 {192 try await v3("position", ["id": id, "prix": String(Int(price.rounded())), "nature": asked ? "demande" : "paye"]).value193 }194195 func v3Properties(bbox: MapBounds, limit: Int = 600) async throws -> PropertiesV3 {196 try await v3("proprietes", ["bbox": bbox.bbox, "limit": String(limit)]).value197 }198199 // MARK: Ventes, inscriptions200201 func v3Sales(_ query: [String: String?], cursor: String? = nil, limit: Int = 30) async throws -> Fetched<SalesPageV3> {202 var q = query203 q["limit"] = String(limit); q["cursor"] = cursor204 return try await v3("ventes", q)205 }206207 func v3Sales(bbox: MapBounds, months: Int, limit: Int = 500) async throws -> SalesPageV3 {208 try await v3("ventes", ["bbox": bbox.bbox, "mois": String(months), "limit": String(limit)]).value209 }210211 func v3Sale(_ id: String) async throws -> Fetched<SaleDetailV3> { try await v3("ventes/" + seg(id)) }212213 func v3Listings(_ query: [String: String?], cursor: String? = nil, limit: Int = 24) async throws -> Fetched<ListingsPageV3> {214 var q = query215 q["limit"] = String(limit); q["cursor"] = cursor216 return try await v3("inscriptions", q)217 }218219 func v3Listings(bbox: MapBounds, limit: Int = 300) async throws -> ListingsPageV3 {220 try await v3("inscriptions", ["bbox": bbox.bbox, "limit": String(limit)]).value221 }222223 func v3Listing(_ uid: String) async throws -> Fetched<ListingV3> { try await v3("inscriptions/" + seg(uid)) }224225 // MARK: Marché, indice, territoires226227 func v3Market(territory: String = "qc", genre: String = "residentiel") async throws -> Fetched<MarketV3> {228 try await v3("marche", ["territoire": territory, "genre": genre])229 }230231 func v3MarketSeries(territory: String, genre: String, freq: String = "T") async throws -> MarketSeriesV3 {232 try await v3("marche/series", ["territoire": territory, "genre": genre, "freq": freq]).value233 }234235 func v3Rankings(criterion: String, genre: String?, level: String?, order: String = "desc", limit: Int = 20) async throws -> RankingV3 {236 try await v3("marche/classements", ["critere": criterion, "genre": genre, "niveau": level, "ordre": order, "limit": String(limit)]).value237 }238239 func v3Index(territory: String, genre: String, freq: String = "T") async throws -> IndexSeriesV3 {240 try await v3("indice/" + seg(territory), ["genre": genre, "freq": freq]).value241 }242243 func v3Territories(level: String? = nil, q: String? = nil, parent: String? = nil, cursor: String? = nil, limit: Int = 100) async throws -> TerritoryListV3 {244 try await v3("territoires", ["niveau": level, "q": q, "parent": parent, "cursor": cursor, "limit": String(limit)]).value245 }246247 func v3Territory(_ id: String) async throws -> Fetched<TerritoryV3> { try await v3("territoires/" + seg(id)) }248249 func v3StreetUnits(_ id: String, cursor: String? = nil, limit: Int = 60) async throws -> StreetUnitsV3 {250 try await v3("territoires/" + seg(id) + "/unites", ["cursor": cursor, "limit": String(limit)]).value251 }252253 // MARK: Modèle, validation, estimation libre254255 func v3Model() async throws -> Fetched<ModelV3> { try await v3("modele") }256257 func v3Validation(population: String? = nil, dimension: String? = nil, method: String? = nil) async throws -> ValidationV3 {258 try await v3("validation", ["population": population, "dimension": dimension, "methode": method]).value259 }260261 func v3FreeEstimate(genre: String, municipality: String?, lat: Double?, lng: Double?, areaM2: Double?, year: Int?) async throws -> FreeEstimateV3 {262 try await v3("estimation-libre", ["genre": genre, "municipalite": lat == nil ? municipality : nil,263 "lat": lat.map { String($0) }, "lng": lng.map { String($0) },264 "aire_m2": areaM2.map { String($0) }, "annee": year.map(String.init)]).value265 }266}267