Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Core/API/APIClient.swift4// Description: client de l'API Food-Ka v2 — acteur, sonde du service (www puis préproduction), cache de5// réponses sur disque, repli hors ligne.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213enum APIError: Error, LocalizedError, Sendable, Equatable {14 case notFound15 case http(Int)16 case server(String)17 case offline18 case decoding(String)19 case invalidURL2021 var errorDescription: String? {22 switch self {23 case .notFound: "Introuvable."24 case .http(let code): "Le serveur a répondu \(code)."25 case .server(let message): message26 case .offline: "Connexion impossible. Vérifiez votre accès à Internet."27 case .decoding: "Réponse illisible."28 case .invalidURL: "Adresse invalide."29 }30 }3132 var isOffline: Bool { self == .offline }33}3435/// Résultat d'une lecture : la valeur, et si elle vient du cache faute de réseau.36struct Fetched<T: Sendable>: Sendable {37 var value: T38 var stale: Bool39}4041/// Client HTTP de l'API. Une seule instance (`APIClient.shared`).42///43/// L'app parle à la v2 du service. Elle sonde d'abord `https://www.food-ka.com/api/version` et n'utilise la44/// production que si elle répond `api: 2` (bascule future) ; sinon, la préproduction.45actor APIClient {46 static let shared = APIClient()4748 static let primary = URL(string: "https://www.food-ka.com")!49 static let fallback = URL(string: "https://foodka-v2.51-161-112-61.sslip.io")!50 /// Adresse publique du site (liens partagés).51 static let site = URL(string: "https://www.food-ka.com")!52 private static let baseKey = "api.base"5354 private let session: URLSession55 private var base: URL56 private var resolved = false57 private var resolving: Task<URL, Never>?5859 init() {60 let cfg = URLSessionConfiguration.default61 cfg.timeoutIntervalForRequest = 2562 cfg.timeoutIntervalForResource = 9063 cfg.waitsForConnectivity = false64 cfg.requestCachePolicy = .useProtocolCachePolicy65 cfg.urlCache = URLCache(memoryCapacity: 16 << 20, diskCapacity: 64 << 20, directory: nil)66 cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]67 session = URLSession(configuration: cfg)68 let saved = UserDefaults.standard.string(forKey: APIClient.baseKey).flatMap(URL.init(string:))69 base = APIClient.forcedBase ?? saved ?? APIClient.fallback70 }7172 /// Adresse imposée par argument de lancement ou variable d'environnement (tests et développement).73 private static var forcedBase: URL? {74 (UserDefaults.standard.string(forKey: "FKBaseURL") ?? ProcessInfo.processInfo.environment["FOODKA_BASE_URL"]).flatMap(URL.init(string:))75 }7677 static var candidates: [URL] {78 if let f = forcedBase { return [f] }79 return [primary, fallback]80 }8182 /// Une réponse de `/api/version` désigne-t-elle une v2 ?83 static func isV2(_ data: Data) -> ServiceInfo? {84 guard let v = try? JSONDecoder().decode(ServiceInfo.self, from: data), v.api >= 2 else { return nil }85 return v86 }8788 private static func probe(_ url: URL, session: URLSession) async -> Bool {89 var req = URLRequest(url: url.appending(path: "api/version"))90 req.timeoutInterval = 691 req.cachePolicy = .reloadIgnoringLocalCacheData92 guard let (data, resp) = try? await session.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200,93 let v = isV2(data) else { return false }94 ServiceInfo.store(v)95 return true96 }9798 /// Service retenu ; sondé une fois par lancement.99 func resolve() async -> URL {100 if resolved { return base }101 if let t = resolving { return await t.value }102 let session = self.session103 let current = base104 let t = Task<URL, Never> {105 for candidate in APIClient.candidates where await APIClient.probe(candidate, session: session) { return candidate }106 // aucune v2 ne répond (hors ligne) : dernier service connu, le cache de réponses porte la même forme107 return APIClient.forcedBase ?? current108 }109 resolving = t110 let b = await t.value111 base = b112 resolved = true113 resolving = nil114 if APIClient.forcedBase == nil { UserDefaults.standard.set(b.absoluteString, forKey: APIClient.baseKey) }115 return b116 }117118 func baseURL() async -> URL { await resolve() }119120 /// URL absolue d'un chemin de l'API (miniatures, PDF).121 func url(_ path: String, query: [String: String?] = [:]) async -> URL? {122 APIClient.compose(base: await resolve(), path: path, query: query)123 }124125 /// Segment de chemin encodé : un identifiant de produit (« maxi:20894117004_EA ») garde ses deux-points.126 static func segment(_ s: String) -> String {127 var ok = CharacterSet.alphanumerics128 ok.insert(charactersIn: "-._~:")129 return s.addingPercentEncoding(withAllowedCharacters: ok) ?? s130 }131132 static func compose(base: URL, path: String, query: [String: String?]) -> URL? {133 // `path` est déjà encodé (les identifiants de produit passent par `APIClient.segment`)134 guard var comps = URLComponents(url: base, resolvingAgainstBaseURL: false) else { return nil }135 comps.percentEncodedPath = "/" + path136 let items = query.compactMap { k, v -> URLQueryItem? in137 guard let v, !v.isEmpty else { return nil }138 return URLQueryItem(name: k, value: v)139 }.sorted { $0.name < $1.name }140 if !items.isEmpty { comps.queryItems = items }141 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")142 return comps.url143 }144145 /// Lit des octets ; en cas de panne réseau, sert la dernière réponse en cache si elle existe.146 private func load(_ req: URLRequest, cacheKey: URL?) async throws -> (Data, Bool) {147 do {148 let (d, resp) = try await session.data(for: req)149 let code = (resp as? HTTPURLResponse)?.statusCode ?? 0150 switch code {151 case 200..<300: return (d, false)152 case 404, 410: throw APIError.notFound // 410 : route retirée153 default:154 if code == 503 { throw APIError.server("Le catalogue se prépare. Réessayez dans quelques secondes.") }155 if let m = (try? JSONDecoder().decode(ServerError.self, from: d))?.detail, code < 500, code != 429 { throw APIError.server(m) }156 if code == 429 { throw APIError.server("Trop de requêtes. Réessayez dans une minute.") }157 throw APIError.http(code)158 }159 } catch let e as APIError {160 throw e161 } catch is CancellationError {162 throw CancellationError()163 } catch let e as URLError where e.code == .cancelled {164 throw CancellationError()165 } catch {166 if let k = cacheKey, let cached = ResponseCache.read(k) { return (cached, true) }167 throw APIError.offline168 }169 }170171 private struct ServerError: Decodable { var detail: String }172173 /// GET JSON, avec l'origine de la réponse (réseau ou cache hors ligne).174 func fetch<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> Fetched<T> {175 guard let u = await url(path, query: query) else { throw APIError.invalidURL }176 let (data, stale) = try await load(URLRequest(url: u), cacheKey: u)177 do {178 let value = try JSONDecoder().decode(T.self, from: data)179 if !stale { ResponseCache.write(u, data) }180 return Fetched(value: value, stale: stale)181 } catch {182 throw APIError.decoding(String(describing: error).prefix(300).description)183 }184 }185186 func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {187 try await fetch(path, query: query, as: type).value188 }189190 /// GET brut (réponses conservées telles quelles).191 func raw(_ path: String, query: [String: String?] = [:]) async throws -> Data {192 guard let u = await url(path, query: query) else { throw APIError.invalidURL }193 let (data, stale) = try await load(URLRequest(url: u), cacheKey: u)194 if !stale { ResponseCache.write(u, data) }195 return data196 }197198 /// POST JSON (comparaison du panier). Jamais mis en cache ici : le panier garde lui-même sa dernière comparaison.199 func post<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], body: Data, as type: T.Type = T.self) async throws -> T {200 guard let u = await url(path, query: query) else { throw APIError.invalidURL }201 var req = URLRequest(url: u)202 req.httpMethod = "POST"203 req.setValue("application/json", forHTTPHeaderField: "Content-Type")204 req.httpBody = body205 let (data, _) = try await load(req, cacheKey: nil)206 do { return try JSONDecoder().decode(T.self, from: data) } catch {207 throw APIError.decoding(String(describing: error).prefix(300).description)208 }209 }210211 /// POST JSON, réponse brute.212 func postRaw(_ path: String, body: Data) async throws -> Data {213 guard let u = await url(path) else { throw APIError.invalidURL }214 var req = URLRequest(url: u)215 req.httpMethod = "POST"216 req.setValue("application/json", forHTTPHeaderField: "Content-Type")217 req.httpBody = body218 return try await load(req, cacheKey: nil).0219 }220221 /// Télécharge un rapport PDF dans un fichier temporaire.222 func download(_ path: String, query: [String: String?], fileName: String) async throws -> URL {223 guard let u = await url(path, query: query) else { throw APIError.invalidURL }224 var req = URLRequest(url: u)225 req.setValue("application/pdf", forHTTPHeaderField: "Accept")226 req.timeoutInterval = 60227 let (data, _) = try await load(req, cacheKey: nil)228 guard data.prefix(4) == Data("%PDF".utf8) else { throw APIError.decoding("pas un PDF") }229 let dir = FileManager.default.temporaryDirectory.appending(path: "rapports", directoryHint: .isDirectory)230 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)231 let file = dir.appending(path: fileName)232 try data.write(to: file, options: .atomic)233 return file234 }235}236237/// Dernières réponses JSON gardées sur disque : fiches consultées, soldes et rayons restent lisibles hors ligne.238enum ResponseCache {239 private static let dir: URL = {240 let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "api", directoryHint: .isDirectory)241 try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)242 return d243 }()244245 /// Clé stable, indépendante de l'hôte (préproduction ou production).246 static func key(_ url: URL) -> String {247 let key = url.path + "?" + (url.query ?? "")248 var h: UInt64 = 1469598103934665603249 for b in key.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }250 return String(h, radix: 36)251 }252253 private static func file(_ url: URL) -> URL { dir.appending(path: key(url) + ".json") }254255 static func write(_ url: URL, _ data: Data) {256 guard data.count < 3_000_000 else { return }257 try? data.write(to: file(url), options: .atomic)258 }259260 static func read(_ url: URL) -> Data? { try? Data(contentsOf: file(url)) }261262 /// Purge les entrées de plus de 30 jours (appelée au lancement).263 static func prune() {264 let limit = Date().addingTimeInterval(-30 * 86400)265 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []266 for f in items {267 if let d = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, d < limit {268 try? FileManager.default.removeItem(at: f)269 }270 }271 }272273 static func clear() {274 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []275 for f in items { try? FileManager.default.removeItem(at: f) }276 }277}278