Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr SMS Gateway9// File : ios/MacLustrSMS/Core/API.swift10// Description : Client de l'API d'administration de la passerelle (session11// par cookie obtenue avec une clé d'accès), flux temps réel12// SSE.13// Module : ios14// Repository : https://git.spboucher.ai/maclustr-sms15// Project Website : https://sms.spboucher.ai16// Created : 2026-11-3017// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293struct APIError: Error, Equatable, LocalizedError, Sendable {94 let status: Int95 let code: String96 let message: String97 var retryAfter: Int? = nil98 var errorDescription: String? { message }99 var isUnauthenticated: Bool { status == 401 }100 static func transport(_ e: Error) -> APIError {101 APIError(status: 0, code: "network", message: (e as? URLError)?.code == .notConnectedToInternet ? "Pas de connexion Internet." : "Serveur injoignable. Vérifiez la connexion et réessayez.")102 }103}104105struct API: Sendable {106 static let production = URL(string: "https://sms.spboucher.ai")!107 static let cookieName = "mlsms_session"108 let base: URL109 let session: URLSession110 let streamSession: URLSession111112 init(base: URL = API.production) {113 self.base = base114 let c = URLSessionConfiguration.default115 c.httpCookieStorage = .shared116 c.httpCookieAcceptPolicy = .always117 c.requestCachePolicy = .reloadIgnoringLocalCacheData118 c.timeoutIntervalForRequest = 20119 c.waitsForConnectivity = false120 session = URLSession(configuration: c)121 // Flux temps réel : le serveur n'envoie un battement que toutes les 25 s. Avec le délai d'inactivité de 20 s des requêtes122 // ordinaires, le flux était coupé en permanence sur un service calme (défaut du build 1) : il a sa propre session.123 let s = URLSessionConfiguration.default124 s.httpCookieStorage = .shared125 s.httpCookieAcceptPolicy = .always126 s.requestCachePolicy = .reloadIgnoringLocalCacheData127 s.timeoutIntervalForRequest = 75128 s.timeoutIntervalForResource = 6 * 3600129 s.waitsForConnectivity = true130 streamSession = URLSession(configuration: s)131 }132133 static let decoder: JSONDecoder = {134 let d = JSONDecoder()135 d.keyDecodingStrategy = .convertFromSnakeCase136 d.dateDecodingStrategy = .custom { dec in137 let s = try dec.singleValueContainer().decode(String.self)138 if let date = API.parseDate(s) { return date }139 throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "date invalide : \(s)"))140 }141 return d142 }()143 static func parseDate(_ s: String) -> Date? {144 let f = ISO8601DateFormatter()145 f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]146 if let d = f.date(from: s) { return d }147 f.formatOptions = [.withInternetDateTime]148 return f.date(from: s)149 }150 /// Décode une réponse d'erreur normalisée { error: { code, message } }.151 static func error(status: Int, data: Data, retryAfter: String? = nil) -> APIError {152 struct Envelope: Decodable { struct E: Decodable { let code: String; let message: String }; let error: E }153 if let e = try? JSONDecoder().decode(Envelope.self, from: data) { return APIError(status: status, code: e.error.code, message: e.error.message.prefix(1).uppercased() + e.error.message.dropFirst() + (e.error.message.hasSuffix(".") ? "" : "."), retryAfter: retryAfter.flatMap(Int.init)) }154 return APIError(status: status, code: "http_\(status)", message: "Erreur \(status) du serveur.", retryAfter: retryAfter.flatMap(Int.init))155 }156157 func request(_ method: String, _ path: String, json: [String: Any]? = nil, headers: [String: String] = [:]) -> URLRequest {158 var r = URLRequest(url: URL(string: path, relativeTo: base)!)159 r.httpMethod = method160 r.setValue("maclustr-sms", forHTTPHeaderField: "X-Requested-With") // exigé par le serveur pour toute écriture (anti-CSRF)161 r.setValue("application/json", forHTTPHeaderField: "Accept")162 for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }163 if let json { r.httpBody = try? JSONSerialization.data(withJSONObject: json); r.setValue("application/json", forHTTPHeaderField: "Content-Type") }164 return r165 }166 func raw(_ method: String, _ path: String, json: [String: Any]? = nil, headers: [String: String] = [:]) async throws -> Data {167 let data: Data, resp: URLResponse168 do { (data, resp) = try await session.data(for: request(method, path, json: json, headers: headers)) } catch { throw APIError.transport(error) }169 let http = resp as! HTTPURLResponse170 guard (200..<300).contains(http.statusCode) else { throw API.error(status: http.statusCode, data: data, retryAfter: http.value(forHTTPHeaderField: "Retry-After")) }171 return data172 }173 func call<T: Decodable>(_ method: String, _ path: String, json: [String: Any]? = nil, headers: [String: String] = [:], as: T.Type = T.self) async throws -> T {174 let data = try await raw(method, path, json: json, headers: headers)175 do { return try API.decoder.decode(T.self, from: data) } catch { throw APIError(status: 0, code: "decoding", message: "Réponse du serveur inattendue.") }176 }177 func object(_ method: String, _ path: String, json: [String: Any]? = nil) async throws -> [String: Any] {178 (try JSONSerialization.jsonObject(with: try await raw(method, path, json: json))) as? [String: Any] ?? [:]179 }180181 // MARK: Points d'entrée182 func me() async throws -> Me { try await call("GET", "/api/auth/me") }183 func logout() async throws { _ = try await raw("POST", "/api/auth/logout", json: [:]) }184 func overview() async throws -> Overview { try await call("GET", "/api/admin/overview") }185 func devices() async throws -> [Device] { try await call("GET", "/api/admin/devices", as: ListOf<Device>.self).data }186 func sims() async throws -> SimList { try await call("GET", "/api/admin/sims") }187 func messages(direction: String? = nil, status: String? = nil, peer: String? = nil, cursor: String? = nil, limit: Int = 40) async throws -> Page<SMSMessage> {188 var q = URLComponents(); q.queryItems = [URLQueryItem(name: "limit", value: String(limit))]189 if let direction { q.queryItems?.append(.init(name: "direction", value: direction)) }190 if let status { q.queryItems?.append(.init(name: "status", value: status)) }191 if let peer { q.queryItems?.append(.init(name: "peer", value: peer)) }192 if let cursor { q.queryItems?.append(.init(name: "cursor", value: cursor)) }193 return try await call("GET", "/api/admin/messages?" + (q.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B"))194 }195 func message(_ id: String) async throws -> SMSMessage { try await call("GET", "/api/admin/messages/\(id)") }196 /// Envoi : la clé d'idempotence garantit qu'un double tap ou un réessai réseau ne crée qu'un seul message.197 func send(to: String, text: String, simId: String?, idempotencyKey: String) async throws -> SMSMessage {198 var body: [String: Any] = ["to": to, "text": text]199 if let simId { body["sim_id"] = simId }200 return try await call("POST", "/api/admin/messages", json: body, headers: ["Idempotency-Key": idempotencyKey])201 }202 func cancel(_ id: String) async throws -> SMSMessage { try await call("POST", "/api/admin/messages/\(id)/cancel", json: [:]) }203 func conversations() async throws -> [Conversation] { try await call("GET", "/api/admin/conversations?limit=100", as: Page<Conversation>.self).data }204 func thread(_ id: String) async throws -> [SMSMessage] { try await call("GET", "/api/admin/conversations/\(id)/messages?limit=100", as: Page<SMSMessage>.self).data }205 func allowedRecipients() async throws -> [AllowedRecipient] { try await call("GET", "/api/admin/allowed-recipients", as: ListOf<AllowedRecipient>.self).data }206 func allow(_ number: String, label: String) async throws { _ = try await raw("POST", "/api/admin/allowed-recipients", json: ["number": number, "label": label]) }207 func disallow(_ number: String) async throws { _ = try await raw("DELETE", "/api/admin/allowed-recipients/" + (number.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? number)) }208 func setKillSwitch(_ on: Bool) async throws { _ = try await raw("PATCH", "/api/admin/settings", json: ["kill_switch": on]) }209210 /// Flux temps réel : chaque élément est l'ensemble des thèmes qui ont changé (« messages », « devices », « queue », « settings »).211 func events() -> AsyncThrowingStream<Set<String>, Error> {212 var r = request("GET", "/api/admin/events"); r.setValue("text/event-stream", forHTTPHeaderField: "Accept"); r.timeoutInterval = 75213 let req = r, session = streamSession214 return AsyncThrowingStream { continuation in215 let task = Task {216 do {217 let (bytes, resp) = try await session.bytes(for: req)218 guard (resp as? HTTPURLResponse)?.statusCode == 200 else { throw APIError(status: (resp as? HTTPURLResponse)?.statusCode ?? 0, code: "sse", message: "Flux temps réel refusé.") }219 continuation.yield([]) // flux établi (aucun thème) : l'appelant sait qu'il est connecté220 for try await line in bytes.lines {221 guard line.hasPrefix("data:"), let d = line.dropFirst(5).trimmingCharacters(in: .whitespaces).data(using: .utf8), let topics = try? JSONDecoder().decode([String].self, from: d) else { continue }222 continuation.yield(Set(topics))223 }224 continuation.finish()225 } catch { continuation.finish(throwing: error) }226 }227 continuation.onTermination = { _ in task.cancel() }228 }229 }230}231