Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Core/API/APIClient.swift10// Description : client de l'API Lou-Ka (v2 et v3) — acteur, validation par11// ETag, erreurs structurées, cache des dernières réponses,12// annulation, repli hors ligne.13// Module : LouKa14// Repository : https://git.spboucher.ai/lou-ka-ios-v315// Project Website : https://www.lou-ka.com16// Created : 2026-11-2517// Last Modified : 2026-11-2818//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 Foundation9293enum APIError: Error, LocalizedError, Sendable {94 case notFound95 case gone96 case http(Int)97 /// Erreur structurée de l'API v3 : `{"error": {"code", "message", "param", "request_id"}}`.98 case api(status: Int, code: String, message: String, param: String?, requestID: String?)99 /// 429 : trop de requêtes ; délai conseillé par l'en-tête `Retry-After`, en secondes.100 case rateLimited(retryAfter: Int?)101 case offline102 case decoding(String)103 case invalidURL104105 var errorDescription: String? {106 switch self {107 case .notFound: "Introuvable."108 case .gone: "Cette annonce a été retirée."109 case .http(let code): "Le serveur a répondu \(code)."110 case .api(_, _, let message, _, _): message111 case .rateLimited(let s): s.map { "Trop de requêtes. Réessayez dans \($0) s." } ?? "Trop de requêtes. Réessayez dans un instant."112 case .offline: "Connexion impossible. Vérifiez votre accès à Internet."113 case .decoding: "Réponse illisible."114 case .invalidURL: "Adresse invalide."115 }116 }117118 var isOffline: Bool { if case .offline = self { return true }; return false }119120 /// Code d'erreur de l'API v3 (`not_found`, `gone`, `no_estimate`, `invalid_parameter`…), s'il y en a un.121 var code: String? {122 switch self {123 case .api(_, let code, _, _, _): code124 case .notFound: "not_found"125 case .gone: "gone"126 case .rateLimited: "rate_limited"127 default: nil128 }129 }130131 /// Lit le corps d'une réponse en erreur de l'API v3.132 static func from(status: Int, data: Data, retryAfter: String?) -> APIError {133 struct Envelope: Decodable {134 struct Body: Decodable { var code: String?; var message: String?; var param: String?; var request_id: String? }135 var error: Body136 }137 let body = (try? JSONDecoder().decode(Envelope.self, from: data))?.error138 if status == 429 { return .rateLimited(retryAfter: retryAfter.flatMap { Int($0) }) }139 if let code = body?.code {140 // « no_estimate » est un 404 qui ne veut pas dire « annonce introuvable »141 if status == 410 || code == "gone" { return .gone }142 if status == 404, code == "not_found" { return .notFound }143 return .api(status: status, code: code, message: body?.message ?? "Le serveur a répondu \(status).", param: body?.param, requestID: body?.request_id)144 }145 switch status {146 case 404: return .notFound147 case 410: return .gone148 default: return .http(status)149 }150 }151}152153/// Client HTTP de l'API. Une seule instance (`APIClient.shared`).154actor APIClient {155 static let shared = APIClient()156157 /// Adresse de production, puis repli de préproduction tant que la v2 n'y est pas en ligne.158 static let primary = URL(string: "https://www.lou-ka.com")!159 static let fallback = URL(string: "https://louka-v2.51-161-112-61.sslip.io")!160 private static let baseKey = "api.base"161162 private let session: URLSession163 private var base: URL164 private var resolved = false165 private var resolving: Task<URL, Never>?166167 init() {168 let cfg = URLSessionConfiguration.default169 cfg.timeoutIntervalForRequest = 20170 cfg.timeoutIntervalForResource = 60171 cfg.waitsForConnectivity = false172 cfg.requestCachePolicy = .useProtocolCachePolicy173 cfg.urlCache = URLCache(memoryCapacity: 16 << 20, diskCapacity: 96 << 20, directory: nil)174 cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]175 session = URLSession(configuration: cfg)176 base = APIClient.initialBase()177 }178179 private static func initialBase() -> URL {180 // argument de lancement ou variable d'environnement : tests et développement181 if let forced = UserDefaults.standard.string(forKey: "LKBaseURL") ?? ProcessInfo.processInfo.environment["LOUKA_BASE_URL"],182 let u = URL(string: forced) {183 return u184 }185 if let saved = UserDefaults.standard.string(forKey: baseKey), let u = URL(string: saved) { return u }186 return primary187 }188189 private static var baseIsForced: Bool {190 UserDefaults.standard.string(forKey: "LKBaseURL") != nil191 || ProcessInfo.processInfo.environment["LOUKA_BASE_URL"] != nil192 }193194 /// Adresse de base retenue ; sondée une fois par lancement (`/api/version` doit répondre api ≥ 2).195 func baseURL() async -> URL {196 if resolved || APIClient.baseIsForced { return base }197 if let t = resolving { return await t.value }198 let session = self.session199 let t = Task<URL, Never> {200 for candidate in [APIClient.primary, APIClient.fallback] {201 var req = URLRequest(url: candidate.appending(path: "api/version"))202 req.timeoutInterval = 6203 req.cachePolicy = .reloadIgnoringLocalCacheData204 if let (data, resp) = try? await session.data(for: req),205 (resp as? HTTPURLResponse)?.statusCode == 200,206 let v = try? JSONDecoder().decode(APIVersion.self, from: data), v.api >= 2 {207 return candidate208 }209 }210 // rien ne répond (hors ligne) : on garde la dernière adresse connue211 return UserDefaults.standard.string(forKey: APIClient.baseKey).flatMap(URL.init(string:)) ?? APIClient.fallback212 }213 resolving = t214 let u = await t.value215 base = u216 resolved = true217 resolving = nil218 UserDefaults.standard.set(u.absoluteString, forKey: APIClient.baseKey)219 return u220 }221222 /// URL absolue d'un chemin de l'API (liens PDF, images).223 func url(_ path: String, query: [String: String?] = [:]) async -> URL? {224 let b = await baseURL()225 guard var comps = URLComponents(url: b.appending(path: path), resolvingAgainstBaseURL: false) else { return nil }226 let items = query.compactMap { k, v -> URLQueryItem? in227 guard let v, !v.isEmpty else { return nil }228 return URLQueryItem(name: k, value: v)229 }.sorted { $0.name < $1.name }230 if !items.isEmpty { comps.queryItems = items }231 // « + » doit être encodé (grandeurs « 6½+ »)232 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")233 return comps.url234 }235236 /// GET JSON. Validation par ETag (`If-None-Match` → 304 : la copie locale est servie sans transfert) ;237 /// en cas de panne réseau, la dernière réponse connue est servie si elle existe.238 func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {239 guard let u = await url(path, query: query) else { throw APIError.invalidURL }240 let data = try await data(for: u)241 do {242 let value = try JSONDecoder().decode(T.self, from: data.body)243 if data.fresh { ResponseCache.write(u, data.body, etag: data.etag) }244 return value245 } catch {246 throw APIError.decoding(String(describing: error).prefix(300).description)247 }248 }249250 /// Corps d'une réponse ; `fresh` est faux quand il vient de la copie locale (304 ou hors ligne).251 private func data(for u: URL) async throws -> (body: Data, etag: String?, fresh: Bool) {252 var req = URLRequest(url: u)253 req.httpMethod = "GET"254 let known = ResponseCache.read(u)255 if known != nil, let etag = ResponseCache.etag(u) {256 req.setValue(etag, forHTTPHeaderField: "If-None-Match")257 // la validation est la nôtre : le cache du système ne doit pas répondre à notre place258 req.cachePolicy = .reloadIgnoringLocalCacheData259 }260 do {261 let (d, resp) = try await session.data(for: req)262 let http = resp as? HTTPURLResponse263 let code = http?.statusCode ?? 0264 if code == 304, let known { stats.notModified += 1; return (known, nil, false) }265 guard (200..<300).contains(code) else {266 throw APIError.from(status: code, data: d, retryAfter: http?.value(forHTTPHeaderField: "Retry-After"))267 }268 stats.fetched += 1269 return (d, http?.value(forHTTPHeaderField: "ETag"), true)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 known { stats.offline += 1; return (known, nil, false) }279 throw APIError.offline280 }281 }282283 /// Compteurs de la session (Réglages › Données) : réponses transférées, validées par ETag, servies hors ligne.284 struct Stats: Sendable { var fetched = 0; var notModified = 0; var offline = 0 }285 private var stats = Stats()286 func sessionStats() -> Stats { stats }287}288289/// Dernières réponses JSON gardées sur disque : favoris et fiches récentes restent lisibles hors ligne.290enum ResponseCache {291 private static let dir: URL = {292 let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "api", directoryHint: .isDirectory)293 try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)294 return d295 }()296297 private static func file(_ url: URL) -> URL {298 // clé stable indépendante de l'hôte (préproduction ou production)299 let key = url.path + "?" + (url.query ?? "")300 var h: UInt64 = 1469598103934665603301 for b in key.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }302 return dir.appending(path: String(h, radix: 36) + ".json")303 }304305 static func write(_ url: URL, _ data: Data, etag: String? = nil) {306 guard data.count < 3_000_000 else { return }307 let f = file(url)308 try? data.write(to: f, options: .atomic)309 let e = f.appendingPathExtension("etag")310 if let etag, let d = etag.data(using: .utf8) { try? d.write(to: e, options: .atomic) } else { try? FileManager.default.removeItem(at: e) }311 }312313 /// Validateur de la copie locale (en-tête `ETag` de la dernière réponse 200).314 static func etag(_ url: URL) -> String? {315 (try? Data(contentsOf: file(url).appendingPathExtension("etag"))).flatMap { String(data: $0, encoding: .utf8) }316 }317318 /// Taille du cache sur disque, en octets.319 static func size() -> Int {320 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.fileSizeKey])) ?? []321 return items.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }322 }323324 static func clear() {325 for f in (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? [] { try? FileManager.default.removeItem(at: f) }326 }327328 static func read(_ url: URL) -> Data? { try? Data(contentsOf: file(url)) }329330 /// Purge les entrées de plus de 30 jours (appelée au lancement).331 static func prune() {332 let limit = Date().addingTimeInterval(-30 * 86400)333 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []334 for f in items {335 if let d = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, d < limit {336 try? FileManager.default.removeItem(at: f)337 }338 }339 }340}341