Cotton code
185 lines · 9.4 KB · KotlinRaw
package com.cottondb.callingimport android.content.ComponentNameimport android.content.Contextimport android.net.Uriimport android.os.Bundleimport android.telecom.Connectionimport android.telecom.ConnectionRequestimport android.telecom.ConnectionServiceimport android.telecom.DisconnectCauseimport android.telecom.PhoneAccountimport android.telecom.PhoneAccountHandleimport android.telecom.TelecomManagerimport android.telecom.VideoProfile/** * The system's call: Telecom, through a self-managed PhoneAccount (iOS: CallKitSystem.swift). Placing a call asks * `placeCall`, a ring asks `addNewIncomingCall`, and Telecom makes the [CallConnection] each names in * [CallConnectionService]; the call's states are set on it as the core says them, and what Telecom says back (a * headset's answer, a watch's decline, a disconnect) is the engine's next ask. * * Telecom makes a connection when it chooses, so what the core said before then is kept by the call's UUID and set * once it exists. Telecom is how the call rings and holds like a phone call; the call itself never waits on it: a * refusal (no leave, a phone that takes no self-managed calls) is logged and the ring is shown by [CallNotices] * alone. */class TelecomCalls(private val context: Context, private val log: CallLog) : SystemCallPort {    lateinit var engine: CallingEngine    private val telecom = context.getSystemService(TelecomManager::class.java)    val account = PhoneAccountHandle(ComponentName(context, CallConnectionService::class.java), ACCOUNT)    private val connections = mutableMapOf<String, CallConnection>()    /** What the core last said of a call Telecom has not made yet. */    private val wanted = mutableMapOf<String, Wanted>()    private data class Wanted(val name: String?, val video: Boolean, val incoming: Boolean, val state: String, val cause: Int? = null)    /** The PhoneAccount, registered at launch: self-managed, audio and video. */    fun register(label: String) {        runCatching {            telecom.registerPhoneAccount(                PhoneAccount.builder(account, label)                    .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED or PhoneAccount.CAPABILITY_VIDEO_CALLING or PhoneAccount.CAPABILITY_SUPPORTS_VIDEO_CALLING)                    .build(),            )        }.onFailure { log.i("calls telecom: the account was refused: $it") }    }    override fun startOutgoing(uuid: String, handle: String, name: String?, video: Boolean) {        wanted[uuid] = Wanted(name, video, incoming = false, state = "dialing")        val extras = Bundle().apply {            putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, account)            putBundle(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, Bundle().apply { putString(UUID, uuid) })            if (video) putInt(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_BIDIRECTIONAL)        }        runCatching { telecom.placeCall(Uri.fromParts(PhoneAccount.SCHEME_TEL, handle.ifEmpty { "cotton" }, null), extras) }            .onFailure { log.i("calls telecom: placeCall was refused: $it") }    }    override fun outgoingConnecting(uuid: String) {        // Telecom has no state between dialling and active: the connection stays dialling until it is up.    }    override fun connected(uuid: String) {        wanted[uuid] = (wanted[uuid] ?: Wanted(null, false, incoming = false, state = "active")).copy(state = "active")        connections[uuid]?.setActive()        engine.notices.ringOver(uuid)    }    override fun reportIncoming(uuid: String, title: String, video: Boolean) {        if (connections.containsKey(uuid) || wanted[uuid]?.incoming == true) return update(uuid, "", title, video)        wanted[uuid] = Wanted(title, video, incoming = true, state = "ringing")        val extras = Bundle().apply {            putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, account)            putBundle(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, Bundle().apply { putString(UUID, uuid) })            if (video) putInt(TelecomManager.EXTRA_INCOMING_VIDEO_STATE, VideoProfile.STATE_BIDIRECTIONAL)        }        runCatching { telecom.addNewIncomingCall(account, extras) }            .onFailure {                log.i("calls telecom: the ring was refused: $it")                engine.notices.ring(uuid, title, video)            }    }    override fun update(uuid: String, handle: String, name: String?, video: Boolean) {        wanted[uuid]?.let { wanted[uuid] = it.copy(name = name ?: it.name, video = video) }        connections[uuid]?.let { connection ->            name?.let { connection.setCallerDisplayName(it, TelecomManager.PRESENTATION_ALLOWED) }            if (handle.isNotEmpty()) connection.setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, handle, null), TelecomManager.PRESENTATION_ALLOWED)        }        // The ring's notice names the caller once the core knows who it is.        if (wanted[uuid]?.state == "ringing") engine.notices.ring(uuid, name ?: wanted[uuid]?.name.orEmpty(), video, again = true)    }    override fun ended(uuid: String, cause: Int) {        engine.notices.ringOver(uuid)        val connection = connections.remove(uuid)        if (connection == null) {            wanted[uuid] = (wanted[uuid] ?: Wanted(null, false, false, "ended")).copy(state = "ended", cause = cause)            return        }        wanted.remove(uuid)        connection.setDisconnected(DisconnectCause(cause))        connection.destroy()    }    /** Telecom made the connection a request names: what the core already said is set on it. */    internal fun made(request: ConnectionRequest?, incoming: Boolean): Connection {        val extras = request?.extras        val uuid = extras?.getString(UUID)            ?: extras?.getBundle(if (incoming) TelecomManager.EXTRA_INCOMING_CALL_EXTRAS else TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS)?.getString(UUID)            ?: wanted.entries.lastOrNull { it.value.incoming == incoming }?.key            ?: return Connection.createFailedConnection(DisconnectCause(DisconnectCause.ERROR))        val want = wanted[uuid]        if (want?.state == "ended") {            wanted.remove(uuid)            return Connection.createFailedConnection(DisconnectCause(want.cause ?: DisconnectCause.LOCAL))        }        val connection = CallConnection(uuid, this)        connection.connectionProperties = Connection.PROPERTY_SELF_MANAGED        connection.audioModeIsVoip = true        connection.connectionCapabilities = Connection.CAPABILITY_MUTE        want?.name?.let { connection.setCallerDisplayName(it, TelecomManager.PRESENTATION_ALLOWED) }        connection.videoState = if (want?.video == true) VideoProfile.STATE_BIDIRECTIONAL else VideoProfile.STATE_AUDIO_ONLY        when (want?.state) {            "active" -> connection.setActive()            "ringing" -> connection.setRinging()            else -> if (incoming) connection.setRinging() else connection.setDialing()        }        connections[uuid] = connection        return connection    }    /** Telecom could not make it: the ring is shown without Telecom; an outgoing call goes on without it. */    internal fun failed(request: ConnectionRequest?, incoming: Boolean) {        log.i("calls telecom: Telecom made no ${if (incoming) "incoming" else "outgoing"} connection")        if (!incoming) return        val uuid = request?.extras?.getBundle(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS)?.getString(UUID)            ?: wanted.entries.lastOrNull { it.value.incoming }?.key ?: return        val want = wanted[uuid] ?: return        if (want.state == "ringing") engine.notices.ring(uuid, want.name.orEmpty(), want.video)    }    internal fun gone(uuid: String) {        connections.remove(uuid)    }    companion object {        const val ACCOUNT = "cotton"        const val UUID = "com.cottondb.calling.UUID"    }}/** One call as Telecom holds it: its asks are the engine's, by the call's UUID. */class CallConnection(val uuid: String, private val calls: TelecomCalls) : Connection() {    private val center get() = calls.engine.center    /** Telecom says the ring may show its own screen: the full-screen notice, ringing. */    override fun onShowIncomingCallUi() {        val call = center.call        calls.engine.notices.ring(uuid, call.name ?: call.number ?: "", call.video)    }    override fun onAnswer() = calls.engine.answer()    override fun onAnswer(videoState: Int) = calls.engine.answer()    override fun onReject() = center.decline()    override fun onDisconnect() = center.systemEnded()    override fun onAbort() = center.systemEnded()    override fun onStateChanged(state: Int) {        if (state == STATE_DISCONNECTED) calls.gone(uuid)    }}/** The ConnectionService Telecom binds for the PhoneAccount: each connection is the engine's [TelecomCalls]'. */class CallConnectionService : ConnectionService() {    private val calls get() = CallingEngine.of(this).telecom    override fun onCreateOutgoingConnection(account: PhoneAccountHandle?, request: ConnectionRequest?): Connection = calls.made(request, incoming = false)    override fun onCreateIncomingConnection(account: PhoneAccountHandle?, request: ConnectionRequest?): Connection = calls.made(request, incoming = true)    override fun onCreateOutgoingConnectionFailed(account: PhoneAccountHandle?, request: ConnectionRequest?) = calls.failed(request, incoming = false)    override fun onCreateIncomingConnectionFailed(account: PhoneAccountHandle?, request: ConnectionRequest?) = calls.failed(request, incoming = true)}