package com.cottondb.calling import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.compose.runtime.snapshotFlow import androidx.core.content.ContextCompat import com.cottondb.shell.ShellApplication import com.cottondb.shell.core.Lines import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import kotlinx.serialization.json.JsonPrimitive /** * The call engine, made once per process (Cotton Calling's, and Cotton Chat's since calls moved into Chat, 19 Nov * 2026; the app's [CallsHost] says whose words it speaks) with its live ports (iOS: CallingEngine.swift): the call center, * Telecom, WebRTC, the room's socket, the audio route and the ringback. It is made at the application's start, before * any screen, so a push that woke the process finds it; the core is the process's one, connected on first ask. * * The leave a call needs (the microphone; the camera for video) is asked when it is first needed, by the screen in * front ([gate], set while the app is open); a ring answered with no leave yet opens the app to ask it. */ class CallingEngine private constructor(val app: ShellApplication) { val log = CallLog { Log.i(TAG, it) } val words = (app as? CallsHost)?.callWords() ?: CallWords() val telecom = TelecomCalls(app, log) val peer = WebRtcPeer(app, log) val notices = CallNotices(app, this) private val scope = MainScope() val center = CallCenter( CallCenter.Ports(telecom, RoomSocket(log), peer, CallAudio(app), Ringback(), MainClock()), scope, core = { app.connectedCore().getOrNull()?.let { core -> CallsCore { method, request -> core.obj(method, request) } } }, log, ) /** The screen in front asks the OS for [permissions], then runs its answer (true: every one given). */ var gate: ((permissions: List, then: (Boolean) -> Unit) -> Unit)? = null /** An answer waiting for the app to come forward and ask the leave it needs. */ var answerWaiting = false init { telecom.engine = this scope.launch { runCatching { val core = app.core.await().getOrThrow() val name = (app.manifest["name"] as? JsonPrimitive)?.content.orEmpty() words.lines = Lines.of(core.obj("shell.lines"), name) telecom.register(name) }.onFailure { log.i("calls: no words: $it") } } // The call's foreground service stands while a call is up (placed or answered) and goes when it ends. scope.launch { snapshotFlow { center.call.active && center.call.phase != CallState.Phase.RingingIn }.collect { up -> if (up) CallService.start(app) else CallService.stop(app) } } } /** The leave a call needs: the microphone, the camera for video, and leave to notify (Android 13+) for the call's notice. */ fun needs(video: Boolean): List = buildList { add(Manifest.permission.RECORD_AUDIO) if (video) add(Manifest.permission.CAMERA) if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS) }.filter { ContextCompat.checkSelfPermission(app, it) != PackageManager.PERMISSION_GRANTED } /** Whether the microphone may be used: a call goes nowhere without it. */ private fun hears() = ContextCompat.checkSelfPermission(app, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED /** Run [then] once the leave for a call is asked; with no microphone the core's call is not placed, and that is said. */ private fun withLeave(video: Boolean, then: () -> Unit) { val missing = needs(video) val gate = gate if (missing.isEmpty() || gate == null) { if (hears()) then() else center.refusal = words.line("android.microphone") return } gate(missing) { _ -> if (hears()) then() else center.refusal = words.line("android.microphone") } } /** Call a person in this copy (a card on the deck). */ fun place(person: String, video: Boolean, refused: (String) -> Unit) = withLeave(video) { center.start(person, video, refused) } /** A call link another app opened: the core reads it (`calls.openLink`) and the call to its person starts. */ fun openLink(link: String) = withLeave(video = false) { center.open(link) } /** Call a number (a row of Your people). */ fun placeNumber(number: String, video: Boolean, refused: (String) -> Unit) = withLeave(video) { center.startNumber(number, video, refused) } /** A call another core method places (`chat.call`), once the leave for it is asked. */ fun placeWith(method: String, request: kotlinx.serialization.json.JsonObject, video: Boolean, refused: (String) -> Unit) = withLeave(video) { center.place(method, request, refused) } /** The phone's other camera. */ fun flipCamera() = peer.flipCamera() /** The camera on or off; turning it on asks its leave first where it has none. */ fun camera() { if (center.call.sendingVideo) return center.toggleVideo() val gate = gate val missing = listOf(Manifest.permission.CAMERA).filter { ContextCompat.checkSelfPermission(app, it) != PackageManager.PERMISSION_GRANTED } if (missing.isEmpty() || gate == null) return center.toggleVideo() gate(missing) { given -> if (given) center.toggleVideo() } } /** * Answer the ring: at once with the leave already given, else the app is brought forward to ask it (a headset's * answer, the ring's own Answer before any leave), and answers once it has. */ fun answer() { if (center.call.phase != CallState.Phase.RingingIn) return if (hears() && gate == null) return center.answer() if (gate != null) return withLeave(center.call.video) { center.answer() } answerWaiting = true runCatching { app.startActivity(CallingActivity.intent(app, CallingActivity.ANSWER)) }.onFailure { log.i("calls: the app could not come forward to answer: $it") } } /** The app came forward with an answer waiting (the ring's Answer): it is asked now that a screen can ask the leave. */ fun answerNow() { answerWaiting = false answer() } companion object { const val TAG = "cotton-calls" @Volatile private var made: CallingEngine? = null /** The process's engine. */ fun of(context: Context): CallingEngine = made ?: synchronized(this) { made ?: CallingEngine(context.applicationContext as ShellApplication).also { made = it } } } } /** * The engine's words, once the core has answered them; before then, the key itself. Cotton Calling's are the calling * set's own keys; another app ([CallsHost]) names its set and which of its keys stands for each. */ class CallWords(private val set: String = "calling", private val keys: Map = emptyMap()) { @Volatile var lines: Lines? = null fun line(key: String): String { val own = keys[key] ?: key return lines?.line(set, own) ?: own } } /** The application an engine runs in, when it is not Cotton Calling: whose words the engine speaks. */ interface CallsHost { fun callWords(): CallWords } /** The actions the call's notices open the app's own activity with (its launcher activity, whichever app it is). */ object CallingActivity { const val RING = "com.cottondb.calling.RING" const val ANSWER = "com.cottondb.calling.ANSWER" /** * This process's own mark on the intents its call notices make (AUDIT E, a stolen phone or another app): the * launcher activity is exported, so any app could send it RING or ANSWER; only an intent carrying this mark, * which no other app can know, stands over the lock screen or answers. */ const val MARK = "com.cottondb.calling.MARK" val mark: String = java.util.UUID.randomUUID().toString() /** The app's launcher activity, asked to [action]. */ fun intent(context: android.content.Context, action: String): android.content.Intent { val launcher = context.packageManager.getLaunchIntentForPackage(context.packageName)?.component return android.content.Intent(action).setPackage(context.packageName).apply { if (launcher != null) component = launcher } .putExtra(MARK, mark) .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) } /** Whether [intent] is one of this process's own call notices' (it carries [mark]). */ fun ours(intent: android.content.Intent): Boolean = intent.getStringExtra(MARK) == mark }