Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / call / WhatsAppCallManager.kt
WhatsAppCallManager.kt290 lines · 11.8 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp.call |
| 2 | |
| 3 | import android.content.Context |
| 4 | import com.vayunmathur.library.log.Log |
| 5 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol |
| 6 | import com.vayunmathur.communicate.data.whatsapp.padMessage |
| 7 | import com.vayunmathur.communicate.data.whatsapp.unpadMessage |
| 8 | import kotlinx.coroutines.CoroutineScope |
| 9 | import kotlinx.coroutines.Dispatchers |
| 10 | import kotlinx.coroutines.SupervisorJob |
| 11 | import kotlinx.coroutines.flow.MutableStateFlow |
| 12 | import kotlinx.coroutines.flow.StateFlow |
| 13 | import kotlinx.coroutines.flow.asStateFlow |
| 14 | import kotlinx.coroutines.launch |
| 15 | |
| 16 | /** Coarse call lifecycle exposed to the UI. */ |
| 17 | enum class WhatsAppCallPhase { Idle, Outgoing, Incoming, Connecting, Active, Ended } |
| 18 | |
| 19 | /** An immutable snapshot of the current WhatsApp call for the UI. */ |
| 20 | data class WhatsAppCallState( |
| 21 | val phase: WhatsAppCallPhase = WhatsAppCallPhase.Idle, |
| 22 | val callId: String = "", |
| 23 | val peerJid: String = "", |
| 24 | val peerName: String = "", |
| 25 | val isVideo: Boolean = false, |
| 26 | val muted: Boolean = false, |
| 27 | val speaker: Boolean = false, |
| 28 | ) |
| 29 | |
| 30 | /** |
| 31 | * Orchestrates a single WhatsApp 1:1 call (Phase D 3c): wires [WhatsAppCallSignaling] to the |
| 32 | * [WhatsAppCallSession] media leg and the [WhatsAppCallCrypto] call key, publishing a |
| 33 | * [WhatsAppCallState] flow. Mirrors `GoogleVoiceCallManager`. |
| 34 | * |
| 35 | * It talks to the transport (socket send + per-device call-key encrypt/decrypt) through a [Bridge] |
| 36 | * implemented by `WhatsAppClient`, so this class has no direct socket/Signal dependency and the |
| 37 | * client stays the single owner of the Noise connection. |
| 38 | * |
| 39 | * Interop: the local SDP + ICE are carried inside our `<webrtc>` `<call>` extension, so calling |
| 40 | * works **client-to-client (our app ↔ our app)** but not against official WhatsApp servers. |
| 41 | */ |
| 42 | object WhatsAppCallManager { |
| 43 | |
| 44 | private const val TAG = "WACallManager" |
| 45 | |
| 46 | /** Transport hooks the client provides. */ |
| 47 | interface Bridge { |
| 48 | val ownJid: String |
| 49 | fun newId(): String |
| 50 | suspend fun sendCallStanza(node: WhatsAppProtocol.Node): Boolean |
| 51 | /** Fan-out encrypt the padded call key to every peer + own device. */ |
| 52 | suspend fun encryptCallKey(toJid: String, paddedCallKey: ByteArray): List<WhatsAppProtocol.ParticipantEnc> |
| 53 | /** Decrypt an inbound call-key `<enc>`; returns the still-padded plaintext or null. */ |
| 54 | suspend fun decryptCallKey(senderJid: String, encType: String, ciphertext: ByteArray): ByteArray? |
| 55 | fun emit(event: com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent) |
| 56 | fun resolveName(jid: String): String? |
| 57 | } |
| 58 | |
| 59 | private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
| 60 | private val _state = MutableStateFlow(WhatsAppCallState()) |
| 61 | val state: StateFlow<WhatsAppCallState> = _state.asStateFlow() |
| 62 | |
| 63 | private var appContext: Context? = null |
| 64 | private var bridge: Bridge? = null |
| 65 | |
| 66 | private var session: WhatsAppCallSession? = null |
| 67 | private var callKey: ByteArray? = null |
| 68 | private var pendingRemoteSdp: String? = null |
| 69 | private var callStartMs: Long = 0L |
| 70 | |
| 71 | fun init(context: Context, bridge: Bridge) { |
| 72 | if (appContext == null) appContext = context.applicationContext |
| 73 | this.bridge = bridge |
| 74 | } |
| 75 | |
| 76 | // ------------------------------------------------------------------ outbound |
| 77 | |
| 78 | fun placeCall(jid: String, video: Boolean = false) { |
| 79 | val ctx = appContext ?: return |
| 80 | val b = bridge ?: return |
| 81 | val callId = b.newId() |
| 82 | _state.value = WhatsAppCallState( |
| 83 | phase = WhatsAppCallPhase.Outgoing, callId = callId, peerJid = jid, |
| 84 | peerName = b.resolveName(jid).orEmpty(), isVideo = video, |
| 85 | ) |
| 86 | scope.launch { |
| 87 | runCatching { |
| 88 | val key = WhatsAppCallCrypto.generateCallKey() |
| 89 | callKey = key |
| 90 | val s = newSession(ctx, video).also { it.initialize() } |
| 91 | session = s |
| 92 | val sdp = s.createOffer() |
| 93 | val encs = b.encryptCallKey(jid, WhatsAppProtocol.padMessage(key)) |
| 94 | if (encs.isEmpty()) { fail(callId, "no_devices"); return@launch } |
| 95 | val node = WhatsAppCallSignaling.buildOffer( |
| 96 | to = jid, callId = callId, callCreator = b.ownJid, video = video, |
| 97 | encs = encs, stanzaId = b.newId(), sdp = sdp, |
| 98 | ) |
| 99 | b.sendCallStanza(node) |
| 100 | emitPhase(callId, WhatsAppCallPhase.Outgoing, video) |
| 101 | }.onFailure { fail(callId, it.message ?: "place_failed") } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fun hangup(reason: String = "hangup") { |
| 106 | val b = bridge ?: return |
| 107 | val st = _state.value |
| 108 | if (st.callId.isEmpty()) { endCall(st.callId, reason); return } |
| 109 | scope.launch { |
| 110 | runCatching { |
| 111 | b.sendCallStanza( |
| 112 | WhatsAppCallSignaling.buildTerminate(st.peerJid, st.callId, b.ownJid, reason, b.newId()), |
| 113 | ) |
| 114 | } |
| 115 | endCall(st.callId, reason) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fun reject() { |
| 120 | val b = bridge ?: return |
| 121 | val st = _state.value |
| 122 | scope.launch { |
| 123 | runCatching { |
| 124 | b.sendCallStanza(WhatsAppCallSignaling.buildReject(st.peerJid, st.callId, st.peerJid, b.newId())) |
| 125 | } |
| 126 | endCall(st.callId, "rejected") |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | fun answer() { |
| 131 | val ctx = appContext ?: return |
| 132 | val b = bridge ?: return |
| 133 | val st = _state.value |
| 134 | val remoteSdp = pendingRemoteSdp ?: run { fail(st.callId, "no_offer_sdp"); return } |
| 135 | scope.launch { |
| 136 | runCatching { |
| 137 | val s = session ?: newSession(ctx, st.isVideo).also { it.initialize(); session = it } |
| 138 | val answerSdp = s.createAnswer(remoteSdp) |
| 139 | b.sendCallStanza( |
| 140 | WhatsAppCallSignaling.buildAccept( |
| 141 | to = st.peerJid, callId = st.callId, callCreator = st.peerJid, |
| 142 | stanzaId = b.newId(), video = st.isVideo, sdp = answerSdp, |
| 143 | ), |
| 144 | ) |
| 145 | setActive(st.callId, st.isVideo) |
| 146 | }.onFailure { fail(st.callId, it.message ?: "answer_failed") } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fun setMuted(muted: Boolean) { |
| 151 | session?.setMuted(muted) |
| 152 | _state.value = _state.value.copy(muted = muted) |
| 153 | } |
| 154 | |
| 155 | fun setSpeaker(on: Boolean) { |
| 156 | session?.setSpeaker(on) |
| 157 | _state.value = _state.value.copy(speaker = on) |
| 158 | } |
| 159 | |
| 160 | /** Flip the camera (video calls only). */ |
| 161 | fun switchCamera() { |
| 162 | (session as? WhatsAppVideoCallSession)?.switchCamera() |
| 163 | } |
| 164 | |
| 165 | /** Enable/disable the local camera track (video calls only). */ |
| 166 | fun setVideoEnabled(enabled: Boolean) { |
| 167 | (session as? WhatsAppVideoCallSession)?.setVideoEnabled(enabled) |
| 168 | } |
| 169 | |
| 170 | /** Attach UI renderers for a video call (no-op for audio). */ |
| 171 | fun attachVideoRenderers(local: org.webrtc.SurfaceViewRenderer?, remote: org.webrtc.SurfaceViewRenderer?) { |
| 172 | (session as? WhatsAppVideoCallSession)?.attachRenderers(local, remote) |
| 173 | } |
| 174 | |
| 175 | // ------------------------------------------------------------------ inbound |
| 176 | |
| 177 | /** Route a parsed inbound `<call>` from the client's message loop. */ |
| 178 | fun onInbound(inbound: WhatsAppCallSignaling.InboundCall) { |
| 179 | val b = bridge ?: return |
| 180 | when (inbound.kind) { |
| 181 | WhatsAppCallSignaling.InboundCall.Kind.OFFER -> onOffer(inbound) |
| 182 | WhatsAppCallSignaling.InboundCall.Kind.ACCEPT -> onAccept(inbound) |
| 183 | WhatsAppCallSignaling.InboundCall.Kind.PREACCEPT -> { |
| 184 | inbound.sdp?.let { sdp -> scope.launch { runCatching { session?.setRemoteAnswer(sdp) } } } |
| 185 | } |
| 186 | WhatsAppCallSignaling.InboundCall.Kind.RELAY -> { |
| 187 | inbound.candidates.forEach { session?.addRemoteCandidate(it) } |
| 188 | } |
| 189 | WhatsAppCallSignaling.InboundCall.Kind.REJECT, |
| 190 | WhatsAppCallSignaling.InboundCall.Kind.TERMINATE -> endCall(inbound.callId, "peer_ended") |
| 191 | WhatsAppCallSignaling.InboundCall.Kind.UNKNOWN -> {} |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | private fun onOffer(inbound: WhatsAppCallSignaling.InboundCall) { |
| 196 | val b = bridge ?: return |
| 197 | if (_state.value.phase != WhatsAppCallPhase.Idle && _state.value.phase != WhatsAppCallPhase.Ended) { |
| 198 | // Busy — auto-reject a second call. |
| 199 | scope.launch { |
| 200 | runCatching { |
| 201 | b.sendCallStanza(WhatsAppCallSignaling.buildReject( |
| 202 | inbound.from, |
| 203 | inbound.callId, |
| 204 | inbound.creator, |
| 205 | b.newId())) |
| 206 | } |
| 207 | } |
| 208 | return |
| 209 | } |
| 210 | scope.launch { |
| 211 | runCatching { |
| 212 | val enc = inbound.enc |
| 213 | if (enc != null) { |
| 214 | val padded = b.decryptCallKey(inbound.creator.ifEmpty { inbound.from }, enc.type, enc.ciphertext) |
| 215 | callKey = padded?.let { WhatsAppProtocol.unpadMessage(it) } |
| 216 | } |
| 217 | pendingRemoteSdp = inbound.sdp |
| 218 | _state.value = WhatsAppCallState( |
| 219 | phase = WhatsAppCallPhase.Incoming, callId = inbound.callId, peerJid = inbound.from, |
| 220 | peerName = b.resolveName(inbound.from).orEmpty(), isVideo = inbound.isVideo, |
| 221 | ) |
| 222 | b.emit( |
| 223 | com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallOffer( |
| 224 | callId = inbound.callId, from = inbound.from, callCreator = inbound.creator, |
| 225 | isVideo = inbound.isVideo, peerName = b.resolveName(inbound.from), |
| 226 | ), |
| 227 | ) |
| 228 | }.onFailure { fail(inbound.callId, it.message ?: "offer_failed") } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | private fun onAccept(inbound: WhatsAppCallSignaling.InboundCall) { |
| 233 | val sdp = inbound.sdp ?: return |
| 234 | scope.launch { |
| 235 | runCatching { |
| 236 | session?.setRemoteAnswer(sdp) |
| 237 | setActive(inbound.callId, inbound.isVideo) |
| 238 | }.onFailure { fail(inbound.callId, it.message ?: "accept_failed") } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // ------------------------------------------------------------------ helpers |
| 243 | |
| 244 | /** Overridable session factory (Phase E swaps in a video session). */ |
| 245 | private fun newSession(ctx: Context, video: Boolean): WhatsAppCallSession = |
| 246 | if (video) WhatsAppVideoCallSession(ctx) else WhatsAppCallSession(ctx) |
| 247 | |
| 248 | private fun setActive(callId: String, video: Boolean) { |
| 249 | callStartMs = System.currentTimeMillis() |
| 250 | _state.value = _state.value.copy(phase = WhatsAppCallPhase.Active, callId = callId, isVideo = video) |
| 251 | emitPhase(callId, WhatsAppCallPhase.Active, video) |
| 252 | } |
| 253 | |
| 254 | private fun emitPhase(callId: String, phase: WhatsAppCallPhase, video: Boolean) { |
| 255 | bridge?.emit( |
| 256 | com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallStateChanged( |
| 257 | callId = callId, phase = phase.name, isVideo = video, |
| 258 | ), |
| 259 | ) |
| 260 | } |
| 261 | |
| 262 | private fun endCall(callId: String, reason: String) { |
| 263 | val duration = if (callStartMs > 0) (System.currentTimeMillis() - callStartMs) / 1000 else 0L |
| 264 | cleanup() |
| 265 | _state.value = WhatsAppCallState(phase = WhatsAppCallPhase.Ended, callId = callId) |
| 266 | bridge?.emit( |
| 267 | com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallEnded( |
| 268 | callId = callId, reason = reason, durationSeconds = duration, |
| 269 | ), |
| 270 | ) |
| 271 | } |
| 272 | |
| 273 | private fun fail(callId: String, reason: String) { |
| 274 | Log.error(TAG, "call $callId failed: $reason") |
| 275 | endCall(callId, reason) |
| 276 | } |
| 277 | |
| 278 | private fun cleanup() { |
| 279 | runCatching { session?.close() } |
| 280 | session = null |
| 281 | callKey = null |
| 282 | pendingRemoteSdp = null |
| 283 | callStartMs = 0L |
| 284 | } |
| 285 | |
| 286 | /** Reset to Idle once the UI consumed the terminal state. */ |
| 287 | fun clearEnded() { |
| 288 | if (_state.value.phase == WhatsAppCallPhase.Ended) _state.value = WhatsAppCallState() |
| 289 | } |
| 290 | } |