package com.cottondb.calling import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.cottondb.shell.bool import com.cottondb.shell.obj import com.cottondb.shell.str import com.cottondb.shell.core.CoreException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put /** * The call engine: every `calls.*` answer's effects performed, in order, on the ports, and what happened handed back * as the next method (iOS: CottonCalls/CallCenter.swift, the same engine). * * It decides nothing. A tap asks the core (`calls.start`, `calls.end`, …), a push asks it (`calls.incoming`, * `calls.stop`), the socket's frames, the peer's descriptions and ICE state and every timer ask it; each answer is * `{ call, effects }`, drawn and performed here. The asks run one at a time, in the order they happened, so an * answer's effects are all performed before the next event reaches the core. [scope] is the main thread's. */ class CallCenter( private val ports: Ports, private val scope: CoroutineScope, private val core: suspend () -> CallsCore?, private val log: CallLog = CallLog(), ) { /** The ports, made once by whoever builds the center. */ class Ports( val system: SystemCallPort, val socket: CallSocketPort, val peer: CallPeerPort, val audio: CallAudioPort, val tone: CallTonePort, val clock: CallClockPort, ) /** The call as the core last answered it. */ var call by mutableStateOf(CallState.idle) private set /** The loudspeaker: a route of this phone's, never the core's. */ var speaker by mutableStateOf(false) private set /** The core's words for a refused ask (`calls.start` refused `no_number`), to be said once and taken. */ var refusal by mutableStateOf(null) /** Every effect performed, by name, in order: what a walk and the tests read. */ val performed = mutableListOf() /** The asks, chained: each waits for the one before it. */ private var chain: Job? = null /** The socket's generation: a frame or a close from a socket since closed is dropped. */ private var socketGeneration = 0 // ── What a person does ────────────────────────────────────────────────── /** Call a person in this copy (`calls.start { person, video }`); a refusal's words go to [refused] as well as [refusal]. */ fun start(person: String, video: Boolean, refused: ((String) -> Unit)? = null) = ask("calls.start", able(buildJsonObject { put("person", person); put("video", video) }), refused) /** * What this app can draw on a call, said to the room on each start, ring and join (`can`): Comms draws Take notes' * mark (`["notes"]`), so the others may take notes; an app that does not say it is never counted as able. */ var can: List = emptyList() /** Chat's flush, for an answer that says a group message waits to be told (`flush: true`): Comms sets it. */ var flushPort: (() -> Unit)? = null /** Take notes on this call: the core's notes effects, for the app that records them (Comms). */ var notesPort: ((CallEffect.Notes) -> Unit)? = null private fun able(request: JsonObject): JsonObject = if (can.isEmpty()) request else JsonObject(request + ("can" to kotlinx.serialization.json.JsonArray(can.map { JsonPrimitive(it) }))) /** Call a number (`calls.start { number, video }`): Your people's rows, which are numbers. */ fun startNumber(number: String, video: Boolean, refused: ((String) -> Unit)? = null) = ask("calls.start", able(buildJsonObject { put("number", number); put("video", video) }), refused) /** * Place a call through another core method that answers as `calls.start` does (`chat.call { thread | call, video }`: * a call from a Cotton Chat conversation, or calling back from its Calls tile). */ fun place(method: String, request: JsonObject, refused: ((String) -> Unit)? = null) = ask(method, able(request), refused) fun answer() = ask("calls.answer", JsonObject(emptyMap())) fun decline() = ask("calls.decline", JsonObject(emptyMap())) /** Hang up, or cancel a call still ringing out. */ fun end() = ask("calls.end", JsonObject(emptyMap())) fun toggleMute() = mute(audio = !call.sendingAudio) /** The microphone as the system's own mute says it. */ fun mute(audio: Boolean) = ask("calls.mute", buildJsonObject { put("audio", audio); put("video", call.sendingVideo) }) /** Turn this phone's camera on or off. */ fun toggleVideo() = ask("calls.mute", buildJsonObject { put("audio", call.sendingAudio); put("video", !call.sendingVideo) }) fun toggleSpeaker() { speaker = !speaker ports.audio.setSpeaker(speaker) routesMoved++ } /** Moves whenever a group call's roster changes (who is in, talking, muted, taking notes): the screen asks again. */ var rosterMoved by mutableStateOf(0) private set /** Take notes on this call, or stop (`calls.notes`): everyone in it is shown the mark. */ fun notes(on: Boolean) = ask("calls.notes", buildJsonObject { put("on", on) }) /** Moves whenever the audio routes or the one in use change: the call screen asks again. */ var routesMoved by mutableStateOf(0) private set init { ports.audio.watch { routesMoved++ } } /** The phone's routes now, and the one in use. */ fun routes(): List = ports.audio.routes() fun route(): String? = ports.audio.current() /** The sound sent where the person chose (the call screen's Audio). */ fun chooseRoute(id: String) { ports.audio.choose(id) speaker = ports.audio.routes().firstOrNull { it.id == id }?.kind == "speaker" routesMoved++ } /** A `cottoncalling://call?…` link another app opened: the core reads it, and a call to its one person starts. */ fun open(link: String) = enqueue(null) { core -> val read = core.ask("calls.openLink", buildJsonObject { put("url", link) }) val person = (read["people"] as? kotlinx.serialization.json.JsonArray)?.firstOrNull()?.let { (it as? JsonPrimitive)?.content } ?: return@enqueue run(core, "calls.start", buildJsonObject { put("person", person); put("video", read.bool("video")) }) } // ── What the system says ──────────────────────────────────────────────── /** A push rang this phone (FCM's `{kind: ring, room, video}`). */ /** * A ring pushed here. With the ring's sealed [box] and this phone's chat key ([chatKey], Chat's), the core names * the caller at once (`caller`, the report's title) without the network, and answers before the join (`later`): * the ring shows first, then `calls.join` joins. */ fun incoming(room: String, video: Boolean, box: String? = null, at: Long? = null) = enqueue(null) { core -> val key = box?.let { chatKey?.invoke() } val answer = core.ask("calls.incoming", able(buildJsonObject { put("room", room) put("video", video) put("later", true) if (box != null && key != null) { put("ring", box); put("privateKey", key) } // When the ring began, as the object kept it: a phone rung late starts the call there (CALLS FIX 3). if (at != null) put("at", at) })) caller = answer.obj("caller")?.let { Caller(it.str("number"), it.str("name"), it.str("photoPath")) } val parsed = CallAnswer.of(answer) call = parsed.call perform(parsed.effects) answer.str("join")?.let { run(core, "calls.join", able(buildJsonObject { put("room", it) })) } } /** Who is calling, as the ring's sealed box said it (null until a ring says). */ var caller by mutableStateOf(null) private set /** This phone's chat key, for the ring's box; Chat sets it (Cotton Calling has none, and rings as before). */ var chatKey: (() -> String?)? = null /** * A stop: the ring here is over (answered elsewhere, cancelled). On a missed call [box] names who called, sealed * for this phone's chat key, so a phone that never heard the ring writes its Missed row, at the ring's own times * ([at], [ended]); a second telling never changes the row (CALLS FIX 2). Nothing is reported to the system for a * ring this phone never had: Android takes no report for a push. */ fun stop(room: String, reason: String, box: String? = null, at: Long? = null, ended: Long? = null) = enqueue(null, label = "calls.stop") { core -> val key = box?.let { chatKey?.invoke() } run(core, "calls.stop", buildJsonObject { put("room", room) put("reason", reason) if (box != null && key != null) { put("ring", box); put("privateKey", key) } if (at != null && ended != null) { put("at", at); put("ended", ended) } }) } /** * A ring or a stop came by FCM: the object is told this phone has it, as a socket frame's ack tells it (CALLS FIX 2). * Apart from the asks' chain, so it never holds up the ring; a failure (an older Worker's 404, no network) is never * shown on the call screen, only logged, and tried again quietly every [ACK_RETRY] ms, at most [ACK_TRIES] times * (CALLS FIX 3). */ fun ack(room: String, tries: Int = 0) { val before = acks acks = scope.launch { before?.join() val core = core() ?: return@launch try { core.ask("calls.ack", buildJsonObject { put("room", room) }) } catch (failure: Exception) { if (failure is kotlinx.coroutines.CancellationException) throw failure log.i("calls: an ack was not taken ($failure); tried again later") if (tries + 1 < ACK_TRIES) ports.clock.after(ACK_RETRY) { ack(room, tries + 1) } } } } /** The acks, chained apart from the asks. */ private var acks: kotlinx.coroutines.Job? = null /** What this app says it speaks with its push token (`ring_ack`); Comms sets it, Cotton Calling says nothing. */ var ringCan: List = emptyList() /** The person ended the call on the system's side (the ring's Decline, the ongoing notification's Hang up, Telecom's disconnect). */ fun systemEnded() = if (call.phase == CallState.Phase.RingingIn) decline() else end() /** * The FCM registration token. Firebase hands it at launch, often before this phone has connected to its object, * which the core refuses `not_connected`: the token is kept and sent again until the object takes it (every * [PUSH_RETRY] ms, at most [PUSH_RETRIES] times), and again at each [refresh] (a return to the app). */ fun pushToken(token: String) { pending = buildJsonObject { put("platform", "android") put("token", token) if (ringCan.isNotEmpty()) put("can", kotlinx.serialization.json.JsonArray(ringCan.map { kotlinx.serialization.json.JsonPrimitive(it) })) } pushTries = 0 sendToken() } private var pending: JsonObject? = null private var pushTries = 0 private fun sendToken() { val token = pending ?: return enqueue(null, quiet = true) { core -> try { core.ask("calls.pushToken", token) if (pending == token) pending = null } catch (refusal: CoreException) { if (refusal.code != "not_connected") throw refusal if (pending != token || pushTries >= PUSH_RETRIES) return@enqueue pushTries += 1 log.i("calls: the push token waits for the object ($pushTries)") ports.clock.after(PUSH_RETRY) { sendToken() } } } } /** The call as the core holds it now (a launch, a return to the app). */ fun refresh() { sendToken() enqueue(null) { core -> val held = core.ask("calls.state", JsonObject(emptyMap())) call = CallState.of(held["call"] as? JsonObject ?: JsonObject(emptyMap())) } } // ── The asks, one at a time ───────────────────────────────────────────── private fun ask(method: String, request: JsonObject, refused: ((String) -> Unit)? = null) = enqueue(refused, label = method) { core -> run(core, method, request) } private fun enqueue(refused: ((String) -> Unit)?, quiet: Boolean = false, label: String? = null, work: suspend (CallsCore) -> Unit) { val before = chain chain = scope.launch { before?.join() val core = core() ?: return@launch log.i("calls: no core to ask") try { work(core) } catch (refusal: CoreException) { log.i("calls: ${label ?: "a call"} refused ${refusal.code}: ${refusal.message}") if (!quiet) { this@CallCenter.refusal = refusal.message refused?.invoke(refusal.message) } } catch (failure: Exception) { if (failure is kotlinx.coroutines.CancellationException) throw failure log.i("calls: $failure") } } } /** Wait for every ask made so far: the tests' and a walk's. */ suspend fun settle() { while (true) { val last = chain ?: break last.join() if (chain === last) break } acks?.join() } private suspend fun run(core: CallsCore, method: String, request: JsonObject) { val raw = core.ask(method, request) val answer = CallAnswer.of(raw) call = answer.call perform(answer.effects) // A group's call is told to its members as a group message, which waits until Chat flushes: the core says // when (`flush: true`). Unflushed, members the room could not ring never heard of the call (walk on dev, // 23 Nov 2026: the iPhone simulator, which gets no VoIP push, had no line and no strip to join from). if ((raw["flush"] as? JsonPrimitive)?.content == "true") flushPort?.invoke() } // ── The effects ───────────────────────────────────────────────────────── /** Each effect on its port, in the order the core said them. */ internal fun perform(effects: List) { for (effect in effects) { performed += effect.name when (effect) { is CallEffect.SystemCallOutgoing -> ports.system.startOutgoing(effect.uuid, effect.handle, effect.callName, effect.video) is CallEffect.SystemCallConnecting -> ports.system.outgoingConnecting(effect.uuid) is CallEffect.SystemCallConnected -> ports.system.connected(effect.uuid) is CallEffect.SystemCallIncoming -> ports.system.reportIncoming(effect.uuid, effect.title, effect.video) is CallEffect.SystemCallUpdate -> ports.system.update(effect.uuid, effect.handle, effect.callName, effect.video) is CallEffect.SystemCallEnded -> ports.system.ended(effect.uuid, effect.android) is CallEffect.StartAudio -> ports.audio.configure(effect.video) CallEffect.StopAudio -> { ports.audio.stop() speaker = false } CallEffect.StartCamera -> ports.peer.startCamera() CallEffect.StopCamera -> ports.peer.stopCamera() is CallEffect.PlayTone -> ports.tone.play(effect.tone) CallEffect.StopTone -> ports.tone.stop() is CallEffect.OpenSocket -> openSocket(effect.url, effect.credential, effect.afterMs) is CallEffect.Send -> ports.socket.send(effect.frame) CallEffect.CloseSocket -> { socketGeneration += 1 ports.socket.close() } is CallEffect.CreatePeer -> ports.peer.create(effect.offerer, effect.iceServers, call.video, peerEvents()) is CallEffect.ApplyRemote -> ports.peer.applyRemote(effect.kind, effect.sdp) is CallEffect.AddCandidate -> ports.peer.addCandidate(effect.candidate, effect.mid, effect.mline) CallEffect.RestartIce -> ports.peer.restartIce() CallEffect.ClosePeer -> ports.peer.close() is CallEffect.SetSending -> ports.peer.setSending(effect.audio, effect.video) // The roster (who is in, talking, muted; who takes notes): the call screen asks again. CallEffect.ShowRoster -> rosterMoved++ is CallEffect.Timer -> ports.clock.after(effect.afterMs) { ask("calls.tick", JsonObject(emptyMap())) } is CallEffect.SwitchToSfu -> ports.peer.switchToSfu(effect.iceServers, call.video, peerEvents()) is CallEffect.PushTracks -> ports.peer.pushTracks(effect.audio, effect.video) // The core asked the room for them already; their tracks are claimed as they arrive. is CallEffect.PullTracks -> Unit is CallEffect.CloseTracks -> ports.peer.closeTracks(effect.member) is CallEffect.ApplyRemoteSdp -> ports.peer.applySfu(effect.op, effect.sdp, effect.tracks) is CallEffect.Notes -> notesPort?.invoke(effect) ?: log.i("calls: notes with no recorder: ${effect.does}") is CallEffect.Unknown -> log.i("calls: an effect this build does not know: ${effect.does}") } } } private fun openSocket(url: String, credential: String, afterMs: Long) { socketGeneration += 1 val generation = socketGeneration val open = open@{ if (socketGeneration != generation) return@open ports.socket.open(url, credential, received = { frame -> // What the room could not do (an SFU operation that failed) is said in the log, with its words. if (((frame as? JsonObject)?.get("t") as? JsonPrimitive)?.content == "error") log.i("calls: the room says $frame") if (socketGeneration == generation) ask("calls.signal", buildJsonObject { put("in", frame) }) }, closed = { if (socketGeneration == generation) { socketGeneration += 1 ask("calls.socketClosed", JsonObject(emptyMap())) } }) } if (afterMs > 0) ports.clock.after(afterMs) { open() } else open() } private fun peerEvents() = object : CallPeerEvents { override fun signal(kind: CallSignalKind, sdp: String?, candidate: String?, mid: String?, mline: Int?) { ask("calls.signal", buildJsonObject { put("out", buildJsonObject { put("kind", kind.word) sdp?.let { put("sdp", it) } candidate?.let { put("candidate", it) } mid?.let { put("mid", it) } mline?.let { put("mline", it) } }) }) } override fun media(state: CallMediaState) { ask("calls.media", buildJsonObject { put("state", state.word) }) } override fun sfu(op: String, sdp: String?, tracks: List?, mids: List?) { ask("calls.signal", buildJsonObject { put("out", buildJsonObject { put("sfu", op) sdp?.let { put("sdp", it) } tracks?.let { list -> put("tracks", kotlinx.serialization.json.JsonArray(list.map { t -> buildJsonObject { t.mid?.let { put("mid", it) }; put("name", t.name); t.kind?.let { put("kind", it) } } })) } mids?.let { put("mids", kotlinx.serialization.json.JsonArray(it.map(::JsonPrimitive))) } }) }) } override fun speaking(on: Boolean) { ask("calls.speaking", buildJsonObject { put("on", on) }) } } companion object { const val PUSH_RETRY = 10_000L const val PUSH_RETRIES = 30 const val ACK_RETRY = 15_000L const val ACK_TRIES = 5 /** The frame a socket received, as `calls.signal { in }` takes it. */ fun frame(text: String): JsonElement? = runCatching { kotlinx.serialization.json.Json.parseToJsonElement(text) }.getOrNull() } } /** The caller a ring's sealed box named: their number, the name this phone knows them by, their picture's file here. */ data class Caller(val number: String?, val name: String?, val photoPath: String?)