package com.cottondb.callingimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport com.cottondb.shell.boolimport com.cottondb.shell.objimport com.cottondb.shell.strimport com.cottondb.shell.core.CoreExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Jobimport kotlinx.coroutines.launchimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonObjectimport 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. */classCallCenter(privateval ports: Ports,privateval scope: CoroutineScope,privateval core: suspend () -> CallsCore?,privateval log: CallLog = CallLog(),) {/** The ports, made once by whoever builds the center. */classPorts(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)privateset/** The loudspeaker: a route of this phone's, never the core's. */var speaker by mutableStateOf(false)privateset/** The core's words for a refused ask (`calls.start` refused `no_number`), to be said once and taken. */var refusal by mutableStateOf<String?>(null)/** Every effect performed, by name, in order: what a walk and the tests read. */val performed = mutableListOf<String>()/** The asks, chained: each waits for the one before it. */privatevar chain: Job? = null/** The socket's generation: a frame or a close from a socket since closed is dropped. */privatevar 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<String> = 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)? = nullprivatefun able(request: JsonObject): JsonObject =if (can.isEmpty()) request elseJsonObject(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)privateset/** 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)privatesetinit { ports.audio.watch { routesMoved++ } }/** The phone's routes now, and the one in use. */fun routes(): List<AudioRoute> = 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. */funopen(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<Caller?>(null)privateset/** 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@launchtry { 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. */privatevar 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<String> = 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() }privatevar pending: JsonObject? = nullprivatevar pushTries = 0privatefun 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 refusalif (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 ─────────────────────────────────────────────privatefun ask(method: String, request: JsonObject, refused: ((String) -> Unit)? = null) = enqueue(refused, label = method) { core -> run(core, method, request) }privatefun 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. */suspendfun settle() {while (true) {val last = chain ?: break last.join()if (chain === last) break } acks?.join() }privatesuspendfun 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. */internalfun perform(effects: List<CallEffect>) {for (effect in effects) { performed += effect.namewhen (effect) {isCallEffect.SystemCallOutgoing -> ports.system.startOutgoing(effect.uuid, effect.handle, effect.callName, effect.video)isCallEffect.SystemCallConnecting -> ports.system.outgoingConnecting(effect.uuid)isCallEffect.SystemCallConnected -> ports.system.connected(effect.uuid)isCallEffect.SystemCallIncoming -> ports.system.reportIncoming(effect.uuid, effect.title, effect.video)isCallEffect.SystemCallUpdate -> ports.system.update(effect.uuid, effect.handle, effect.callName, effect.video)isCallEffect.SystemCallEnded -> ports.system.ended(effect.uuid, effect.android)isCallEffect.StartAudio -> ports.audio.configure(effect.video)CallEffect.StopAudio -> { ports.audio.stop() speaker = false }CallEffect.StartCamera -> ports.peer.startCamera()CallEffect.StopCamera -> ports.peer.stopCamera()isCallEffect.PlayTone -> ports.tone.play(effect.tone)CallEffect.StopTone -> ports.tone.stop()isCallEffect.OpenSocket -> openSocket(effect.url, effect.credential, effect.afterMs)isCallEffect.Send -> ports.socket.send(effect.frame)CallEffect.CloseSocket -> { socketGeneration += 1 ports.socket.close() }isCallEffect.CreatePeer -> ports.peer.create(effect.offerer, effect.iceServers, call.video, peerEvents())isCallEffect.ApplyRemote -> ports.peer.applyRemote(effect.kind, effect.sdp)isCallEffect.AddCandidate -> ports.peer.addCandidate(effect.candidate, effect.mid, effect.mline)CallEffect.RestartIce -> ports.peer.restartIce()CallEffect.ClosePeer -> ports.peer.close()isCallEffect.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++isCallEffect.Timer -> ports.clock.after(effect.afterMs) { ask("calls.tick", JsonObject(emptyMap())) }isCallEffect.SwitchToSfu -> ports.peer.switchToSfu(effect.iceServers, call.video, peerEvents())isCallEffect.PushTracks -> ports.peer.pushTracks(effect.audio, effect.video)// The core asked the room for them already; their tracks are claimed as they arrive.isCallEffect.PullTracks -> UnitisCallEffect.CloseTracks -> ports.peer.closeTracks(effect.member)isCallEffect.ApplyRemoteSdp -> ports.peer.applySfu(effect.op, effect.sdp, effect.tracks)isCallEffect.Notes -> notesPort?.invoke(effect) ?: log.i("calls: notes with no recorder: ${effect.does}")isCallEffect.Unknown -> log.i("calls: an effect this build does not know: ${effect.does}") } } }privatefun openSocket(url: String, credential: String, afterMs: Long) { socketGeneration += 1val generation = socketGenerationvalopen = 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() } elseopen() }privatefun peerEvents() = object : CallPeerEvents {overridefun 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) } }) }) }overridefun media(state: CallMediaState) { ask("calls.media", buildJsonObject { put("state", state.word) }) }overridefun sfu(op: String, sdp: String?, tracks: List<SfuTrack>?, mids: List<String>?) { 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))) } }) }) }overridefun speaking(on: Boolean) { ask("calls.speaking", buildJsonObject { put("on", on) }) } }companionobject {constval PUSH_RETRY = 10_000Lconstval PUSH_RETRIES = 30constval ACK_RETRY = 15_000Lconstval 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. */dataclassCaller(val number: String?, val name: String?, val photoPath: String?)