Modern Apps git

← Modern-Apps.git

communicate: add a call button to the conversation screen, with Signal TURN relays

Commit
abeb0369042b127d429e0cb5c401cf6f382d315e
Author
vayun-mathur <[email protected]>
When
2026-08-22 22:17 UTC (3 months ago)
Parents
ad3faa3

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 9439b1a889..5f677cd2a5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -1352,6 +1352,51 @@ object CommunicateRepository {         SignalClient.acceptIdentityChange(aci, keyHex)     } +    /**+     * Place a voice call on [line] for a conversation.+     *+     * SIM and Google Voice go through Telecom; WhatsApp and Signal are in-app WebRTC calls addressed by+     * conversation id. Returns false when the line cannot place the call, so the caller can say so rather+     * than appear to succeed.+     */+    suspend fun placeCallForLine(+        context: Context,+        line: CommunicateLine,+        address: String,+        remoteId: String?,+        video: Boolean = false,+    ): Boolean = when (line) {+        CommunicateLine.Sim -> {+            placeCall(context, choice = null, number = address)+            true+        }+        CommunicateLine.GoogleVoice -> {+            placeCall(context, choice = LineChoice.GoogleVoice, number = address)+            true+        }+        CommunicateLine.WhatsApp -> {+            val target = remoteId ?: address+            if (target.isBlank()) false else { whatsAppPlaceCall(target, video); true }+        }+        CommunicateLine.Signal -> withContext(Dispatchers.IO) {+            val target = remoteId?.takeIf { it.isNotBlank() } ?: toSignalRecipient(context, address)+            if (target.isBlank()) {+                false+            } else {+                SignalClient.get(context).placeCall(target, video)+                true+            }+        }+    }++    /** Whether [line] can place a call at all, so the UI can hide the affordance instead of failing. */+    fun canPlaceCall(line: CommunicateLine): Boolean = when (line) {+        CommunicateLine.Sim -> true+        CommunicateLine.GoogleVoice -> true+        CommunicateLine.WhatsApp -> com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled+        CommunicateLine.Signal -> com.vayunmathur.communicate.data.signal.SignalFeature.enabled+    }+     suspend fun createSignalGroup(         context: Context,         subject: String,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex bb876ee0da..8d8e8e1aba 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -9,6 +9,7 @@ import com.vayunmathur.communicate.data.signal.call.SignalCallMessage import com.vayunmathur.communicate.data.signal.call.toContent import com.vayunmathur.communicate.data.signal.call.toRingRtc import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload+import com.vayunmathur.communicate.data.signal.transport.SignalCallingApi import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi import com.vayunmathur.communicate.data.signal.transport.SignalPayload import com.vayunmathur.communicate.data.signal.transport.SignalSocket@@ -18,6 +19,7 @@ import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.UntrustedIdentityException import org.signal.libsignal.protocol.message.DecryptionErrorMessage import org.signal.libsignal.protocol.message.PlaintextContent+import org.webrtc.PeerConnection import com.vayunmathur.library.network.NetworkClient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -1227,6 +1229,9 @@ object SignalClient {                     )                 } +                override suspend fun iceServers(): List<PeerConnection.IceServer> =+                    SignalCallingApi.fetchIceServers(basicAuthHeader(), signalTls())+                 override fun onCallStateChanged(                     aci: String,                     callId: Long,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.ktindex 7a1300e73b..62130742e3 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt@@ -58,6 +58,12 @@ class SignalCallManager(         /** The identity keys RingRTC binds the SRTP key derivation to. */         suspend fun identityKeys(aci: String): IdentityKeyPairBytes? +        /**+         * TURN/STUN relays for the call. Without them only host candidates are available, so a call fails+         * behind NAT.+         */+        suspend fun iceServers(): List<PeerConnection.IceServer>+         fun onCallStateChanged(aci: String, callId: Long, state: CallState, isVideo: Boolean)     } @@ -207,13 +213,23 @@ class SignalCallManager(         val mediaType = callMediaType ?: CallManager.CallMediaType.AUDIO_CALL         callMediaTypes[id] = mediaType         signaling.onCallStateChanged(aci, id, CallState.Ringing, mediaType.isVideo())-        // RingRTC waits for proceed() before touching media.-        proceed(id, mediaType)+        // RingRTC waits for proceed() before touching media, and proceed() needs relays, so both happen+        // off the callback thread.+        scope.launch { proceed(id, mediaType) }     } -    private fun proceed(callId: Long, mediaType: CallManager.CallMediaType) {+    private suspend fun proceed(callId: Long, mediaType: CallManager.CallMediaType) {         val manager = callManager ?: return         val egl = eglBase ?: return+        val iceServers = try {+            signaling.iceServers()+        } catch (t: Throwable) {+            Log.w(TAG, "could not fetch ICE servers; the call will likely fail behind NAT", t)+            emptyList()+        }+        if (iceServers.isEmpty()) {+            Log.w(TAG, "proceeding with no ICE servers; expect connection failure unless both ends are local")+        }         try {             manager.proceed(                 CallId(callId),@@ -224,9 +240,7 @@ class SignalCallManager(                 NoVideoSink,                 NoVideoSink,                 NoCameraControl,-                // TURN servers come from GET /v2/calling/relays, which is not wired up; with an empty-                // list only host and STUN-less candidates are available, so calls will fail behind NAT.-                emptyList<PeerConnection.IceServer>(),+                iceServers,                 false,                 CallManager.DataMode.NORMAL,                 AUDIO_LEVEL_INTERVAL_MS,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCallingApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCallingApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCallingApi.ktnew file mode 100644index 0000000000..31e2acdf07--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCallingApi.kt@@ -0,0 +1,87 @@+package com.vayunmathur.communicate.data.signal.transport++import android.util.Log+import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.webrtc.PeerConnection+import javax.net.ssl.SSLSocketFactory++/**+ * TURN/STUN relays for calling (`GET /v2/calling/relays`).+ *+ * Without these a call can only use host candidates, so it connects on a shared LAN and fails behind any+ * NAT — which is most real networks. The credentials are short-lived (the response carries a ttl), so they+ * are fetched per call rather than cached.+ */+object SignalCallingApi {+    private const val TAG = "SignalCallingApi"++    private val json = Json { ignoreUnknownKeys = true }++    suspend fun fetchIceServers(+        authHeader: String,+        sslSocketFactory: SSLSocketFactory?,+    ): List<PeerConnection.IceServer> {+        val resp = try {+            NetworkClient.execute(+                "https://chat.signal.org/v2/calling/relays",+                method = "GET",+                headers = mapOf("Authorization" to "Basic $authHeader"),+                sslSocketFactory = sslSocketFactory,+            )+        } catch (t: Throwable) {+            Log.w(TAG, "could not fetch calling relays", t)+            return emptyList()+        }+        if (!resp.isSuccess) {+            Log.w(TAG, "calling relays request failed: ${resp.status} ${resp.statusMessage}")+            return emptyList()+        }+        val servers = parseRelays(resp.text)+        Log.i(TAG, "fetched ${servers.size} ICE servers")+        return servers+    }++    internal fun parseRelays(+        body: String,+        warn: (String) -> Unit = { Log.w(TAG, it) },+    ): List<PeerConnection.IceServer> {+        val relays = try {+            json.parseToJsonElement(body).jsonObject["relays"]?.jsonArray+        } catch (e: Exception) {+            warn("unparseable calling relays response: ${e.message}")+            return emptyList()+        } ?: return emptyList()++        return relays.mapNotNull { element ->+            val relay = try { element.jsonObject } catch (_: Exception) { return@mapNotNull null }+            val username = relay["username"]?.jsonPrimitive?.contentOrNull()+            val password = relay["password"]?.jsonPrimitive?.contentOrNull()+            // Prefer urlsWithIps: they skip a DNS lookup, which matters on a call setup path.+            val urls = (relay["urlsWithIps"] ?: relay["urls"])?.let { urlsElement ->+                try { urlsElement.jsonArray.mapNotNull { it.jsonPrimitive.contentOrNull() } } catch (_: Exception) { null }+            }?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null+            val hostname = relay["hostname"]?.jsonPrimitive?.contentOrNull()++            try {+                PeerConnection.IceServer.builder(urls)+                    .apply {+                        if (username != null) setUsername(username)+                        if (password != null) setPassword(password)+                        // Needed when connecting to an IP while the certificate names the host.+                        if (!hostname.isNullOrEmpty()) setHostname(hostname)+                    }+                    .createIceServer()+            } catch (t: Throwable) {+                warn("skipping an unusable ICE server: ${t.message}")+                null+            }+        }+    }++    private fun kotlinx.serialization.json.JsonPrimitive.contentOrNull(): String? =+        content.takeIf { it.isNotEmpty() && it != "null" }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex beaa3d5d66..81aa0b9a5d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -285,6 +285,21 @@ fun ConversationScreen(                     onDismiss = { showDeleteConfirm = false },                 )             }+            // Calling is per line: SIM and Google Voice hand off to Telecom, WhatsApp and Signal place an+            // in-app WebRTC call. Groups are excluded — group calling is not implemented on either line.+            if (!isGroup && address.isNotBlank() && CommunicateRepository.canPlaceCall(line)) {+                IconButton(onClick = {+                    scope.launch {+                        val placed = CommunicateRepository.placeCallForLine(+                            context = context,+                            line = line,+                            address = address,+                            remoteId = remoteId,+                        )+                        if (!placed) AppMessages.show(context.getString(R.string.call_failed))+                    }+                }) { com.vayunmathur.library.ui.IconCall() }+            }             if (line == CommunicateLine.GoogleVoice && remoteId != null) {                 IconButton(onClick = {                     scope.launch {
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex 022db2afa1..e115fd0b21 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -112,4 +112,5 @@     <string name="signal_safety_number_verify_prompt">Compare this number with them in person or over a call you trust before accepting.</string>     <string name="signal_safety_number_accept">Accept new safety number</string>     <string name="signal_safety_number_accept_failed">Could not accept the new safety number</string>+    <string name="call_failed">Could not start the call</string> </resources>
communicate/src/test/java/com/vayunmathur/communicate/signal/SignalCallingApiTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalCallingApiTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalCallingApiTest.ktnew file mode 100644index 0000000000..5e64b18ffe--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalCallingApiTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.communicate.signal++import com.vayunmathur.communicate.data.signal.transport.SignalCallingApi+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Parser vectors for `GET /v2/calling/relays`. A relay without usable urls has to be dropped rather than+ * turned into an ICE server that fails at connection time.+ */+class SignalCallingApiTest {+    private fun parse(body: String) = SignalCallingApi.parseRelays(body, warn = {})++    @Test+    fun parsesCredentialsAndUrls() {+        val servers = parse(+            """+            {"relays":[{"username":"u","password":"p","hostname":"turn.example",+             "urls":["turn:turn.example:80"],"urlsWithIps":["turn:1.2.3.4:80"],"ttl":86400}]}+            """.trimIndent(),+        )+        assertEquals(1, servers.size)+        assertEquals("u", servers[0].username)+        assertEquals("p", servers[0].password)+    }++    @Test+    fun prefersUrlsWithIpsToAvoidADnsLookupDuringSetup() {+        val servers = parse(+            """{"relays":[{"username":"u","password":"p","urls":["turn:host:80"],"urlsWithIps":["turn:9.9.9.9:80"]}]}""",+        )+        assertTrue(servers[0].urls.any { it.contains("9.9.9.9") })+    }++    @Test+    fun fallsBackToUrlsWhenNoIpsAreGiven() {+        val servers = parse("""{"relays":[{"username":"u","password":"p","urls":["turn:host:80"]}]}""")+        assertTrue(servers[0].urls.any { it.contains("host") })+    }++    @Test+    fun dropsRelaysWithNoUrls() {+        assertTrue(parse("""{"relays":[{"username":"u","password":"p"}]}""").isEmpty())+        assertTrue(parse("""{"relays":[{"username":"u","password":"p","urls":[]}]}""").isEmpty())+    }++    @Test+    fun handlesMultipleRelays() {+        val servers = parse(+            """+            {"relays":[{"username":"a","password":"b","urls":["turn:one:80"]},+                       {"username":"c","password":"d","urls":["turn:two:80"]}]}+            """.trimIndent(),+        )+        assertEquals(2, servers.size)+    }++    @Test+    fun emptyOrJunkGivesNoServers() {+        assertTrue(parse("""{"relays":[]}""").isEmpty())+        assertTrue(parse("""{}""").isEmpty())+        assertTrue(parse("not json").isEmpty())+        assertTrue(parse("").isEmpty())+    }+}