Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Ops/AlertsAPI.swift3// Description: Endpoints of the alerts layer (services/api/src/alerts/routes.ts): the in-app list and its unread counters, mark4// as read, the owner's switches / quiet hours / thresholds, the outgoing webhook (its secret is generated by the5// server and shown once), and the Web Push devices.6// PUSH: the server only speaks Web Push (VAPID, RFC 8030/8291/8292) to browsers' push services. There is NO APNs7// route and no device-token registration: a native app polls `unread()` / `list()` and raises LOCAL notifications,8// and only ever from alert rows the server returned (`WalletAlert`) — never from a guess of its own.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation1314public struct AlertsAPI: Sendable {15 let client: APIClient16 public init(_ client: APIClient) { self.client = client }1718 // MARK: in-app alerts1920 /** Newest first. Page towards the past with `before: page.nextBefore`. */21 public func list(_ q: AlertListQuery = AlertListQuery()) async throws -> AlertPage {22 try await client.get("/alerts", query: [23 "limit": q.limit.map { String(min(max($0, 1), 200)) },24 "before": q.before.map(String.init),25 "severity": q.severity?.rawValue,26 "group": q.group?.rawValue,27 "unread": q.unreadOnly ? "1" : nil,28 ])29 }3031 public func unread() async throws -> AlertUnread { try await client.get("/alerts/unread") }3233 /** Mark these alerts read (1…500 ids per call, the server's bound). Answers the counters after the change. */34 public func markRead(ids: [Int64]) async throws -> AlertUnread {35 precondition(!ids.isEmpty && ids.count <= 500, "the server accepts 1 to 500 ids per call")36 struct Body: Encodable, Sendable { let ids: [Int64] }37 return try await client.post("/alerts/read", body: Body(ids: ids))38 }3940 public func markAllRead() async throws -> AlertUnread {41 struct Body: Encodable, Sendable { let all = true }42 return try await client.post("/alerts/read", body: Body())43 }4445 /**46 The request of the SSE stream of unread counters (GET /alerts/stream; at most 8 at once, each ends by itself after ten47 minutes). To be run with a streaming loader and parsed with `ServerSentEventParser` → `AlertStreamEvent`. Nil when signed out.48 */49 public func streamRequest() async -> URLRequest? { await client.eventStreamRequest("/alerts/stream") }5051 // MARK: owner settings5253 public func settings() async throws -> AlertSettingsView { try await client.get("/alerts/settings") }5455 /** Merge a partial change over the stored settings; answers the whole view again. Enabling the webhook requires an https URL and a generated secret. */56 public func update(_ patch: AlertSettingsPatch) async throws -> AlertSettingsView { try await client.put("/alerts/settings", body: patch) }5758 // MARK: webhook5960 /**61 Generate (or replace) the webhook's shared secret. The answer is the ONLY time the secret is visible: show it, let the62 owner copy it, drop it. Rate-limited by the server (6 per minute).63 */64 public func rotateWebhookSecret() async throws -> AlertWebhookSecret { try await client.post("/alerts/webhook/secret") }6566 /** One signed test call (`system.test`) to the configured URL. Rate-limited by the server (6 per minute). */67 public func testWebhook() async throws -> AlertWebhookTestResult { try await client.post("/alerts/webhook/test") }6869 // MARK: Web Push devices (browsers)7071 public func pushPublicKey() async throws -> PushPublicKey { try await client.get("/push/key") }72 public func pushSubscriptions() async throws -> [PushSubscription] { try await client.get("/push/subscriptions") }7374 /** Register a BROWSER's Web Push subscription. Not usable with an APNs device token: the server refuses any endpoint that is not a browser push service. */75 public func subscribeWebPush(_ s: WebPushSubscriptionRequest) async throws -> PushSubscription { try await client.post("/push/subscriptions", body: s) }7677 public func updatePushSubscription(id: String, label: String? = nil, locale: AlertLocale? = nil) async throws -> PushSubscription {78 struct Body: Encodable, Sendable { let label: String?; let locale: AlertLocale? }79 return try await client.send(.patch, "/push/subscriptions/\(APIClient.segment(id))", body: Body(label: label, locale: locale))80 }8182 public func deletePushSubscription(id: String) async throws { let _: OKResponse = try await client.delete("/push/subscriptions/\(APIClient.segment(id))") }8384 /** A test notification through the real path to one device (or all when `id` is nil). Rate-limited by the server (6 per minute). */85 public func testPush(id: String? = nil) async throws -> PushTestResult {86 struct Body: Encodable, Sendable { let id: String? }87 return try await client.post("/push/test", body: Body(id: id))88 }89}9091extension APIClient {92 /**93 A GET of a `text/event-stream` route with the session cookie, for a streaming loader the caller owns (`URLSession.bytes`94 on a session WITHOUT a cookie jar and that does not follow redirects). Nil when signed out.95 */96 func eventStreamRequest(_ path: String, query: [String: String] = [:], lastEventId: String? = nil) -> URLRequest? {97 guard let cookie = cookieHeader(), var c = URLComponents(url: configuration.origin, resolvingAgainstBaseURL: false) else { return nil }98 c.percentEncodedPath = "/api/v1" + path99 if !query.isEmpty { c.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } }100 guard let url = c.url else { return nil }101 var req = URLRequest(url: url)102 req.httpMethod = "GET"103 req.httpShouldHandleCookies = false104 req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData105 req.setValue(configuration.userAgent, forHTTPHeaderField: "User-Agent")106 req.setValue("text/event-stream", forHTTPHeaderField: "Accept")107 req.setValue(cookie, forHTTPHeaderField: "Cookie")108 if let lastEventId { req.setValue(lastEventId, forHTTPHeaderField: "Last-Event-ID") }109 return req110 }111}112