SPB Git

Repository Public

AccountAPI.swift 21.7 KB 413 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Core/Account/AccountAPI.swift10// Description      : client de l'API de compte (`/api/v3/compte…`, contrat dans11//                    docs/COMPTES-API.md). Générique : une seule fonction12//                    d'envoi (méthode, chemin, corps JSON, réponse décodée),13//                    en-tête `X-LouKa-Client: ios`, jeton `Authorization:14//                    Bearer`, erreurs structurées. Aucun cache : les réponses15//                    de compte sont `no-store`. Le jeton n'est jamais16//                    journalisé.17// Module           : LouKa18// Repository       : https://git.spboucher.ai/lou-ka-ios-v319// Project Website  : https://www.lou-ka.com20// Created          : 2026-11-3021// Last Modified    : 2026-11-3022//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation9697/// Erreur de l'API de compte.98enum AccountError: Error, LocalizedError, Sendable, Equatable {99    /// `{"error": {"code", "message", "param"}}` ; `retryAfter` en secondes pour un 429.100    case api(status: Int, code: String, message: String, param: String?, retryAfter: Int?)101    /// Le serveur ne connaît pas les routes de compte (404 ou 405 sans erreur de compte).102    case unavailable103    case http(Int)104105    /// L'objet demandé n'existe pas ou plus (404 du serveur).106    var isNotFound: Bool { if case .api(let s, _, _, _, _) = self { return s == 404 }; return false }107    case offline108    case decoding109110    var errorDescription: String? {111        switch self {112        case .api(let status, _, let message, _, let retry):113            if status == 429, let retry, retry > 0, !message.contains("\(retry)") {114                return "\(message) Délai d'attente : \(AccountError.delay(retry))."115            }116            return message117        case .unavailable: return "Les comptes ne sont pas offerts pour le moment. Réessayez plus tard."118        case .http(let s): return "Le serveur a répondu \(s). Réessayez dans un instant."119        case .offline: return "Connexion impossible. Vérifiez votre accès à Internet."120        case .decoding: return "Réponse illisible. Réessayez dans un instant."121        }122    }123124    var code: String? { if case .api(_, let c, _, _, _) = self { return c }; return nil }125    var param: String? { if case .api(_, _, _, let p, _) = self { return p }; return nil }126    var retryAfter: Int? { if case .api(_, _, _, _, let r) = self { return r }; return nil }127    var isOffline: Bool { self == .offline }128    /// Session absente ou expirée : l'app repasse à l'état déconnecté.129    var isUnauthenticated: Bool { code == "non_authentifie" }130131    /// « 45 s », « 2 min ».132    static func delay(_ seconds: Int) -> String {133        seconds < 90 ? "\(seconds) s" : "\(Int((Double(seconds) / 60).rounded(.up))) min"134    }135136    static func from(status: Int, data: Data, retryAfter: String?) -> AccountError {137        struct Envelope: Decodable {138            struct Body: Decodable { var code: String?; var message: String?; var param: String? }139            var error: Body140        }141        let body = (try? JSONDecoder().decode(Envelope.self, from: data))?.error142        let retry = retryAfter.flatMap { Int($0.trimmingCharacters(in: .whitespaces)) }143        if let code = body?.code {144            // serveur sans la route (la production avant sa mise à niveau) ; un 404 `not_found` en JSON est une145            // vraie réponse (conversation effacée, gestionnaire inconnu) et garde le message du serveur146            if status == 405, code == "method_not_allowed" { return .unavailable }147            return .api(status: status, code: code, message: body?.message ?? "Le serveur a répondu \(status).", param: body?.param, retryAfter: retry)148        }149        if status == 429 {150            return .api(status: 429, code: "trop_de_tentatives", message: "Trop de tentatives.", param: nil, retryAfter: retry)151        }152        if status == 404 || status == 405 { return .unavailable }153        return .http(status)154    }155}156157/// Réponse sans corps (204).158struct NoContent: Decodable, Sendable { init() {}; init(from decoder: Decoder) throws {} }159160/// Client HTTP des routes de compte. Sans état propre : la base et le jeton sont fournis par l'appelant,161/// si bien que la même couche servira aux prochaines routes (messagerie, rôles).162struct AccountAPI: Sendable {163    static let clientName = "ios"164    static let root = "api/v3/compte"165    /// Délai `Retry-After` le plus long (secondes) après lequel une requête est rejouée d'elle-même.166    static let maxAutoRetryDelay = 5167168    var session: URLSession169    /// Adresse de base du serveur (production par défaut ; `-LKBaseURL` pour la préproduction).170    var base: @Sendable () async -> URL171    /// Jeton de session courant, s'il y en a un.172    var token: @Sendable () -> String?173174    static let defaultSession: URLSession = {175        let cfg = URLSessionConfiguration.ephemeral176        cfg.timeoutIntervalForRequest = 20177        cfg.timeoutIntervalForResource = 45178        cfg.waitsForConnectivity = false179        cfg.requestCachePolicy = .reloadIgnoringLocalCacheData180        cfg.urlCache = nil181        cfg.httpCookieStorage = nil182        cfg.httpShouldSetCookies = false183        cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]184        return URLSession(configuration: cfg)185    }()186187    /// Chemin d'un identifiant écrit « tel quel » : « : » et « / » restent lisibles, seuls les caractères188    /// interdits dans un chemin (espace, « ? », « # », « % »…) sont encodés.189    static func pathComponent(_ id: String) -> String {190        // `urlPathAllowed` exclut « : » ; il est pourtant permis dans un segment qui n'est pas le premier191        id.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed.union(CharacterSet(charactersIn: ":"))) ?? id192    }193194    /// Adresse absolue d'une route ; `path` est déjà encodé. Relatif à `/api/v3/compte`, ou à `/api/v3` s'il195    /// commence par « / » (messagerie, gestionnaires).196    static func url(base: URL, path: String) -> URL? {197        var s = base.absoluteString198        while s.hasSuffix("/") { s.removeLast() }199        if path.hasPrefix("/") { return URL(string: s + "/api/v3" + path) }200        return URL(string: s + "/" + root + (path.isEmpty ? "" : "/" + path))201    }202203    func request(_ method: String, _ path: String, body: Data? = nil, authorized: Bool = true) async throws -> URLRequest {204        guard let u = AccountAPI.url(base: await base(), path: path) else { throw AccountError.http(0) }205        var req = URLRequest(url: u)206        req.httpMethod = method207        req.setValue(AccountAPI.clientName, forHTTPHeaderField: "X-LouKa-Client")208        req.setValue("application/json", forHTTPHeaderField: "Accept")209        if let body {210            req.httpBody = body211            req.setValue("application/json", forHTTPHeaderField: "Content-Type")212        } else if method != "GET" {213            // le serveur exige un corps JSON sur toute écriture214            req.httpBody = Data("{}".utf8)215            req.setValue("application/json", forHTTPHeaderField: "Content-Type")216        }217        if authorized, let t = token() { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }218        return req219    }220221    /// Envoie une requête et décode la réponse. `T` = `NoContent` pour un 204.222    func send<T: Decodable & Sendable>(_ method: String, _ path: String, body: (any Encodable & Sendable)? = nil,223                                       authorized: Bool = true, as type: T.Type = T.self) async throws -> T {224        let data = try body.map { try JSONEncoder().encode($0) }225        let req = try await request(method, path, body: data, authorized: authorized)226        var d = Data(), attempt = 0227        while true {228            let resp: URLResponse229            do {230                (d, resp) = try await session.data(for: req)231            } catch is CancellationError {232                throw CancellationError()233            } catch let e as URLError where e.code == .cancelled {234                throw CancellationError()235            } catch {236                throw AccountError.offline237            }238            let http = resp as? HTTPURLResponse239            let status = http?.statusCode ?? 0240            if (200..<300).contains(status) { break }241            let error = AccountError.from(status: status, data: d, retryAfter: http?.value(forHTTPHeaderField: "Retry-After"))242            // limiteur général de l'API (`rate_limited`, quelques secondes) : on attend et on rejoue, deux fois243            // au plus. `trop_de_tentatives` (protection des comptes) n'est jamais rejoué : il est montré.244            if error.code == "rate_limited", let wait = error.retryAfter, wait <= AccountAPI.maxAutoRetryDelay, attempt < 2 {245                attempt += 1246                try await Task.sleep(for: .seconds(Double(max(wait, 1)) + 0.2))247                continue248            }249            throw error250        }251        if T.self == NoContent.self { return NoContent() as! T }252        do { return try JSONDecoder().decode(T.self, from: d) } catch { throw AccountError.decoding }253    }254255    // MARK: Inscription, vérification, connexion256257    /// Corps des routes d'identité : `email` ou `phone` selon l'identifiant, jamais les deux.258    private struct Credentials: Encodable, Sendable {259        var email: String?; var phone: String?; var password: String?; var name: String?; var code: String?260        init(_ id: AccountIdentifier, password: String? = nil, name: String? = nil, code: String? = nil) {261            switch id {262            case .email: email = id.value263            case .phone: phone = id.value264            }265            self.password = password; self.name = name; self.code = code266        }267    }268269    /// Ce que le serveur offre à l'inscription (courriel, cellulaire). Public, sans session.270    func options() async throws -> AccountOptions { try await send("GET", "options", authorized: false) }271272    func signUp(_ id: AccountIdentifier, password: String, name: String?) async throws -> AccountAccepted {273        try await send("POST", "inscription", body: Credentials(id, password: password, name: name?.isEmpty == false ? name : nil), authorized: false)274    }275    func verify(_ id: AccountIdentifier, code: String) async throws -> AccountSession {276        try await send("POST", "verification", body: Credentials(id, code: code), authorized: false)277    }278    @discardableResult279    func resendVerification(_ id: AccountIdentifier) async throws -> AccountAccepted {280        try await send("POST", "verification/renvoi", body: Credentials(id), authorized: false)281    }282    func signIn(_ id: AccountIdentifier, password: String) async throws -> AccountSession {283        try await send("POST", "connexion", body: Credentials(id, password: password), authorized: false)284    }285    @discardableResult286    func forgotPassword(_ id: AccountIdentifier) async throws -> AccountAccepted {287        try await send("POST", "mot-de-passe/oubli", body: Credentials(id), authorized: false)288    }289    func resetPassword(_ id: AccountIdentifier, code: String, password: String) async throws -> AccountSession {290        try await send("POST", "mot-de-passe/reinitialisation", body: Credentials(id, password: password, code: code), authorized: false)291    }292293    // formes par courriel, gardées pour les appelants existants294    func signUp(email: String, password: String, name: String?) async throws -> AccountAccepted { try await signUp(.email(email), password: password, name: name) }295    func verify(email: String, code: String) async throws -> AccountSession { try await verify(.email(email), code: code) }296    func resendVerification(email: String) async throws { try await resendVerification(.email(email)) }297    func signIn(email: String, password: String) async throws -> AccountSession { try await signIn(.email(email), password: password) }298    func signOut() async throws { let _: NoContent = try await send("POST", "deconnexion") }299    func forgotPassword(email: String) async throws { try await forgotPassword(.email(email)) }300    func resetPassword(email: String, code: String, password: String) async throws -> AccountSession { try await resetPassword(.email(email), code: code, password: password) }301302    // MARK: Compte303304    func me() async throws -> AccountSession { try await send("GET", "") }305    func rename(_ name: String) async throws -> AccountUser {306        try await send("PATCH", "", body: ["name": name], as: AccountUserEnvelope.self).user307    }308    func changePassword(current: String, new: String) async throws {309        let _: NoContent = try await send("POST", "mot-de-passe", body: ["current_password": current, "new_password": new])310    }311    func sessions() async throws -> [DeviceSession] { try await send("GET", "sessions", as: DeviceSessionList.self).items }312    func revokeSession(_ id: String) async throws {313        let _: NoContent = try await send("DELETE", "sessions/\(AccountAPI.pathComponent(id))")314    }315    func signOutEverywhereElse() async throws -> Int {316        try await send("POST", "deconnexion-partout", as: RevokedCount.self).revoked ?? 0317    }318    func deleteAccount(password: String) async throws {319        let _: NoContent = try await send("POST", "suppression", body: ["password": password])320    }321322    // MARK: Gestionnaires (public, sans session)323324    /// Ce que la fiche d'un logement montre de son gestionnaire ; nil si le serveur ne connaît pas la route.325    func listingManager(uid: String) async throws -> ListingManagerInfo {326        try await send("GET", "/gestionnaires/annonce/\(AccountAPI.pathComponent(uid))", authorized: false)327    }328    /// Fiche publique d'un gestionnaire ; `countView` : une vue comptée (une fois par ouverture de la page).329    func managerFiche(sourceID: String, countView: Bool) async throws -> ManagerFiche {330        try await send("GET", "/gestionnaires/\(AccountAPI.pathComponent(sourceID))/fiche" + (countView ? "?vue=1" : ""), authorized: false)331    }332333    // MARK: Messagerie (session requise)334335    private struct OpenBody: Encodable, Sendable {336        var uid: String?; var sourceID: String?; var text: String; var listing: FavoriteSnapshot?337        enum CodingKeys: String, CodingKey { case uid, text, listing; case sourceID = "source_id" }338    }339    private struct PatchBody: Encodable, Sendable { var archived: Bool?; var status: String? }340    private struct ReportBody: Encodable, Sendable {341        var reason: String; var messageID: Int64?342        enum CodingKeys: String, CodingKey { case reason; case messageID = "message_id" }343    }344345    func conversations(archived: Bool = false) async throws -> ConversationList {346        try await send("GET", "/messagerie" + (archived ? "?archives=1" : ""))347    }348    func unreadCount() async throws -> Int { try await send("GET", "/messagerie/non-lus", as: UnreadCount.self).unread }349    /// Ouvre une conversation à propos d'un logement (`uid`, avec son aperçu) ou avec une entreprise (`sourceID`).350    func openConversation(uid: String?, sourceID: String?, text: String, listing: FavoriteSnapshot?) async throws -> ConversationThread {351        try await send("POST", "/messagerie", body: OpenBody(uid: uid, sourceID: uid == nil ? sourceID : nil, text: text, listing: uid == nil ? nil : listing))352    }353    /// Le fil ; `after` : seulement les messages plus récents que cet identifiant (relève). Marque comme lu.354    func thread(_ id: String, after: Int64? = nil) async throws -> ConversationThread {355        try await send("GET", "/messagerie/\(AccountAPI.pathComponent(id))" + (after.map { "?apres=\($0)" } ?? ""))356    }357    func reply(_ id: String, text: String) async throws -> ChatMessage {358        try await send("POST", "/messagerie/\(AccountAPI.pathComponent(id))/messages", body: ["text": text], as: MessageEnvelope.self).message359    }360    func setArchived(_ id: String, _ archived: Bool) async throws -> Conversation {361        try await send("PATCH", "/messagerie/\(AccountAPI.pathComponent(id))", body: PatchBody(archived: archived), as: ConversationEnvelope.self).conversation362    }363    func closeConversation(_ id: String) async throws -> Conversation {364        try await send("PATCH", "/messagerie/\(AccountAPI.pathComponent(id))", body: PatchBody(status: "fermee"), as: ConversationEnvelope.self).conversation365    }366    func deleteConversation(_ id: String) async throws {367        let _: NoContent = try await send("DELETE", "/messagerie/\(AccountAPI.pathComponent(id))")368    }369    func report(_ id: String, reason: String, messageID: Int64? = nil) async throws {370        let _: NoContent = try await send("POST", "/messagerie/\(AccountAPI.pathComponent(id))/signalement", body: ReportBody(reason: reason, messageID: messageID))371    }372373    // MARK: Favoris374375    private struct FavoriteBody: Encodable, Sendable {376        var savedAt: Int64; var note: String; var snapshot: FavoriteSnapshot377        enum CodingKeys: String, CodingKey { case note, snapshot; case savedAt = "saved_at" }378    }379380    func favorites() async throws -> FavoriteList { try await send("GET", "favoris") }381    @discardableResult382    func putFavorite(_ f: RemoteFavorite) async throws -> RemoteFavorite {383        try await send("PUT", "favoris/\(AccountAPI.pathComponent(f.uid))",384                       body: FavoriteBody(savedAt: f.savedAt, note: f.note ?? "", snapshot: f.snapshot ?? FavoriteSnapshot()))385    }386    func deleteFavorite(_ uid: String) async throws {387        let _: NoContent = try await send("DELETE", "favoris/\(AccountAPI.pathComponent(uid))")388    }389    func syncFavorites(items: [RemoteFavorite], removed: [RemovedFavorite]) async throws -> FavoriteList {390        try await send("POST", "favoris/synchronisation", body: FavoriteSyncRequest(items: items, removed: removed))391    }392393    // MARK: Recherches enregistrées394395    private struct SearchBody: Encodable, Sendable {396        var label: String; var query: String; var origin: String; var savedAt: Int64; var lastTotal: Int?397        enum CodingKeys: String, CodingKey { case label, query, origin; case savedAt = "saved_at"; case lastTotal = "last_total" }398    }399400    func searches() async throws -> SearchList { try await send("GET", "recherches") }401    @discardableResult402    func putSearch(_ s: RemoteSearch) async throws -> RemoteSearch {403        try await send("PUT", "recherches/\(AccountAPI.pathComponent(s.id))",404                       body: SearchBody(label: s.label, query: s.query, origin: s.origin, savedAt: s.savedAt, lastTotal: s.lastTotal))405    }406    func deleteSearch(_ id: String) async throws {407        let _: NoContent = try await send("DELETE", "recherches/\(AccountAPI.pathComponent(id))")408    }409    func syncSearches(items: [RemoteSearch], removed: [RemovedSearch]) async throws -> SearchList {410        try await send("POST", "recherches/synchronisation", body: SearchSyncRequest(items: items, removed: removed))411    }412}413
Files main
Menu

Theme