Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/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-ImmoKa-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 : ImmoKa18// Repository : https://git.spboucher.ai/immo-ka-ios-v319// Project Website : https://www.immo-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, courtier inconnu) et garde le message du serveur146 if status == 405, code == "method_not_allowed" { return .unavailable }147 if status == 404, code == "not_found", body?.message == "Route inconnue" { return .unavailable }148 return .api(status: status, code: code, message: body?.message ?? "Le serveur a répondu \(status).", param: body?.param, retryAfter: retry)149 }150 if status == 429 {151 return .api(status: 429, code: "trop_de_tentatives", message: "Trop de tentatives.", param: nil, retryAfter: retry)152 }153 if status == 404 || status == 405 { return .unavailable }154 return .http(status)155 }156}157158/// Réponse sans corps (204).159struct NoContent: Decodable, Sendable { init() {}; init(from decoder: Decoder) throws {} }160161/// Client HTTP des routes de compte. Sans état propre : la base et le jeton sont fournis par l'appelant,162/// si bien que la même couche servira aux prochaines routes (messagerie, rôles).163struct AccountAPI: Sendable {164 static let clientName = "ios"165 static let root = "api/v3/compte"166 /// Délai `Retry-After` le plus long (secondes) après lequel une requête est rejouée d'elle-même.167 static let maxAutoRetryDelay = 5168169 var session: URLSession170 /// Adresse de base du serveur (production par défaut ; `-IKBaseURL` pour la préproduction).171 var base: @Sendable () async -> URL172 /// Jeton de session courant, s'il y en a un.173 var token: @Sendable () -> String?174175 static let defaultSession: URLSession = {176 let cfg = URLSessionConfiguration.ephemeral177 cfg.timeoutIntervalForRequest = 20178 cfg.timeoutIntervalForResource = 45179 cfg.waitsForConnectivity = false180 cfg.requestCachePolicy = .reloadIgnoringLocalCacheData181 cfg.urlCache = nil182 cfg.httpCookieStorage = nil183 cfg.httpShouldSetCookies = false184 cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]185 return URLSession(configuration: cfg)186 }()187188 /// Chemin d'un identifiant écrit « tel quel » : « : » et « / » restent lisibles, seuls les caractères189 /// interdits dans un chemin (espace, « ? », « # », « % »…) sont encodés.190 static func pathComponent(_ id: String) -> String {191 // `urlPathAllowed` exclut « : » ; il est pourtant permis dans un segment qui n'est pas le premier192 id.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed.union(CharacterSet(charactersIn: ":"))) ?? id193 }194195 /// Adresse absolue d'une route ; `path` est déjà encodé. Relatif à `/api/v3/compte`, ou à `/api/v3` s'il196 /// commence par « / » (messagerie, courtiers).197 static func url(base: URL, path: String) -> URL? {198 var s = base.absoluteString199 while s.hasSuffix("/") { s.removeLast() }200 if path.hasPrefix("/") { return URL(string: s + "/api/v3" + path) }201 return URL(string: s + "/" + root + (path.isEmpty ? "" : "/" + path))202 }203204 func request(_ method: String, _ path: String, body: Data? = nil, authorized: Bool = true) async throws -> URLRequest {205 guard let u = AccountAPI.url(base: await base(), path: path) else { throw AccountError.http(0) }206 var req = URLRequest(url: u)207 req.httpMethod = method208 req.setValue(AccountAPI.clientName, forHTTPHeaderField: "X-ImmoKa-Client")209 req.setValue("application/json", forHTTPHeaderField: "Accept")210 if let body {211 req.httpBody = body212 req.setValue("application/json", forHTTPHeaderField: "Content-Type")213 } else if method != "GET" {214 // le serveur exige un corps JSON sur toute écriture215 req.httpBody = Data("{}".utf8)216 req.setValue("application/json", forHTTPHeaderField: "Content-Type")217 }218 if authorized, let t = token() { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }219 return req220 }221222 /// Envoie une requête et décode la réponse. `T` = `NoContent` pour un 204.223 func send<T: Decodable & Sendable>(_ method: String, _ path: String, body: (any Encodable & Sendable)? = nil,224 authorized: Bool = true, as type: T.Type = T.self) async throws -> T {225 let data = try body.map { try JSONEncoder().encode($0) }226 let req = try await request(method, path, body: data, authorized: authorized)227 var d = Data(), attempt = 0228 while true {229 let resp: URLResponse230 do {231 (d, resp) = try await session.data(for: req)232 } catch is CancellationError {233 throw CancellationError()234 } catch let e as URLError where e.code == .cancelled {235 throw CancellationError()236 } catch {237 throw AccountError.offline238 }239 let http = resp as? HTTPURLResponse240 let status = http?.statusCode ?? 0241 if (200..<300).contains(status) { break }242 let error = AccountError.from(status: status, data: d, retryAfter: http?.value(forHTTPHeaderField: "Retry-After"))243 // limiteur général de l'API (`rate_limited`, quelques secondes) : on attend et on rejoue, deux fois244 // au plus. `trop_de_tentatives` (protection des comptes) n'est jamais rejoué : il est montré.245 if error.code == "rate_limited", let wait = error.retryAfter, wait <= AccountAPI.maxAutoRetryDelay, attempt < 2 {246 attempt += 1247 try await Task.sleep(for: .seconds(Double(max(wait, 1)) + 0.2))248 continue249 }250 throw error251 }252 if T.self == NoContent.self { return NoContent() as! T }253 do { return try JSONDecoder().decode(T.self, from: d) } catch { throw AccountError.decoding }254 }255256 // MARK: Inscription, vérification, connexion257258 /// Corps des routes d'identité : `email` ou `phone` selon l'identifiant, jamais les deux.259 private struct Credentials: Encodable, Sendable {260 var email: String?; var phone: String?; var password: String?; var name: String?; var code: String?261 init(_ id: AccountIdentifier, password: String? = nil, name: String? = nil, code: String? = nil) {262 switch id {263 case .email: email = id.value264 case .phone: phone = id.value265 }266 self.password = password; self.name = name; self.code = code267 }268 }269270 /// Ce que le serveur offre à l'inscription (courriel, cellulaire). Public, sans session.271 func options() async throws -> AccountOptions { try await send("GET", "options", authorized: false) }272273 func signUp(_ id: AccountIdentifier, password: String, name: String?) async throws -> AccountAccepted {274 try await send("POST", "inscription", body: Credentials(id, password: password, name: name?.isEmpty == false ? name : nil), authorized: false)275 }276 func verify(_ id: AccountIdentifier, code: String) async throws -> AccountSession {277 try await send("POST", "verification", body: Credentials(id, code: code), authorized: false)278 }279 @discardableResult280 func resendVerification(_ id: AccountIdentifier) async throws -> AccountAccepted {281 try await send("POST", "verification/renvoi", body: Credentials(id), authorized: false)282 }283 func signIn(_ id: AccountIdentifier, password: String) async throws -> AccountSession {284 try await send("POST", "connexion", body: Credentials(id, password: password), authorized: false)285 }286 @discardableResult287 func forgotPassword(_ id: AccountIdentifier) async throws -> AccountAccepted {288 try await send("POST", "mot-de-passe/oubli", body: Credentials(id), authorized: false)289 }290 func resetPassword(_ id: AccountIdentifier, code: String, password: String) async throws -> AccountSession {291 try await send("POST", "mot-de-passe/reinitialisation", body: Credentials(id, password: password, code: code), authorized: false)292 }293294 // formes par courriel, gardées pour les appelants existants295 func signUp(email: String, password: String, name: String?) async throws -> AccountAccepted { try await signUp(.email(email), password: password, name: name) }296 func verify(email: String, code: String) async throws -> AccountSession { try await verify(.email(email), code: code) }297 func resendVerification(email: String) async throws { try await resendVerification(.email(email)) }298 func signIn(email: String, password: String) async throws -> AccountSession { try await signIn(.email(email), password: password) }299 func signOut() async throws { let _: NoContent = try await send("POST", "deconnexion") }300 func forgotPassword(email: String) async throws { try await forgotPassword(.email(email)) }301 func resetPassword(email: String, code: String, password: String) async throws -> AccountSession { try await resetPassword(.email(email), code: code, password: password) }302303 // MARK: Compte304305 func me() async throws -> AccountSession { try await send("GET", "") }306 func rename(_ name: String) async throws -> AccountUser {307 try await send("PATCH", "", body: ["name": name], as: AccountUserEnvelope.self).user308 }309 func changePassword(current: String, new: String) async throws {310 let _: NoContent = try await send("POST", "mot-de-passe", body: ["current_password": current, "new_password": new])311 }312 func sessions() async throws -> [DeviceSession] { try await send("GET", "sessions", as: DeviceSessionList.self).items }313 func revokeSession(_ id: String) async throws {314 let _: NoContent = try await send("DELETE", "sessions/\(AccountAPI.pathComponent(id))")315 }316 func signOutEverywhereElse() async throws -> Int {317 try await send("POST", "deconnexion-partout", as: RevokedCount.self).revoked ?? 0318 }319 func deleteAccount(password: String) async throws {320 let _: NoContent = try await send("POST", "suppression", body: ["password": password])321 }322323 // MARK: Courtiers (public, sans session)324325 /// Ce que la fiche d'une propriété montre de son courtier ; nil si le serveur ne connaît pas la route.326 func listingBroker(uid: String) async throws -> ListingBrokerInfo {327 try await send("GET", "/courtiers/annonce/\(AccountAPI.pathComponent(uid))", authorized: false)328 }329 /// Fiche publique d'un courtier ; `countView` : une vue comptée (une fois par ouverture de la page).330 func brokerFiche(brokerID: String, countView: Bool) async throws -> BrokerFiche {331 try await send("GET", "/courtiers/\(AccountAPI.pathComponent(brokerID))/fiche" + (countView ? "?vue=1" : ""), authorized: false)332 }333334 // MARK: Messagerie (session requise)335336 private struct OpenBody: Encodable, Sendable {337 var uid: String?; var brokerID: String?; var text: String; var listing: FavoriteSnapshot?338 enum CodingKeys: String, CodingKey { case uid, text, listing; case brokerID = "broker_id" }339 }340 private struct PatchBody: Encodable, Sendable { var archived: Bool?; var status: String? }341 private struct ReportBody: Encodable, Sendable {342 var reason: String; var messageID: Int64?343 enum CodingKeys: String, CodingKey { case reason; case messageID = "message_id" }344 }345346 func conversations(archived: Bool = false) async throws -> ConversationList {347 try await send("GET", "/messagerie" + (archived ? "?archives=1" : ""))348 }349 func unreadCount() async throws -> Int { try await send("GET", "/messagerie/non-lus", as: UnreadCount.self).unread }350 /// Ouvre une conversation à propos d'une propriété (`uid`, avec son aperçu) ou avec un courtier (`brokerID`).351 func openConversation(uid: String?, brokerID: String?, text: String, listing: FavoriteSnapshot?) async throws -> ConversationThread {352 try await send("POST", "/messagerie", body: OpenBody(uid: uid, brokerID: uid == nil ? brokerID : nil, text: text, listing: uid == nil ? nil : listing))353 }354 /// Le fil ; `after` : seulement les messages plus récents que cet identifiant (relève). Marque comme lu.355 func thread(_ id: String, after: Int64? = nil) async throws -> ConversationThread {356 try await send("GET", "/messagerie/\(AccountAPI.pathComponent(id))" + (after.map { "?apres=\($0)" } ?? ""))357 }358 func reply(_ id: String, text: String) async throws -> ChatMessage {359 try await send("POST", "/messagerie/\(AccountAPI.pathComponent(id))/messages", body: ["text": text], as: MessageEnvelope.self).message360 }361 func setArchived(_ id: String, _ archived: Bool) async throws -> Conversation {362 try await send("PATCH", "/messagerie/\(AccountAPI.pathComponent(id))", body: PatchBody(archived: archived), as: ConversationEnvelope.self).conversation363 }364 func closeConversation(_ id: String) async throws -> Conversation {365 try await send("PATCH", "/messagerie/\(AccountAPI.pathComponent(id))", body: PatchBody(status: "fermee"), as: ConversationEnvelope.self).conversation366 }367 func deleteConversation(_ id: String) async throws {368 let _: NoContent = try await send("DELETE", "/messagerie/\(AccountAPI.pathComponent(id))")369 }370 func report(_ id: String, reason: String, messageID: Int64? = nil) async throws {371 let _: NoContent = try await send("POST", "/messagerie/\(AccountAPI.pathComponent(id))/signalement", body: ReportBody(reason: reason, messageID: messageID))372 }373374 // MARK: Favoris375376 private struct FavoriteBody: Encodable, Sendable {377 var savedAt: Int64; var note: String; var snapshot: FavoriteSnapshot378 enum CodingKeys: String, CodingKey { case note, snapshot; case savedAt = "saved_at" }379 }380381 func favorites() async throws -> FavoriteList { try await send("GET", "favoris") }382 @discardableResult383 func putFavorite(_ f: RemoteFavorite) async throws -> RemoteFavorite {384 try await send("PUT", "favoris/\(AccountAPI.pathComponent(f.uid))",385 body: FavoriteBody(savedAt: f.savedAt, note: f.note ?? "", snapshot: f.snapshot ?? FavoriteSnapshot()))386 }387 func deleteFavorite(_ uid: String) async throws {388 let _: NoContent = try await send("DELETE", "favoris/\(AccountAPI.pathComponent(uid))")389 }390 func syncFavorites(items: [RemoteFavorite], removed: [RemovedFavorite]) async throws -> FavoriteList {391 try await send("POST", "favoris/synchronisation", body: FavoriteSyncRequest(items: items, removed: removed))392 }393394 // MARK: Recherches enregistrées395396 private struct SearchBody: Encodable, Sendable {397 var label: String; var query: String; var origin: String; var savedAt: Int64; var lastTotal: Int?398 enum CodingKeys: String, CodingKey { case label, query, origin; case savedAt = "saved_at"; case lastTotal = "last_total" }399 }400401 func searches() async throws -> SearchList { try await send("GET", "recherches") }402 @discardableResult403 func putSearch(_ s: RemoteSearch) async throws -> RemoteSearch {404 try await send("PUT", "recherches/\(AccountAPI.pathComponent(s.id))",405 body: SearchBody(label: s.label, query: s.query, origin: s.origin, savedAt: s.savedAt, lastTotal: s.lastTotal))406 }407 func deleteSearch(_ id: String) async throws {408 let _: NoContent = try await send("DELETE", "recherches/\(AccountAPI.pathComponent(id))")409 }410 func syncSearches(items: [RemoteSearch], removed: [RemovedSearch]) async throws -> SearchList {411 try await send("POST", "recherches/synchronisation", body: SearchSyncRequest(items: items, removed: removed))412 }413}414