Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka Admin iOS9// File : LouKaAdmin/Core/AdminAPI.swift10// Description : client de l'API d'administration (`/api/v3/admin`).11// En-tête `X-LouKa-Client: ios-admin`, jeton de session par12// `Authorization: Bearer`, erreurs structurées13// (`error.message` est affiché tel quel). Session14// `URLSession` éphémère : ni cache, ni témoins. Le jeton15// n'est jamais journalisé.16// Module : LouKaAdmin17// Repository : https://git.spboucher.ai/lou-ka-admin-ios18// Project Website : https://www.lou-ka.com19// Created : 2026-11-3020// Last Modified : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation9596enum AdminError: Error, LocalizedError, Sendable, Equatable {97 case api(status: Int, code: String, message: String, param: String?)98 case offline99 case decoding100101 var errorDescription: String? {102 switch self {103 case .api(_, _, let message, _): message104 case .offline: "Connexion impossible. Vérifiez le réseau, puis réessayez."105 case .decoding: "Réponse illisible. Réessayez dans un instant."106 }107 }108109 var code: String? { if case .api(_, let c, _, _) = self { return c }; return nil }110 var status: Int? { if case .api(let s, _, _, _) = self { return s }; return nil }111 /// Session absente ou expirée : retour à l'écran de connexion.112 var isUnauthenticated: Bool { if case .api(401, "non_authentifie", _, _) = self { return true }; return false }113114 /// Phrase de repli quand le serveur ne fournit pas de message.115 static func fallback(_ status: Int) -> String {116 switch status {117 case 401: "Votre session est terminée. Reconnectez-vous."118 case 403: "Cette action vous est refusée."119 case 404: "Élément introuvable."120 case 429: "Trop de tentatives. Patientez un moment, puis réessayez."121 case 500...: "Le serveur a rencontré une erreur. Réessayez dans un instant."122 default: "La demande n'a pas pu être traitée."123 }124 }125126 static func from(status: Int, data: Data) -> AdminError {127 struct Envelope: Decodable {128 struct Body: Decodable { var code: String?; var message: String?; var param: String? }129 var error: Body130 }131 let body = (try? JSONDecoder().decode(Envelope.self, from: data))?.error132 let message = body?.message.flatMap { $0.isEmpty ? nil : $0 } ?? fallback(status)133 return .api(status: status, code: body?.code ?? "http_\(status)", message: message, param: body?.param)134 }135136 /// Message à afficher pour une erreur quelconque.137 static func message(_ error: Error) -> String {138 (error as? AdminError)?.errorDescription ?? (error as? LocalizedError)?.errorDescription ?? "Une erreur inattendue est survenue. Réessayez."139 }140}141142struct Empty: Decodable, Sendable { init() {}; init(from decoder: Decoder) throws {} }143144/// Pièce jointe téléchargée, écrite dans un fichier temporaire pour la feuille de partage.145struct DownloadedFile: Sendable, Equatable { var url: URL; var bytes: Int }146147struct AdminAPI: Sendable {148 static let clientName = "ios-admin"149150 var session: URLSession151 var base: @Sendable () -> URL152 var token: @Sendable () -> String?153154 static let defaultSession: URLSession = {155 let cfg = URLSessionConfiguration.ephemeral156 cfg.timeoutIntervalForRequest = 25157 cfg.timeoutIntervalForResource = 90158 cfg.requestCachePolicy = .reloadIgnoringLocalCacheData159 cfg.urlCache = nil160 cfg.httpCookieStorage = nil161 cfg.httpShouldSetCookies = false162 cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]163 return URLSession(configuration: cfg)164 }()165166 /// Segment de chemin : tout ce qui n'est pas lettre, chiffre ou « -._~ » est encodé (comme `encodeURIComponent`).167 static func component(_ s: String) -> String {168 s.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")) ?? s169 }170171 /// Chaîne de requête sans les valeurs vides, clés triées.172 static func query(_ params: [String: String?]) -> String {173 let items = params.compactMap { k, v -> String? in174 guard let v, !v.isEmpty else { return nil }175 return "\(component(k))=\(component(v))"176 }.sorted()177 return items.isEmpty ? "" : "?" + items.joined(separator: "&")178 }179180 /// `path` relatif à `/api/v3/admin` ; un chemin qui commence par « / » est relatif à `/api/v3`.181 func url(_ path: String) -> URL? {182 var s = base().absoluteString183 while s.hasSuffix("/") { s.removeLast() }184 if path.hasPrefix("/") { return URL(string: s + "/api/v3" + path) }185 return URL(string: s + "/api/v3/admin" + (path.isEmpty || path.hasPrefix("?") ? path : "/" + path))186 }187188 func request(_ method: String, _ path: String, body: Data? = nil, authorized: Bool = true) throws -> URLRequest {189 guard let u = url(path) else { throw AdminError.decoding }190 var req = URLRequest(url: u)191 req.httpMethod = method192 req.setValue(AdminAPI.clientName, forHTTPHeaderField: "X-LouKa-Client")193 if method != "GET" && method != "DELETE" {194 req.httpBody = body ?? Data("{}".utf8)195 req.setValue("application/json", forHTTPHeaderField: "Content-Type")196 }197 if authorized, let t = token() { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }198 return req199 }200201 private func perform(_ req: URLRequest) async throws -> (Data, HTTPURLResponse) {202 do {203 let (d, resp) = try await session.data(for: req)204 guard let http = resp as? HTTPURLResponse else { throw AdminError.decoding }205 guard (200..<300).contains(http.statusCode) else { throw AdminError.from(status: http.statusCode, data: d) }206 return (d, http)207 } catch let e as AdminError {208 throw e209 } catch is CancellationError {210 throw CancellationError()211 } catch let e as URLError where e.code == .cancelled {212 throw CancellationError()213 } catch {214 throw AdminError.offline215 }216 }217218 func send<T: Decodable & Sendable>(_ method: String, _ path: String, body: (any Encodable & Sendable)? = nil, authorized: Bool = true, as type: T.Type = T.self) async throws -> T {219 let data = try body.map { try JSONEncoder().encode($0) }220 let (d, http) = try await perform(try request(method, path, body: data, authorized: authorized))221 if T.self == Empty.self || http.statusCode == 204 || d.isEmpty {222 if let e = Empty() as? T { return e }223 throw AdminError.decoding224 }225 do { return try JSONDecoder().decode(T.self, from: d) } catch { throw AdminError.decoding }226 }227228 // MARK: Session229230 private struct TokenBody: Encodable, Sendable { var token: String }231 private struct LoginVerify: Encodable, Sendable {232 var challengeID: String; var credential: JSONValue233 enum CodingKeys: String, CodingKey { case credential; case challengeID = "challenge_id" }234 }235 private struct ActivationVerify: Encodable, Sendable {236 var token: String; var challengeID: String; var credential: JSONValue; var keyName: String237 enum CodingKeys: String, CodingKey { case token, credential; case challengeID = "challenge_id"; case keyName = "key_name" }238 }239240 func me() async throws -> Me { try await send("GET", "") }241 func loginOptions() async throws -> PasskeyChallenge { try await send("POST", "connexion/options", authorized: false) }242 func loginVerify(challengeID: String, credential: JSONValue) async throws -> AdminSessionResponse {243 try await send("POST", "connexion/verification", body: LoginVerify(challengeID: challengeID, credential: credential), authorized: false)244 }245 func activationOptions(token: String) async throws -> PasskeyChallenge {246 try await send("POST", "activation/options", body: TokenBody(token: token), authorized: false)247 }248 func activationVerify(token: String, challengeID: String, credential: JSONValue, keyName: String) async throws -> AdminSessionResponse {249 try await send("POST", "activation/verification", body: ActivationVerify(token: token, challengeID: challengeID, credential: credential, keyName: keyName), authorized: false)250 }251 func logout() async throws { let _: Empty = try await send("POST", "deconnexion") }252253 // MARK: Compte254255 func keyInvitation() async throws -> KeyInvitation { try await send("POST", "cles/invitation") }256 func deleteKey(_ id: String) async throws { let _: Empty = try await send("DELETE", "cles/\(AdminAPI.component(id))") }257 func admins() async throws -> [AdminAccount] { try await send("GET", "administrateurs", as: ItemList<AdminAccount>.self).items }258 func journal() async throws -> [JournalEntry] { try await send("GET", "journal", as: ItemList<JournalEntry>.self).items }259260 // MARK: Gestionnaires261262 private struct DecisionBody: Encodable, Sendable {263 var action: String; var reason: String?; var sourceID: String?264 enum CodingKeys: String, CodingKey { case action, reason; case sourceID = "source_id" }265 }266 private struct HideBody: Encodable, Sendable { var hidden: Bool; var reason: String }267268 func managers(_ filter: ManagerFilter) async throws -> [ManagerRequest] {269 try await send("GET", "gestionnaires" + AdminAPI.query(["etat": filter.rawValue]), as: ItemList<ManagerRequest>.self).items270 }271 @discardableResult272 func decide(accountID: String, action: ManagerAction, reason: String? = nil, sourceID: String? = nil) async throws -> DecisionResult {273 let r = reason?.trimmingCharacters(in: .whitespacesAndNewlines)274 return try await send("POST", "gestionnaires/\(AdminAPI.component(accountID))/decision",275 body: DecisionBody(action: action.rawValue, reason: (r ?? "").isEmpty ? nil : r, sourceID: (sourceID ?? "").isEmpty ? nil : sourceID))276 }277 /// Annuaire public des gestionnaires (pour rattacher une demande).278 func searchDirectory(_ q: String) async throws -> [DirectoryManager] {279 try await send("GET", "/gestionnaires/recherche" + AdminAPI.query(["q": q]), authorized: false, as: ItemList<DirectoryManager>.self).items280 }281 func fiche(sourceID: String) async throws -> AdminFiche { try await send("GET", "fiches/\(AdminAPI.component(sourceID))") }282 func hideFiche(sourceID: String, hidden: Bool, reason: String) async throws {283 let _: Empty = try await send("POST", "fiches/\(AdminAPI.component(sourceID))/masquage", body: HideBody(hidden: hidden, reason: reason.trimmingCharacters(in: .whitespacesAndNewlines)))284 }285286 // MARK: Signalements287288 func reports(all: Bool) async throws -> [Report] {289 try await send("GET", "signalements" + AdminAPI.query(["tous": all ? "1" : nil]), as: ItemList<Report>.self).items290 }291 func decideReport(_ id: Int, decision: String) async throws {292 let _: Empty = try await send("POST", "signalements/\(id)/decision", body: ["decision": decision])293 }294295 // MARK: Courrier296297 private struct PatchBody: Encodable, Sendable { var unread: Bool?; var starred: Bool? }298299 func mailboxes() async throws -> [Mailbox] { try await send("GET", "courrier/boites", as: MailboxList.self).mailboxes }300 func messages(address: String, folder: String, text: String? = nil, cursor: String? = nil, limit: Int = 30) async throws -> MailPage {301 try await send("GET", "courrier/messages" + AdminAPI.query(["address": address, "folder": folder, "text": text, "cursor": cursor, "limit": String(limit)]))302 }303 func message(_ id: String) async throws -> MailMessage { try await send("GET", "courrier/messages/\(AdminAPI.component(id))") }304 func patchMessage(_ id: String, unread: Bool? = nil, starred: Bool? = nil) async throws {305 let _: Empty = try await send("PATCH", "courrier/messages/\(AdminAPI.component(id))", body: PatchBody(unread: unread, starred: starred), as: Empty.self)306 }307 func trashMessage(_ id: String) async throws { let _: Empty = try await send("DELETE", "courrier/messages/\(AdminAPI.component(id))") }308 func sendMail(_ draft: MailDraft) async throws { let _: Empty = try await send("POST", "courrier/envoi", body: draft, as: Empty.self) }309310 /// Télécharge une pièce jointe dans un fichier temporaire (jamais ouverte par l'app : remise à la feuille de partage).311 func attachment(messageID: String, attachment: MailAttachment) async throws -> DownloadedFile {312 let req = try request("GET", "courrier/messages/\(AdminAPI.component(messageID))/pieces/\(AdminAPI.component(attachment.id))")313 let (d, _) = try await perform(req)314 let dir = FileManager.default.temporaryDirectory.appending(path: "pieces-\(UUID().uuidString)", directoryHint: .isDirectory)315 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)316 let file = dir.appending(path: MailLogic.fileName(attachment))317 try d.write(to: file, options: [.atomic, .completeFileProtection])318 return DownloadedFile(url: file, bytes: d.count)319 }320}321