Cotton code
228 lines · 10.0 KB · SwiftRaw
// The system's call UI on an iPhone: CallKit.//// One `CXProvider` (video, one call group of one call, kept out of the// phone's own Recents because the core writes the history and a call must not// be counted twice) and one `CXCallController`. The core's `system_call_*`// effects arrive as the port's calls; the person's acts on the system screen// (answer, end, mute) come back to the center as its methods. The audio// session is activated by CallKit alone (`didActivate`), never by the app.#if os(iOS)import AVFoundationimport CallKitimport Foundation@MainActorpublic final class CallKitSystem: NSObject, SystemCallPort, RingReporter {    private let provider: CXProvider    private let controller = CXCallController()    /// Where the person's acts go: set once the center is made.    public weak var center: CallCenter?    /// The calls CallKit holds, reported or started here.    private var known: Set<UUID> = []    /// Ends this app asked for (`CXEndCallAction` the core said to request),    /// so the provider's perform does not hand them back as the person's.    private var endingHere: Set<UUID> = []    /// Outgoing calls whose start CallKit has performed: only then may it be told they connect.    private var startedHere: Set<UUID> = []    /// Calls the core said connected before CallKit performed their start (a group's call can be live in    /// a quarter second): told once the start is performed.    private var connectedEarly: Set<UUID> = []    private var log: @Sendable (String) -> Void    /// `icon`: the telephone's template image (PNG data), shown on the    /// system call screen's button back into the app.    public init(icon: Data?, log: @escaping @Sendable (String) -> Void = { _ in }) {        let configuration = CXProviderConfiguration()        configuration.supportsVideo = true        configuration.maximumCallGroups = 1        configuration.maximumCallsPerCallGroup = 1        configuration.includesCallsInRecents = false        configuration.supportedHandleTypes = [.phoneNumber, .generic]        configuration.iconTemplateImageData = icon        provider = CXProvider(configuration: configuration)        self.log = log        super.init()        provider.setDelegate(self, queue: nil)    }    /// Whether CallKit already holds this call (the push reported it).    public func holds(_ uuid: UUID) -> Bool { known.contains(uuid) }    // MARK: The push's own report    /// Report a ring at once, inside the PushKit handler, before the core has    /// said anything: iOS ends an app that does not report a call for EVERY    /// VoIP push, a stop push included. A call CallKit already holds is    /// reported again all the same: CallKit refuses it as already there,    /// which is the report iOS asks for. `completion` runs when CallKit has    /// taken (or refused) it.    public func reportRing(uuid: UUID, video: Bool, completion: @escaping @Sendable () -> Void) {        let fresh = known.insert(uuid).inserted        let update = CXCallUpdate()        update.hasVideo = video        update.supportsHolding = false        update.supportsGrouping = false        update.supportsUngrouping = false        update.supportsDTMF = false        provider.reportNewIncomingCall(with: uuid, update: update) { [weak self, log] error in            if let error {                log("callkit: the ring was not taken: \(error)")                if fresh { Task { @MainActor in self?.known.remove(uuid) } }            }            completion()        }    }    // MARK: SystemCallPort    public func startOutgoing(uuid: UUID, handle: String, name: String?, video: Bool) {        known.insert(uuid)        let action = CXStartCallAction(call: uuid, handle: Self.handle(handle, name: name))        action.isVideo = video        action.contactIdentifier = name        controller.request(CXTransaction(action: action)) { [log] error in            if let error { log("callkit: start refused: \(error)") }        }        let update = Self.update(handle: handle, name: name, video: video)        provider.reportCall(with: uuid, updated: update)    }    public func outgoingConnecting(uuid: UUID) {        provider.reportOutgoingCall(with: uuid, startedConnectingAt: Date())    }    public func outgoingConnected(uuid: UUID) {        guard startedHere.contains(uuid) else {            connectedEarly.insert(uuid)            return        }        provider.reportOutgoingCall(with: uuid, connectedAt: Date())    }    public func reportIncoming(uuid: UUID, title: String, handle: String?, video: Bool) {        if !known.contains(uuid) { reportRing(uuid: uuid, video: video) {} }        // The push reported it: the core's words (the caller's name, once the        // ring's box opened) go on as an update.        let update = CXCallUpdate()        update.localizedCallerName = title        if let handle, !handle.isEmpty { update.remoteHandle = CXHandle(type: .phoneNumber, value: handle) }        update.hasVideo = video        provider.reportCall(with: uuid, updated: update)    }    public func update(uuid: UUID, handle: String, name: String?, video: Bool) {        provider.reportCall(with: uuid, updated: Self.update(handle: handle, name: name, video: video))    }    public func ended(uuid: UUID, reason: Int?) {        guard known.contains(uuid) else { return }        if let reason, let ended = CXCallEndedReason(rawValue: reason) {            known.remove(uuid)            provider.reportCall(with: uuid, endedAt: Date(), reason: ended)            return        }        endingHere.insert(uuid)        controller.request(CXTransaction(action: CXEndCallAction(call: uuid))) { [weak self] error in            guard let error else { return }            Task { @MainActor in                // CallKit no longer holds it (already ended): it is over either way.                self?.log("callkit: end refused: \(error)")                self?.endingHere.remove(uuid)                self?.known.remove(uuid)                self?.provider.reportCall(with: uuid, endedAt: Date(), reason: .remoteEnded)            }        }    }    /// A person's number; a group's call (joined late: the core says no number, chat/CONTRACT.md "Group calls")    /// is the group, by its name.    nonisolated static func handle(_ handle: String, name: String?) -> CXHandle {        handle.isEmpty ? CXHandle(type: .generic, value: name ?? handle) : CXHandle(type: .phoneNumber, value: handle)    }    private static func update(handle: String, name: String?, video: Bool) -> CXCallUpdate {        let update = CXCallUpdate()        update.remoteHandle = Self.handle(handle, name: name)        update.localizedCallerName = name        update.hasVideo = video        update.supportsHolding = false        update.supportsGrouping = false        update.supportsUngrouping = false        update.supportsDTMF = false        return update    }}// The delegate's queue is the main queue (`setDelegate(_, queue: nil)`), so// each callback is on the main actor already and is performed there at once.extension CallKitSystem: CXProviderDelegate {    nonisolated public func providerDidReset(_ provider: CXProvider) {        MainActor.assumeIsolated {            // A reset drops the calls CallKit holds, and only those end. The call daemon (callservicesd) also quits            // when it holds none: on a simulator, whose calls CallKit never holds (`SimulatorCallSystem`), its idle            // exit reset this provider and hung up a group call twice on CALLS WALK 1 (callservicesd exited            // JETSAM_REASON_MEMORY_IDLE_EXIT at 18:17:21.198 and 18:31:17.640; the calls ended cancelled and hung_up            // 0.1 to 1 s later, nobody tapping).            let held = !known.isEmpty            log(held ? "callkit: the provider was reset; the call it held ends" : "callkit: the provider was reset; it held no call")            known.removeAll()            endingHere.removeAll()            startedHere.removeAll()            connectedEarly.removeAll()            if held { center?.end() }        }    }    nonisolated public func provider(_ provider: CXProvider, perform action: CXStartCallAction) {        // The core placed the call already; CallKit is told it is under way, and connected if it is already.        let uuid = action.callUUID        provider.reportOutgoingCall(with: uuid, startedConnectingAt: nil)        action.fulfill()        MainActor.assumeIsolated {            startedHere.insert(uuid)            if connectedEarly.remove(uuid) != nil { self.provider.reportOutgoingCall(with: uuid, connectedAt: Date()) }        }    }    nonisolated public func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {        MainActor.assumeIsolated { center?.answer() }        action.fulfill()    }    nonisolated public func provider(_ provider: CXProvider, perform action: CXEndCallAction) {        let uuid = action.callUUID        MainActor.assumeIsolated {            known.remove(uuid)            startedHere.remove(uuid)            connectedEarly.remove(uuid)            if endingHere.remove(uuid) == nil {                // The person ended it on the system's screen.                log("callkit: ended on the system's screen")                center?.systemEnded()            }        }        action.fulfill()    }    nonisolated public func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {        let muted = action.isMuted        MainActor.assumeIsolated {            if let center, center.call.sendingAudio == muted { center.mute(audio: !muted) }        }        action.fulfill()    }    nonisolated public func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {        action.fail()    }    nonisolated public func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {        MainActor.assumeIsolated { center?.audioActivated() }    }    nonisolated public func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {        MainActor.assumeIsolated { center?.audioDeactivated() }    }}#endif