Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalCalls.kt

SignalCalls.kt308 lines · 13.2 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.communicate.data.CommunicateLine
5import com.vayunmathur.communicate.data.call.CallCapabilities
6import com.vayunmathur.communicate.data.call.InAppCallPhase
7import com.vayunmathur.communicate.data.call.InAppCallRegistry
8import com.vayunmathur.communicate.data.signal.call.SignalCallManager
9import com.vayunmathur.communicate.data.signal.call.accept
10import com.vayunmathur.communicate.data.signal.call.ensureInitialized
11import com.vayunmathur.communicate.data.signal.call.hangup
12import com.vayunmathur.communicate.data.signal.call.placeCall
13import com.vayunmathur.communicate.data.signal.call.setAudioEnabled
14import com.vayunmathur.communicate.data.signal.call.receivedAnswer
15import com.vayunmathur.communicate.data.signal.call.receivedBusy
16import com.vayunmathur.communicate.data.signal.call.receivedHangup
17import com.vayunmathur.communicate.data.signal.call.receivedIceCandidates
18import com.vayunmathur.communicate.data.signal.call.receivedOffer
19import com.vayunmathur.communicate.data.signal.call.toRingRtc
20import com.vayunmathur.communicate.data.call.InAppCallSystemBridge
21import kotlinx.coroutines.launch
22import org.whispersystems.signalservice.internal.push.SignalServiceProtos
23
24/**
25 * SignalClient 1:1 + group calling (split from SignalClient.kt for file length).
26 *
27 * Extension functions on [SignalClient]; behavior identical, call sites unchanged.
28 * The RingRTC bridge instances ([SignalClient.callManager] etc.) stay in core —
29 * extension properties cannot hold state.
30 */
31
32/**
33 * Hand an inbound `CallMessage` to RingRTC, which owns the call state machine.
34 *
35 * `destinationDeviceId` is application-level addressing: the server fans out to every device, so a
36 * message meant for a different one of our devices must be ignored here.
37 */
38internal suspend fun SignalClient.handleCallMessage(
39 cm: SignalServiceProtos.CallMessage,
40 senderAci: String,
41 senderDeviceId: Int,
42 env: SignalProtocol.SignalEnvelope,
43 timestamp: Long,
44) {
45 val localDeviceId = authData?.deviceId ?: PRIMARY_DEVICE_ID
46 if (cm.hasDestinationDeviceId() && cm.destinationDeviceId != localDeviceId) return
47 val manager = callManager ?: run {
48 Log.status(TAG, "RingRTC unavailable, dropping a call message from $senderAci")
49 return
50 }
51 // Ensure the native stack is up before feeding anything in.
52 val localAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return
53 if (manager.ensureInitialized(localAci) == null) return
54
55 when {
56 cm.hasOffer() -> handleCallOffer(cm, senderAci, senderDeviceId, env, timestamp, manager, localDeviceId)
57 cm.hasAnswer() -> manager.receivedAnswer(
58 callId = cm.answer.id,
59 senderAci = senderAci,
60 senderDeviceId = senderDeviceId,
61 opaque = cm.answer.opaque.toByteArray(),
62 )
63 cm.iceUpdateCount > 0 -> {
64 // A batch shares one call id.
65 val callId = cm.iceUpdateList.first().id
66 manager.receivedIceCandidates(
67 callId = callId,
68 senderAci = senderAci,
69 senderDeviceId = senderDeviceId,
70 candidates = cm.iceUpdateList.map { it.opaque.toByteArray() },
71 )
72 }
73 cm.hasHangup() -> {
74 manager.receivedHangup(
75 callId = cm.hangup.id,
76 senderAci = senderAci,
77 senderDeviceId = senderDeviceId,
78 type = cm.hangup.type.toRingRtc(),
79 deviceId = cm.hangup.deviceId,
80 )
81 eventsMutable.emit(SignalEvent.CallEnded(callId = cm.hangup.id.toString(), reason = "hangup"))
82 }
83 cm.hasBusy() -> {
84 manager.receivedBusy(cm.busy.id, senderAci, senderDeviceId)
85 eventsMutable.emit(SignalEvent.CallEnded(callId = cm.busy.id.toString(), reason = "busy"))
86 }
87 cm.hasOpaque() -> Log.status(TAG, "ignoring an opaque call message (group calling not implemented)")
88 }
89}
90
91/** Inbound offer: log, emit, hand to telecom + RingRTC. */
92private suspend fun SignalClient.handleCallOffer(
93 cm: SignalServiceProtos.CallMessage,
94 senderAci: String,
95 senderDeviceId: Int,
96 env: SignalProtocol.SignalEnvelope,
97 timestamp: Long,
98 manager: SignalCallManager,
99 localDeviceId: Int,
100) {
101 val offer = cm.offer
102 val isVideo = offer.type == SignalServiceProtos.CallMessage.Offer.Type.OFFER_VIDEO_CALL
103 // Logged in full so an inbound offer from official Signal can be compared against what we
104 // send: our own offers are accepted by the server but never ring, and our side reports
105 // success, so the difference has to be in the message itself.
106 val ageSec = ((env.serverTimestamp - env.timestamp).coerceAtLeast(0L)) / 1000
107 Log.status(
108 TAG,
109 "inbound Offer callId=${offer.id} from $senderAci:$senderDeviceId " +
110 "opaque=${offer.opaque.size()}B type=${offer.type} " +
111 "hasDestinationDeviceId=${cm.hasDestinationDeviceId()} " +
112 "destinationDeviceId=${cm.destinationDeviceId} ageSec=$ageSec " +
113 "urgent=${env.urgent}",
114 )
115 // Recorded before RingRTC reports Ringing, which is how the shared registry tells an
116 // inbound call from an outbound one, and what `answer()` needs.
117 pendingIncomingCallAci = senderAci
118 pendingIncomingCallId = offer.id
119 eventsMutable.emit(
120 SignalEvent.CallOffer(
121 callId = offer.id.toString(),
122 from = senderAci,
123 callCreator = senderAci,
124 isVideo = isVideo,
125 peerName = displayNameFor(senderAci),
126 timestamp = timestamp,
127 ),
128 )
129 // Hand the call to the system so it owns ringing, audio focus and routing.
130 appContext?.let { ctx -> InAppCallSystemBridge.addIncoming(ctx, senderAci) }
131 // Telecom can silently drop the mirror (no failure callback); the ringing surface still
132 // has to come up, so start it directly as well. Idempotent with the ConnectionService path.
133 appContext?.let { ctx ->
134 runCatching {
135 InAppCallSystemBridge.startForegroundService(ctx)
136 }
137 }
138 manager.receivedOffer(
139 callId = offer.id,
140 senderAci = senderAci,
141 senderDeviceId = senderDeviceId,
142 localDeviceId = localDeviceId,
143 opaque = offer.opaque.toByteArray(),
144 messageAgeSec = ageSec,
145 video = isVideo,
146 )
147}
148
149/**
150 * Mirror RingRTC's state into the shared call registry, which is what the call screen and the system
151 * call surface read. Registered lazily on the first state change so the controller is bound before the
152 * UI can act on it.
153 */
154internal suspend fun SignalClient.publishCallState(
155 aci: String,
156 state: SignalCallManager.CallState,
157 isVideo: Boolean,
158) {
159 val current = InAppCallRegistry.state.value
160 if (current.phase == InAppCallPhase.Idle && state != SignalCallManager.CallState.Ended) {
161 InAppCallRegistry.bind(
162 CommunicateLine.Signal,
163 signalCallController,
164 CallCapabilities.AudioAndVideo,
165 )
166 InAppCallRegistry.videoController = signalVideoController
167 InAppCallRegistry.onCallStarting(
168 line = CommunicateLine.Signal,
169 peerId = aci,
170 peerName = displayNameFor(aci),
171 isVideo = isVideo,
172 // RingRTC reports Ringing for both directions; an inbound call already has an offer
173 // recorded, which is how we tell them apart.
174 incoming = pendingIncomingCallAci == aci,
175 capabilities = CallCapabilities.AudioAndVideo,
176 )
177 }
178 when (state) {
179 SignalCallManager.CallState.Ringing ->
180 if (pendingIncomingCallAci == aci) {
181 InAppCallRegistry.onPhase(InAppCallPhase.Incoming)
182 } else {
183 InAppCallRegistry.onPhase(InAppCallPhase.Outgoing)
184 }
185 SignalCallManager.CallState.Connecting -> InAppCallRegistry.onPhase(InAppCallPhase.Connecting)
186 SignalCallManager.CallState.Connected -> InAppCallRegistry.onPhase(InAppCallPhase.Active)
187 SignalCallManager.CallState.Ended -> {
188 InAppCallRegistry.onEnded(null)
189 pendingIncomingCallAci = null
190 }
191 }
192}
193
194internal suspend fun SignalClient.emitCallState(
195 callId: Long,
196 state: SignalCallManager.CallState,
197 isVideo: Boolean,
198) {
199 val id = callId.toString()
200 when (state) {
201 SignalCallManager.CallState.Ringing ->
202 eventsMutable.emit(SignalEvent.CallStateChanged(callId = id, phase = "ringing", isVideo = isVideo))
203 SignalCallManager.CallState.Connecting ->
204 eventsMutable.emit(SignalEvent.CallStateChanged(callId = id, phase = "connecting", isVideo = isVideo))
205 SignalCallManager.CallState.Connected ->
206 eventsMutable.emit(SignalEvent.CallStateChanged(callId = id, phase = "connected", isVideo = isVideo))
207 SignalCallManager.CallState.Ended ->
208 eventsMutable.emit(SignalEvent.CallEnded(callId = id, reason = "ended"))
209 }
210}
211
212/**
213 * Place a 1:1 call. Requires an established session with the recipient, since RingRTC needs both
214 * identity keys to derive the SRTP keys.
215 *
216 * The app addresses conversations by phone number, so the destination is resolved the same way a send
217 * is. A call needs an **ACI** specifically: a PNI-only contact cannot be called, because calling binds
218 * to the ACI identity. Their ACI arrives with their first message.
219 */
220fun SignalClient.placeCall(conversationId: String, video: Boolean) {
221 val localAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: run {
222 Log.status(TAG, "cannot call before registration")
223 return
224 }
225 val manager = callManager ?: run {
226 Log.status(TAG, "RingRTC unavailable, cannot place a call")
227 return
228 }
229 scope.launch {
230 val resolved = resolveDestinationAci(conversationId)
231 if (resolved == null) {
232 Log.status(TAG, "cannot call $conversationId: no Signal identity for it")
233 eventsMutable.emit(SignalEvent.CallEnded(callId = "", reason = "not a Signal user"))
234 return@launch
235 }
236 if (!ACI_REGEX.matches(resolved)) {
237 // A PNI is enough to message but not to call.
238 Log.status(TAG, "cannot call $resolved: calling needs an ACI, which arrives with their first message")
239 eventsMutable.emit(SignalEvent.CallEnded(callId = "", reason = "cannot call this contact yet"))
240 return@launch
241 }
242 val e = e2e
243 if (e == null || (!e.hasSession(resolved, PRIMARY_DEVICE_ID) && !establishSession(e, resolved))) {
244 Log.status(TAG, "no session with $resolved, cannot place a call")
245 eventsMutable.emit(SignalEvent.CallEnded(callId = "", reason = "no session"))
246 return@launch
247 }
248 manager.placeCall(localAci, authData?.deviceId ?: PRIMARY_DEVICE_ID, resolved, video)
249 // Mirror the call into the system so it owns audio focus and routing.
250 appContext?.let { ctx -> InAppCallSystemBridge.addOutgoing(ctx, resolved) }
251 }
252}
253
254fun SignalClient.acceptCall(callId: String): Boolean {
255 val id = callId.toLongOrNull() ?: return false
256 return callManager?.accept(id) ?: false
257}
258
259suspend fun SignalClient.rejectCall(callId: String): Boolean {
260 // RingRTC turns this into the right hangup type and tells us what to send.
261 val ok = callManager?.hangup() ?: false
262 if (!ok) eventsMutable.emit(SignalEvent.CallEnded(callId = callId, reason = "rejected"))
263 return true
264}
265
266fun SignalClient.endCall(): Boolean = callManager?.hangup() ?: false
267
268fun SignalClient.setCallAudioEnabled(enabled: Boolean): Boolean =
269 callManager?.setAudioEnabled(enabled) ?: false
270
271/**
272 * Start or join the group call for [conversationId].
273 *
274 * Needs the group's membership, which is why it refreshes first: RingRTC cannot identify participants
275 * without every member's ACI ciphertext.
276 */
277suspend fun SignalClient.placeGroupCall(conversationId: String): Boolean {
278 if (!SignalProtocol.isGroupConversation(conversationId)) return false
279 val manager = groupCallManager ?: run {
280 Log.status(TAG, "RingRTC unavailable, cannot place a group call")
281 return false
282 }
283 val conversation = try { db?.conversationDao()?.getConversation(conversationId) } catch (_: Exception) { null }
284 val masterKey = conversation?.groupMasterKey ?: run {
285 Log.status(TAG, "no master key for $conversationId, cannot place a group call")
286 return false
287 }
288 // Membership must be current or participants cannot be matched to people.
289 refreshGroup(conversationId)
290 val groupIdentifier = SignalGroups.groupIdentifierBytes(masterKey) ?: return false
291
292 InAppCallRegistry.bind(CommunicateLine.Signal, signalCallController, CallCapabilities.AudioAndVideo)
293 InAppCallRegistry.onCallStarting(
294 line = CommunicateLine.Signal,
295 peerId = conversationId,
296 peerName = conversation.name ?: conversationId,
297 isVideo = false,
298 incoming = false,
299 capabilities = CallCapabilities.AudioAndVideo,
300 )
301 if (!manager.connect(groupIdentifier)) {
302 InAppCallRegistry.onEnded("could not start the group call")
303 return false
304 }
305 manager.join()
306 appContext?.let { ctx -> InAppCallSystemBridge.addOutgoing(ctx, conversationId) }
307 return true
308}