Repository Public
1import Foundation2import SwiftUI3import UserNotifications45enum Phase: Equatable { case loading, anon, first, recoveryKey(String), link, pending, ready, failed(String) }67@MainActor8final class AppModel: ObservableObject {9 @Published var phase: Phase = .loading10 @Published var snap = Snapshot()11 @Published var open: String? { didSet { if open != oldValue { messages = []; Task { await pushActive(); await refresh() } } } }12 @Published var messages: [Message] = []13 @Published var toast: String?14 @Published var who = ""15 let host = EngineHost()16 private let passkey = Passkey()17 private var seenNotices = 018 var active = true { didSet { Task { await pushActive() } } }1920 init() {21 host.onChanged = { [weak self] in Task { await self?.refresh() } }22 host.onNotify = { [weak self] title, _ in self?.notify(title) }23 Task { await start() }24 }2526 func start() async {27 if let e = host.storeError { phase = .failed(e); return }28 await host.start()29 #if DEBUG30 if let cookie = UserDefaults.standard.string(forKey: "SPMDevCookie"), let host = Config.base.host {31 let parts = cookie.split(separator: "=", maxSplits: 1).map(String.init)32 if parts.count == 2, let c = HTTPCookie(properties: [.name: parts[0], .value: parts[1], .domain: host, .path: "/"]) { HTTPCookieStorage.shared.setCookie(c) }33 }34 #endif35 await boot()36 }3738 func boot() async {39 do {40 guard let r = try await host.call("boot") as? [String: Any], let p = r["phase"] as? String else { phase = .failed("Unexpected engine reply"); return }41 who = r["name"] as? String ?? ""42 switch p {43 case "anon": phase = .anon44 case "first": phase = .first45 case "link":46 phase = .link47 #if DEBUG48 if let key = UserDefaults.standard.string(forKey: "SPMDevRecovery") { await recover(key) }49 #endif50 case "pending": phase = .pending51 case "ready":52 phase = .ready53 await refresh()54 #if DEBUG55 if let text = UserDefaults.standard.string(forKey: "SPMDevSend") {56 Task {57 for _ in 0..<60 where snap.convs.first(where: { !$0.waiting }) == nil { try? await Task.sleep(for: .seconds(1)); await refresh() }58 if let c = snap.convs.first { open = c.id; try? await Task.sleep(for: .seconds(1)); _ = try? await host.call("send", c.id, text, NSNull()) }59 }60 return61 }62 #endif63 _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])64 default: phase = .failed(p)65 }66 } catch { phase = .failed(error.localizedDescription) }67 }6869 func refresh() async {70 guard phase == .ready, let json = try? await host.call("snapshot", open ?? NSNull()) as? String, let data = json.data(using: .utf8),71 let s = try? JSONDecoder().decode(Snapshot.self, from: data) else { return }72 if s.convs != snap.convs || s.online != snap.online || s.pending != snap.pending || s.fatal != snap.fatal || s.unread != snap.unread || s.me != snap.me || s.prefs != snap.prefs {73 var t = s74 t.messages = []75 snap = t76 }77 if s.messages != messages { messages = s.messages }78 if s.notices.count > seenNotices { toast = s.notices.last; seenNotices = s.notices.count }79 #if os(macOS)80 NSApp.dockTile.badgeLabel = s.unread > 0 ? "\(s.unread)" : nil81 #endif82 if s.fatal != nil { await signOut(wipe: false) }83 }84 private func pushActive() async { _ = try? await host.call("setActive", open ?? NSNull(), active) }8586 func run(_ work: @escaping () async throws -> Void) {87 Task { do { try await work() } catch { self.toast = error.localizedDescription } }88 }8990 // ---- sign-in and enrolment91 func signIn() async {92 do {93 let o = try await host.net.json("POST", "/api/login/options", [:])94 let response = try await passkey.assert(options: o["options"] as? [String: Any] ?? [:])95 _ = try await host.net.json("POST", "/api/login/verify", ["challenge_id": o["challenge_id"] ?? "", "response": response])96 await boot()97 } catch { if (error as NSError).code != 1001 { toast = error.localizedDescription } }98 }99 /// Creates an account from an invitation or administrator set-up link.100 func join(link: String, name: String, handle: String) async {101 guard let u = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)), let token = u.fragment, token.count >= 20 else { toast = L("This is not a valid SP Message link.", "Ce lien SP Message n’est pas valide."); return }102 do {103 let o = try await host.net.json("POST", "/api/register/options", ["token": token, "bootstrap": u.path == "/bootstrap", "handle": handle, "display_name": name])104 let response = try await passkey.register(options: o["options"] as? [String: Any] ?? [:])105 _ = try await host.net.json("POST", "/api/register/verify", ["challenge_id": o["challenge_id"] ?? "", "response": response, "label": Config.deviceLabel])106 await boot()107 } catch { if (error as NSError).code != 1001 { toast = error.localizedDescription } }108 }109 func createIdentity() async {110 do {111 if let key = try await host.call("createIdentity", Config.deviceLabel) as? String { phase = .recoveryKey(key) }112 } catch { phase = .failed(error.localizedDescription) }113 }114 func recover(_ key: String) async {115 do { try await host.call("recover", key, Config.deviceLabel); await boot() } catch { toast = error.localizedDescription }116 }117 func signOut(wipe: Bool) async {118 _ = try? await host.call("signOut", wipe)119 host.net.clearCookies()120 open = nil121 snap = Snapshot()122 phase = .anon123 }124125 private func notify(_ title: String) {126 guard !active, snap.prefs?.notify != false else { return }127 let c = UNMutableNotificationContent()128 c.title = title129 c.body = L("New message", "Nouveau message") // never the content of the message130 c.sound = .default131 UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, content: c, trigger: nil))132 }133}134135private let french = (Locale.preferredLanguages.first ?? "en").hasPrefix("fr")136func L(_ en: String, _ fr: String) -> String { french ? fr : en }137