// The VoIP pushes that ring this phone: PushKit. // // The Worker's pushes name nobody Apple can read: `{ room, video, box? }` // rings and `{ room, stop }` stops a ring (`apps/business/src/calling/push.ts`). // `box` is who is calling, sealed by the person's own object for this phone's // chat key. iOS ENDS an app that does not report a call to CallKit for every // VoIP push before the handler's completion, so the handler reports first, at // once, with the call's UUID made from the room (`RingUUID`), and only then // asks the core (`calls.incoming { ring: box, privateKey, later: true }`), // which opens the box without the network and names the caller on the same // call, then joins (`calls.join`). import CottonKit import Foundation /// One VoIP push, as the Worker sends it. enum VoIPPush: Equatable, Sendable { case ring(room: String, video: Bool, box: String?, at: Int64? = nil) case stop(room: String, reason: String, box: String?, times: CallTimes? = nil) public init?(payload: [AnyHashable: Any]) { guard let room = payload["room"] as? String, !room.isEmpty else { return nil } let box = (payload["box"] as? String).flatMap { $0.isEmpty ? nil : $0 } if let reason = payload["stop"] as? String { let ms = { (key: String) in (payload[key] as? NSNumber)?.int64Value } self = .stop(room: room, reason: reason, box: box, times: CallTimes(at: ms("at"), ended: ms("ended"))) } else { self = .ring(room: room, video: (payload["video"] as? Bool) ?? false, box: box, at: (payload["at"] as? NSNumber)?.int64Value) } } public var room: String { switch self { case .ring(let room, _, _, _), .stop(let room, _, _, _): room } } } /// Who the push handler reports a ring to: CallKit. @MainActor public protocol RingReporter: AnyObject { func reportRing(uuid: UUID, video: Bool, completion: @escaping @Sendable () -> Void) func ended(uuid: UUID, reason: Int?) } /// What a VoIP push does, apart from PushKit itself. @MainActor public final class VoIPPushHandler { private let reporter: any RingReporter private let center: CallCenter /// This phone's chat key, which opens the ring's box (`ChatKeychain`). private let chatKey: @MainActor () -> String? public init(reporter: any RingReporter, center: CallCenter, chatKey: @escaping @MainActor () -> String? = { ChatKeychain().key() }) { self.reporter = reporter self.center = center self.chatKey = chatKey } /// Report the call at once, then hand the push to the core. `completion` /// is PushKit's, called once CallKit has the report. public func handle(payload: [AnyHashable: Any], completion: @escaping @Sendable () -> Void) { guard let push = VoIPPush(payload: payload), let uuid = RingUUID.of(room: push.room) else { // A push this build cannot read is still a call iOS wants told: // reported, and ended at once as failed (`CXCallEndedReason.failed`). let uuid = UUID() reporter.reportRing(uuid: uuid, video: false) { completion() } reporter.ended(uuid: uuid, reason: 1) return } switch push { case .ring(let room, let video, let box, let at): reporter.reportRing(uuid: uuid, video: video) { completion() } center.incoming(room: room, video: video, ring: box, privateKey: box == nil ? nil : chatKey(), pushed: true, at: at) center.ack(room: room) case .stop(let room, let reason, let box, let times): reporter.reportRing(uuid: uuid, video: false) { completion() } center.stop(room: room, reason: reason, ring: box, privateKey: box == nil ? nil : chatKey(), times: times, pushed: true) center.ack(room: room) } } } #if os(iOS) import PushKit /// PushKit's registry for `.voIP`: the token goes to the object through the /// core (`calls.pushToken`), each push to `VoIPPushHandler`. @MainActor public final class VoIPRegistry: NSObject, PKPushRegistryDelegate { private let registry: PKPushRegistry private let handler: VoIPPushHandler private let center: CallCenter public init(handler: VoIPPushHandler, center: CallCenter) { self.handler = handler self.center = center registry = PKPushRegistry(queue: .main) super.init() registry.delegate = self registry.desiredPushTypes = [.voIP] } nonisolated public func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, for type: PKPushType) { guard type == .voIP else { return } let token = credentials.token MainActor.assumeIsolated { // The topic is this app's bundle id; Cotton's entitlement is // `aps-environment: production` on every build (`Cotton.entitlements`), // so the token is a production one and is never filed as sandbox. center.pushToken(token, topic: Bundle.main.bundleIdentifier ?? "", sandbox: false) } } nonisolated public func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) {} nonisolated public func pushRegistry( _ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void ) { guard type == .voIP else { completion() return } nonisolated(unsafe) let dictionary = payload.dictionaryPayload nonisolated(unsafe) let done = completion // The registry's queue is the main queue: reported here, synchronously. MainActor.assumeIsolated { handler.handle(payload: dictionary) { DispatchQueue.main.async { done() } } } } } #endif