Repository Public
1//2// Fabri-Ka iOS v23// File: FabriKa/Core/API/APIClient.swift4// Description: client de l'API Fabri-Ka v2 — acteur, cache de réponses sur disque, repli hors ligne. Lecture seule,5// sauf l'inscription d'une boutique. Aucun compte, aucun témoin.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213enum APIError: Error, LocalizedError, Sendable, Equatable {14 case notFound15 /// produit que la boutique n'offre plus (410) : proposer la boutique16 case gone(storeId: String?)17 /// produit regroupé sous un autre de même nom : suivre l'identifiant canonique18 case moved(uid: String)19 case http(Int)20 case server(String)21 case offline22 case decoding(String)23 case invalidURL2425 var errorDescription: String? {26 switch self {27 case .notFound: "Introuvable."28 case .gone: "La boutique n'offre plus ce produit."29 case .moved: "Ce produit est regroupé sous un autre."30 case .http(let code): "Le service a répondu \(code)."31 case .server(let message): message32 case .offline: "Connexion impossible. Vérifiez votre accès à Internet."33 case .decoding: "Réponse illisible."34 case .invalidURL: "Adresse invalide."35 }36 }3738 var isOffline: Bool { self == .offline }39}4041/// Résultat d'une lecture : la valeur, et si elle vient du cache faute de réseau.42struct Fetched<T: Sendable>: Sendable {43 var value: T44 var stale: Bool45}4647/// Client HTTP de l'API. Une seule instance (`APIClient.shared`).48actor APIClient {49 static let shared = APIClient()5051 /// Service de la v2. `www.fabri-ka.com` sert encore la v1 : l'app ne la contacte pas.52 static let service = URL(string: "https://fabrika-v2.51-161-112-61.sslip.io")!53 /// Adresse publique des pages (liens partagés).54 static let site = service5556 private let session: URLSession57 private let base: URL5859 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 cfg.httpCookieStorage = nil68 cfg.httpShouldSetCookies = false69 session = URLSession(configuration: cfg)70 base = APIClient.forcedBase ?? APIClient.service71 }7273 /// Adresse imposée par argument de lancement (tests hors ligne et développement) ; n'existe qu'en Debug.74 private static var forcedBase: URL? {75 #if DEBUG76 return (UserDefaults.standard.string(forKey: "FBBaseURL") ?? ProcessInfo.processInfo.environment["FABRIKA_BASE_URL"]).flatMap(URL.init(string:))77 #else78 return nil79 #endif80 }8182 /// URL absolue d'un chemin de l'API (miniatures).83 nonisolated func url(_ path: String, query: [String: String?] = [:]) -> URL? {84 APIClient.compose(base: APIClient.forcedBase ?? APIClient.service, path: path, query: query)85 }8687 /// Segment de chemin encodé (identifiant de boutique = nom de domaine).88 static func segment(_ s: String) -> String {89 var ok = CharacterSet.alphanumerics90 ok.insert(charactersIn: "-._~")91 return s.addingPercentEncoding(withAllowedCharacters: ok) ?? s92 }9394 static func compose(base: URL, path: String, query: [String: String?]) -> URL? {95 guard var comps = URLComponents(url: base, resolvingAgainstBaseURL: false) else { return nil }96 comps.percentEncodedPath = "/" + path97 let items = query.compactMap { k, v -> URLQueryItem? in98 guard let v, !v.isEmpty else { return nil }99 return URLQueryItem(name: k, value: v)100 }.sorted { $0.name < $1.name }101 if !items.isEmpty { comps.queryItems = items }102 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")103 return comps.url104 }105106 private struct ServerError: Decodable {107 var detail: String?108 var reason: String?109 var canonical_uid: String?110 var store_id: String?111 var message: String?112 }113114 /// Lit des octets ; en cas de panne réseau, sert la dernière réponse en cache si elle existe.115 private func load(_ req: URLRequest, cacheKey: URL?) async throws -> (Data, Bool) {116 do {117 let (d, resp) = try await session.data(for: req)118 let code = (resp as? HTTPURLResponse)?.statusCode ?? 0119 if (200..<300).contains(code) { return (d, false) }120 let body = try? JSONDecoder().decode(ServerError.self, from: d)121 switch code {122 case 404:123 if let uid = body?.canonical_uid, !uid.isEmpty { throw APIError.moved(uid: uid) }124 throw APIError.notFound125 case 410:126 if body?.reason == "retire" { throw APIError.gone(storeId: body?.store_id) }127 throw APIError.notFound128 case 429: throw APIError.server(body?.detail ?? "Trop de demandes. Réessayez plus tard.")129 case 503: throw APIError.server(body?.detail ?? "Le répertoire se prépare. Réessayez dans quelques secondes.")130 default:131 if code < 500, let m = body?.detail ?? body?.message { throw APIError.server(m) }132 throw APIError.http(code)133 }134 } catch let e as APIError {135 throw e136 } catch is CancellationError {137 throw CancellationError()138 } catch let e as URLError where e.code == .cancelled {139 throw CancellationError()140 } catch {141 if let k = cacheKey, let cached = ResponseCache.read(k) { return (cached, true) }142 throw APIError.offline143 }144 }145146 /// GET JSON, avec l'origine de la réponse (réseau ou cache hors ligne).147 func fetch<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> Fetched<T> {148 guard let u = url(path, query: query) else { throw APIError.invalidURL }149 let (data, stale) = try await load(URLRequest(url: u), cacheKey: u)150 do {151 let value = try JSONDecoder().decode(T.self, from: data)152 if !stale { ResponseCache.write(u, data) }153 return Fetched(value: value, stale: stale)154 } catch {155 throw APIError.decoding(String(describing: error).prefix(300).description)156 }157 }158159 func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {160 try await fetch(path, query: query, as: type).value161 }162163 /// POST JSON (inscription d'une boutique). Jamais mis en cache.164 func post<T: Decodable & Sendable>(_ path: String, body: Data, as type: T.Type = T.self) async throws -> T {165 guard let u = url(path) else { throw APIError.invalidURL }166 var req = URLRequest(url: u)167 req.httpMethod = "POST"168 req.setValue("application/json", forHTTPHeaderField: "Content-Type")169 req.httpBody = body170 let (data, _) = try await load(req, cacheKey: nil)171 do { return try JSONDecoder().decode(T.self, from: data) } catch {172 throw APIError.decoding(String(describing: error).prefix(300).description)173 }174 }175}176177/// Dernières réponses JSON gardées sur disque : fiches, boutiques et listes consultées restent lisibles hors ligne.178enum ResponseCache {179 private static let dir: URL = {180 let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "api", directoryHint: .isDirectory)181 try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)182 return d183 }()184185 /// Clé stable, indépendante de l'hôte.186 static func key(_ url: URL) -> String {187 let key = url.path + "?" + (url.query ?? "")188 var h: UInt64 = 1469598103934665603189 for b in key.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }190 return String(h, radix: 36)191 }192193 private static func file(_ url: URL) -> URL { dir.appending(path: key(url) + ".json") }194195 static func write(_ url: URL, _ data: Data) {196 guard data.count < 3_000_000 else { return }197 try? data.write(to: file(url), options: .atomic)198 }199200 static func read(_ url: URL) -> Data? { try? Data(contentsOf: file(url)) }201202 /// Purge les entrées de plus de 30 jours (appelée au lancement).203 static func prune() {204 let limit = Date().addingTimeInterval(-30 * 86400)205 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []206 for f in items {207 if let d = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, d < limit {208 try? FileManager.default.removeItem(at: f)209 }210 }211 }212213 static func clear() {214 let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []215 for f in items { try? FileManager.default.removeItem(at: f) }216 }217}218