121 lines · 4.5 KB · SwiftRaw
// Cotton chat round the app's root: the engine made once with its live// ports, told when the app comes and goes, when APNs hands a token and when// the object's door opens or closes, and handed down to the screens// (`\.cottonChat`).#if os(iOS)import CottonKitimport CottonMailboximport CottonUIimport SwiftUIimport UIKitimport UserNotifications@MainActorpublic final class ChatEngine { public static let shared = ChatEngine() public let center: ChatCenter /// The chat's notifications: categories, responses, reconcile, keep. let notifier: ChatNotifier private let opener = ChatCoreOpener() private init() { let log: @Sendable (String) -> Void = { Log.write($0) } let opener = self.opener let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("chat-pictures", isDirectory: true) let center = ChatCenter( ports: .init(socket: WebSocketChatSocket(log: log), clock: MainChatClock(), secrets: ChatKeychain(), names: ChatNames.defaults(), pictures: caches, path: NetworkChatPath()), topic: Bundle.main.bundleIdentifier, core: { await opener.core() }, log: log) self.center = center // Made with the engine, before launch finishes: the categories are // registered and the delegate's hooks filled before any response. notifier = ChatNotifier(center: center, log: log) ChatSignOut.forgetDevice = { await center.forgetDevice() } } /// The core, opened through `open` when the engine first needs it. Once, at launch. public func attach(_ open: @escaping @Sendable () async -> (any CottonCalling)?) { Task { await opener.set(open) } }}/// The core, opened on first ask and kept.private actor ChatCoreOpener { private var open: (@Sendable () async -> (any CottonCalling)?)? private var waiting: [CheckedContinuation<Void, Never>] = [] private var opened: CoreChat? func set(_ open: @escaping @Sendable () async -> (any CottonCalling)?) { self.open = open waiting.forEach { $0.resume() } waiting.removeAll() } func core() async -> (any ChatCore)? { if let opened { return opened } if open == nil { await withCheckedContinuation { waiting.append($0) } } guard let core = await open?() else { return nil } let chat = CoreChat(core: core) opened = chat return chat }}public struct ChatShell: ViewModifier { @Environment(\.scenePhase) private var scenePhase @State private var bridge = NotificationBridge.shared private let center = ChatEngine.shared.center public init() {} public func body(content: Content) -> some View { content .environment(\.cottonChat, center) .onChange(of: scenePhase, initial: true) { _, phase in switch phase { case .active: center.foregrounded() Task { await ChatEngine.shared.notifier.foregrounded() } case .background: center.backgrounded() default: break } } .onChange(of: bridge.deviceToken, initial: true) { _, token in if let token { center.alertToken(token) } } .onReceive(NotificationCenter.default.publisher(for: .cottonPersonalDoor)) { note in if note.userInfo?["open"] as? Bool == true { center.doorOpened() } else { center.signedOut() } } .onChange(of: center.registered) { _, registered in if registered { Task { await Self.askToAlert() } } } .task { await center.loadSettings() } } /// A chat is no use unheard: once this phone's key is published, the /// alert permission is asked (the system asks once) and the token follows. /// The ask goes through `CapabilityAuthority`, by the notification seam /// that broadcasts the answer (`SystemNotificationAuthority`). private static func askToAlert() async { let alerts = SystemNotificationAuthority() switch await alerts.read() { case .undetermined: guard await alerts.ask() == .granted else { return } case .granted: break case .denied: return } UIApplication.shared.registerForRemoteNotifications() }}extension View { /// Cotton chat's engine round this view. public func chatShell() -> some View { modifier(ChatShell()) }}#endif