package com.cottondb.calling import android.content.Intent import android.os.Build import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts /** * What an app's one activity does for its calls (Cotton Chat's; Cotton Calling's MainActivity does the same itself): * it asks the leave a call needs while it is in front ([CallingEngine.gate]), and takes the ring's Answer and its * full-screen tap ([CallingActivity]), standing over the lock screen for them as a phone's call screen does. * * Made as the activity's own property, before its `onCreate`, so its result launcher registers in time. */ class CallGate(private val activity: ComponentActivity) { private var then: ((Boolean) -> Unit)? = null private val leave = activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { given -> val run = then then = null run?.invoke(given.values.all { it }) } /** The activity's `onCreate` and `onNewIntent`. */ fun take(intent: Intent?) { val action = intent?.action ?: return if (action != CallingActivity.RING && action != CallingActivity.ANSWER) return // AUDIT E: only this app's own ring, and only while a call rings or is on, stands over the lock screen or // answers; another app's RING or ANSWER sent to the exported activity is nothing. if (!CallingActivity.ours(intent) || !callLive()) return if (Build.VERSION.SDK_INT >= 27) { activity.setShowWhenLocked(true) activity.setTurnScreenOn(true) } if (action == CallingActivity.ANSWER) CallingEngine.of(activity).answerWaiting = true } /** Whether a call rings or is on now. */ private fun callLive(): Boolean = CallingEngine.of(activity).center.call.let { it.active || it.phase == CallState.Phase.RingingIn } /** Off the lock screen again once no call is on (AUDIT E: it stood over it for good after any call). */ private fun stepDown() { if (Build.VERSION.SDK_INT >= 27 && !callLive()) { activity.setShowWhenLocked(false) activity.setTurnScreenOn(false) } } /** The activity's `onResume`: the leave is asked here while it is in front, and a waiting answer answered. */ fun resumed() { stepDown() val engine = CallingEngine.of(activity) engine.gate = { permissions, then -> this.then = then leave.launch(permissions.toTypedArray()) } if (engine.answerWaiting) engine.answerNow() } /** The activity's `onPause`. */ fun paused() { CallingEngine.of(activity).gate = null stepDown() } }