Cotton code
223 lines · 11.9 KB · KotlinRaw
package com.cottondb.callingimport com.cottondb.shell.arrimport com.cottondb.shell.boolimport com.cottondb.shell.numimport com.cottondb.shell.objimport com.cottondb.shell.strimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.contentOrNull// Cotton Calling's words from the core, as the Android shell reads them (iOS: CottonCalls/CallEffect.swift).//// Every `calls.*` method answers `{ call, effects }` (crates/cotton-ffi/src/phone/calls.rs): the call as the core// holds it, and the effects the shell performs, IN ORDER. The shell decides nothing: it draws `call` and performs// `effects`, and hands back what happened (a tap, a push, a socket frame, the ICE state, a timer) as the next method./** One call, as the core answers it (`cotton_core::calling::machine::Call`). */data class CallState(    val phase: Phase,    /** This person placed it. */    val outgoing: Boolean,    val video: Boolean,    /** `p2p` or `sfu`. */    val mode: String,    val uuid: String,    val room: String?,    val number: String?,    val person: String?,    val name: String?,    /** What this device sends. */    val sendingAudio: Boolean,    val sendingVideo: Boolean,    /** Milliseconds since the epoch. */    val liveAt: Long?,    val endedAt: Long?,    /** The end reason's word (`hung_up`, `no_answer`, …), once ended. */    val reason: String?,) {    enum class Phase(val word: String) {        Idle("idle"), Dialling("dialling"), RingingOut("ringing_out"), RingingIn("ringing_in"),        Connecting("connecting"), Live("live"), Reconnecting("reconnecting"), Ended("ended");        companion object {            fun of(word: String?): Phase = entries.firstOrNull { it.word == word } ?: Idle        }    }    /** A call is under way: anything but idle and ended. */    val active: Boolean get() = phase != Phase.Idle && phase != Phase.Ended    companion object {        val idle = of(JsonObject(emptyMap()))        fun of(json: JsonObject): CallState {            val own = json.obj("own")            return CallState(                phase = Phase.of(json.str("phase")),                outgoing = json.str("direction") != "in",                video = json.bool("video"),                mode = json.str("mode") ?: "p2p",                uuid = json.str("uuid").orEmpty(),                room = json.str("room"),                number = json.str("number"),                person = json.str("person"),                name = json.str("name"),                sendingAudio = own?.str("audio")?.let { it == "true" } ?: true,                sendingVideo = own?.bool("video") ?: false,                liveAt = json.num("liveAt")?.toLong(),                endedAt = json.num("endedAt")?.toLong(),                reason = json.str("reason"),            )        }    }}/** An ICE server, as the object handed it. */data class CallIceServer(val urls: List<String>, val username: String?, val credential: String?) {    companion object {        fun of(json: JsonObject): CallIceServer {            val urls = when (val u = json["urls"]) {                is JsonArray -> u.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }                is JsonPrimitive -> listOfNotNull(u.contentOrNull)                else -> emptyList()            }            return CallIceServer(urls, json.str("username"), json.str("credential"))        }    }}/** The SDP kinds a peer-to-peer signal carries. */enum class CallSignalKind(val word: String) {    Offer("offer"), Answer("answer"), Ice("ice"), Restart("restart");    companion object {        fun of(word: String?): CallSignalKind? = entries.firstOrNull { it.word == word }    }}/** The ICE connection, as `calls.media` takes it. */enum class CallMediaState(val word: String) { Connected("connected"), Disconnected("disconnected"), Failed("failed") }/** One effect, as the core names it (`Effect`, `#[serde(tag = "do")]`). What the shell does with each is [CallCenter]'s. */sealed class CallEffect(val name: String) {    data class SystemCallOutgoing(val uuid: String, val handle: String, val callName: String?, val video: Boolean) : CallEffect("system_call_outgoing")    data class SystemCallConnecting(val uuid: String) : CallEffect("system_call_connecting")    data class SystemCallConnected(val uuid: String, val outgoing: Boolean) : CallEffect("system_call_connected")    data class SystemCallIncoming(val uuid: String, val title: String, val video: Boolean) : CallEffect("system_call_incoming")    data class SystemCallUpdate(val uuid: String, val handle: String, val callName: String?, val video: Boolean) : CallEffect("system_call_update")    /** `android` is Telecom's `DisconnectCause` code (ERROR 1, LOCAL 2, REMOTE 3, …). */    data class SystemCallEnded(val uuid: String, val cause: String, val android: Int) : CallEffect("system_call_ended")    data class StartAudio(val video: Boolean) : CallEffect("start_audio")    data object StopAudio : CallEffect("stop_audio")    data object StartCamera : CallEffect("start_camera")    data object StopCamera : CallEffect("stop_camera")    data class PlayTone(val tone: String) : CallEffect("play_tone")    data object StopTone : CallEffect("stop_tone")    /** `url` is the socket's whole address (the core puts the object's origin on `path`). */    data class OpenSocket(val url: String, val credential: String, val afterMs: Long) : CallEffect("open_socket")    data class Send(val frame: JsonElement) : CallEffect("send")    data object CloseSocket : CallEffect("close_socket")    data class CreatePeer(val offerer: Boolean, val iceServers: List<CallIceServer>) : CallEffect("create_peer")    data class ApplyRemote(val kind: CallSignalKind, val sdp: String) : CallEffect("apply_remote")    data class AddCandidate(val candidate: String, val mid: String?, val mline: Int?) : CallEffect("add_candidate")    data object RestartIce : CallEffect("restart_ice")    data object ClosePeer : CallEffect("close_peer")    data class SetSending(val audio: Boolean, val video: Boolean) : CallEffect("set_sending")    data class Timer(val afterMs: Long) : CallEffect("timer")    /**     * The room's members as the core holds them. The core says it on a one-to-one call too (the room's roster and     * member frames, machine.rs), so it is no group call's; this build draws no roster.     */    data object ShowRoster : CallEffect("show_roster")    /** A group call (owner, 23 Nov 2026; through the SFU, protected in transit and not end to end): its connection. */    data class SwitchToSfu(val iceServers: List<CallIceServer>) : CallEffect("switch_to_sfu")    data class PushTracks(val audio: Boolean, val video: Boolean) : CallEffect("push_tracks")    /** The SFU will offer [member]'s tracks by these names (the core has asked for them). */    data class PullTracks(val member: String, val names: List<String>) : CallEffect("pull_tracks")    data class CloseTracks(val member: String) : CallEffect("close_tracks")    /** The SFU's `answer` or `offer`; an offer's [tracks] say whose each mid is. */    data class ApplyRemoteSdp(val op: String, val sdp: String, val tracks: List<SfuTrack>) : CallEffect("apply_remote_sdp")    /**     * Take notes on this call (chat CONTRACT "Take notes"): `notes_start { meeting, tracks }`, `notes_track { track,     * member, path, … }`, `notes_stop { meeting, tracks }`, `notes_failed { why }`, as the core said them.     */    data class Notes(val does: String, val json: JsonObject) : CallEffect(does)    /** An effect this build does not know: said in the log, never guessed at. */    data class Unknown(val does: String) : CallEffect(does)    companion object {        fun of(json: JsonObject): CallEffect {            val does = json.str("do").orEmpty()            val uuid = json.str("uuid").orEmpty()            val video = json.bool("video")            return when (does) {                "system_call_outgoing" -> SystemCallOutgoing(uuid, json.str("handle").orEmpty(), json.str("name"), video)                "system_call_connecting" -> SystemCallConnecting(uuid)                "system_call_connected" -> SystemCallConnected(uuid, json.bool("outgoing"))                "system_call_incoming" -> SystemCallIncoming(uuid, json.str("title").orEmpty(), video)                "system_call_update" -> SystemCallUpdate(uuid, json.str("handle").orEmpty(), json.str("name"), video)                "system_call_ended" -> SystemCallEnded(uuid, json.str("cause").orEmpty(), json.num("android")?.toInt() ?: 1)                "start_audio" -> StartAudio(video)                "stop_audio" -> StopAudio                "start_camera" -> StartCamera                "stop_camera" -> StopCamera                "play_tone" -> PlayTone(json.str("tone") ?: "ringback")                "stop_tone" -> StopTone                "open_socket" -> {                    val url = json.str("url")                    val credential = json.str("credential")                    if (url != null && credential != null) OpenSocket(url, credential, json.num("after_ms")?.toLong() ?: 0) else Unknown("open_socket.no_url")                }                "send" -> Send(json["frame"] ?: JsonNull)                "close_socket" -> CloseSocket                "create_peer" -> CreatePeer(json.bool("offerer"), json.arr("ice_servers").map(CallIceServer::of))                "apply_remote" -> {                    val kind = CallSignalKind.of(json.str("kind"))                    val sdp = json.str("sdp")                    if (kind != null && sdp != null) ApplyRemote(kind, sdp) else Unknown("apply_remote.no_sdp")                }                "add_candidate" -> AddCandidate(json.str("candidate").orEmpty(), json.str("mid"), json.num("mline")?.toInt())                "restart_ice" -> RestartIce                "close_peer" -> ClosePeer                "set_sending" -> SetSending(json.str("audio")?.let { it == "true" } ?: true, json.bool("video"))                "timer" -> Timer(json.num("after_ms")?.toLong() ?: 0)                "show_roster" -> ShowRoster                "switch_to_sfu" -> SwitchToSfu(json.arr("ice_servers").map(CallIceServer::of))                "push_tracks" -> PushTracks(json.str("audio")?.let { it == "true" } ?: true, json.bool("video"))                "pull_tracks" -> PullTracks(json.str("member").orEmpty(), (json["names"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }.orEmpty())                "close_tracks" -> CloseTracks(json.str("member").orEmpty())                "apply_remote_sdp" -> {                    val sdp = json.str("sdp")                    if (sdp != null) ApplyRemoteSdp(json.str("op").orEmpty(), sdp, json.arr("tracks").map { SfuTrack(it.str("mid"), it.str("member"), it.str("name").orEmpty(), it.str("kind")) }) else Unknown("apply_remote_sdp.no_sdp")                }                "notes_start", "notes_track", "notes_stop", "notes_failed" -> Notes(does, json)                else -> Unknown(does)            }        }    }}/** One `calls.*` answer: the call, and the effects to perform in order. */data class CallAnswer(val call: CallState, val effects: List<CallEffect>) {    companion object {        fun of(json: JsonObject): CallAnswer =            CallAnswer(CallState.of(json.obj("call") ?: JsonObject(emptyMap())), json.arr("effects").map(CallEffect::of))    }}/** * The room's 32 hex is the call's UUID (`cotton_core::calling::machine::uuid_of_room`), so a push's ring and every * later report name the same call. Any other shape is not a room the Worker makes. */object RingUuid {    fun of(room: String): String? {        val hex = room.lowercase()        if (hex.length != 32 || !hex.all { it in '0'..'9' || it in 'a'..'f' }) return null        return "${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}"    }}