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`). */dataclassCallState(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?,) {enumclassPhase(val word: String) {Idle("idle"), Dialling("dialling"), RingingOut("ringing_out"), RingingIn("ringing_in"),Connecting("connecting"), Live("live"), Reconnecting("reconnecting"), Ended("ended");companionobject {fun of(word: String?): Phase = entries.firstOrNull { it.word == word } ?: Idle } }/** A call is under way: anything but idle and ended. */val active: Booleanget() = phase != Phase.Idle && phase != Phase.Endedcompanionobject {val idle = of(JsonObject(emptyMap()))fun of(json: JsonObject): CallState {val own = json.obj("own")returnCallState( 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. */dataclassCallIceServer(val urls: List<String>, val username: String?, val credential: String?) {companionobject {fun of(json: JsonObject): CallIceServer {val urls = when (val u = json["urls"]) {isJsonArray -> u.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }isJsonPrimitive -> listOfNotNull(u.contentOrNull)else -> emptyList() }returnCallIceServer(urls, json.str("username"), json.str("credential")) } }}/** The SDP kinds a peer-to-peer signal carries. */enumclassCallSignalKind(val word: String) {Offer("offer"), Answer("answer"), Ice("ice"), Restart("restart");companionobject {fun of(word: String?): CallSignalKind? = entries.firstOrNull { it.word == word } }}/** The ICE connection, as `calls.media` takes it. */enumclassCallMediaState(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. */sealedclassCallEffect(val name: String) {dataclassSystemCallOutgoing(val uuid: String, val handle: String, val callName: String?, val video: Boolean) : CallEffect("system_call_outgoing")dataclassSystemCallConnecting(val uuid: String) : CallEffect("system_call_connecting")dataclassSystemCallConnected(val uuid: String, val outgoing: Boolean) : CallEffect("system_call_connected")dataclassSystemCallIncoming(val uuid: String, val title: String, val video: Boolean) : CallEffect("system_call_incoming")dataclassSystemCallUpdate(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, …). */dataclassSystemCallEnded(val uuid: String, val cause: String, val android: Int) : CallEffect("system_call_ended")dataclassStartAudio(val video: Boolean) : CallEffect("start_audio")dataobjectStopAudio : CallEffect("stop_audio")dataobjectStartCamera : CallEffect("start_camera")dataobjectStopCamera : CallEffect("stop_camera")dataclassPlayTone(val tone: String) : CallEffect("play_tone")dataobjectStopTone : CallEffect("stop_tone")/** `url` is the socket's whole address (the core puts the object's origin on `path`). */dataclassOpenSocket(val url: String, val credential: String, val afterMs: Long) : CallEffect("open_socket")dataclassSend(val frame: JsonElement) : CallEffect("send")dataobjectCloseSocket : CallEffect("close_socket")dataclassCreatePeer(val offerer: Boolean, val iceServers: List<CallIceServer>) : CallEffect("create_peer")dataclassApplyRemote(val kind: CallSignalKind, val sdp: String) : CallEffect("apply_remote")dataclassAddCandidate(val candidate: String, val mid: String?, val mline: Int?) : CallEffect("add_candidate")dataobjectRestartIce : CallEffect("restart_ice")dataobjectClosePeer : CallEffect("close_peer")dataclassSetSending(val audio: Boolean, val video: Boolean) : CallEffect("set_sending")dataclassTimer(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. */dataobjectShowRoster : CallEffect("show_roster")/** A group call (owner, 23 Nov 2026; through the SFU, protected in transit and not end to end): its connection. */dataclassSwitchToSfu(val iceServers: List<CallIceServer>) : CallEffect("switch_to_sfu")dataclassPushTracks(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). */dataclassPullTracks(val member: String, val names: List<String>) : CallEffect("pull_tracks")dataclassCloseTracks(val member: String) : CallEffect("close_tracks")/** The SFU's `answer` or `offer`; an offer's [tracks] say whose each mid is. */dataclassApplyRemoteSdp(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. */dataclassNotes(val does: String, val json: JsonObject) : CallEffect(does)/** An effect this build does not know: said in the log, never guessed at. */dataclassUnknown(val does: String) : CallEffect(does)companionobject {fun of(json: JsonObject): CallEffect {val does = json.str("do").orEmpty()val uuid = json.str("uuid").orEmpty()val video = json.bool("video")returnwhen (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) elseUnknown("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) elseUnknown("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")) }) elseUnknown("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. */dataclassCallAnswer(val call: CallState, val effects: List<CallEffect>) {companionobject {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. */objectRingUuid {fun of(room: String): String? {val hex = room.lowercase()if (hex.length != 32 || !hex.all { it in'0'..'9' || it in'a'..'f' }) returnnullreturn"${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}" }}