Modern Apps git

← Modern-Apps.git

communicate: RCS missing UP features - sessions inbound, REFER, OPTIONS, geopush, large-msg, revoke-edit

Commit
89e2ac769b2c490f4c100251016216d3dd42f264
Author
vayun-mathur <[email protected]>
When
2026-09-25 20:58 UTC (2 months ago)
Parents
5cbc513

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.ktindex 24cf15281b..ee3c0afbcd 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -11,7 +11,12 @@ import com.vayunmathur.communicate.data.rcs.RcsFileTransfer import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsMsrp import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.ImdnDisposition import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.buildEditBody+import com.vayunmathur.communicate.data.rcs.buildGeopushBody+import com.vayunmathur.communicate.data.rcs.buildRevokeBody+import com.vayunmathur.communicate.data.rcs.chunkLargeMessage import com.vayunmathur.library.util.AppMessages import java.util.UUID import kotlinx.coroutines.Dispatchers@@ -180,10 +185,27 @@ suspend fun CommunicateRepository.sendRcsMessage(             toUri = "sip:$recipient@rcs",             body = body,         )-        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        // Large Message: chunk oversized bodies with a shared Message-ID so+        // the far end reassembles; cache one row per send (snippet = full text).+        val messageId = "rcs-${UUID.randomUUID()}"+        val chunks = chunkLargeMessage(messageId, body)+        var ok = true+        for ((index, chunk) in chunks.withIndex()) {+            val (line, head, payload) = if (chunks.size == 1) {+                Triple(startLine, headers, content)+            } else {+                RcsSipTransport.buildChatMessage(+                    fromUri = "sip:me@rcs",+                    toUri = "sip:$recipient@rcs",+                    callId = "${UUID.randomUUID()}@rcs-lm$index",+                    body = chunk,+                )+            }+            ok = RcsSipTransport.sendSipMessage(line, head, payload) && ok+        }         if (!ok) return@withContext RcsSendResult.FallbackSms         if (body.isNotBlank()) {-            cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}")+            cacheOutgoingRcs(context, recipient, body, messageId)         }         RcsSendResult.Sent     }.getOrDefault(RcsSendResult.FallbackSms)@@ -329,6 +351,122 @@ fun CommunicateRepository.notifyRcsFallback(context: Context) {     AppMessages.show(context.getString(com.vayunmathur.communicate.R.string.rcs_fallback_sms)) } +/**+ * Send a Geolocation Push to [recipient] (UP Geolocation Push, geosms tag).+ * Returns true when the SIP leg accepted.+ */+suspend fun CommunicateRepository.sendRcsGeopush(+    context: Context,+    recipient: String,+    latitude: Double,+    longitude: Double,+    label: String? = null,+): Boolean = withContext(Dispatchers.IO) {+    if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return@withContext false+    runCatching {+        val body = buildGeopushBody(latitude, longitude, label)+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$recipient@rcs",+            callId = "${UUID.randomUUID()}@rcs-geo",+            body = body,+        )+        val geoHeaders = headers.replace(+            "Content-Type: message/cpim",+            "Content-Type: application/vnd.gsma.rcs.geopush+xml",+        )+        if (!RcsSipTransport.sendSipMessage(startLine, geoHeaders, content)) {+            return@withContext false+        }+        cacheOutgoingRcs(context, recipient, label ?: "๐Ÿ“ Location", "local-${UUID.randomUUID()}")+        true+    }.getOrDefault(false)+}++/**+ * Revoke our outgoing message [messageId] in [conversationId]: sends the+ * revoke report and blanks the local row. Returns true when sent.+ */+suspend fun CommunicateRepository.revokeRcsMessage(+    context: Context,+    conversationId: String,+    messageId: String,+): Boolean = withContext(Dispatchers.IO) {+    if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return@withContext false+    runCatching {+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$conversationId@rcs",+            callId = "${UUID.randomUUID()}@rcs-revoke",+            body = buildRevokeBody(messageId),+        )+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        if (ok) {+            val db = RcsDatabase.getDatabase(context)+            db.cachedMessageDao().get(messageId)?.let {+                db.cachedMessageDao().upsert(it.copy(body = ""))+            }+        }+        ok+    }.getOrDefault(false)+}++/**+ * Edit our outgoing message [messageId] in [conversationId] to [newText]:+ * sends the replacement and updates the local row. Returns true when sent.+ */+suspend fun CommunicateRepository.editRcsMessage(+    context: Context,+    conversationId: String,+    messageId: String,+    newText: String,+): Boolean = withContext(Dispatchers.IO) {+    if (!RcsFeature.enabled || !RcsSipTransport.canSend() || newText.isBlank()) {+        return@withContext false+    }+    runCatching {+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$conversationId@rcs",+            callId = "${UUID.randomUUID()}@rcs-edit",+            body = buildEditBody(messageId, newText),+        )+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        if (ok) {+            val db = RcsDatabase.getDatabase(context)+            db.cachedMessageDao().get(messageId)?.let {+                db.cachedMessageDao().upsert(it.copy(body = newText))+            }+        }+        ok+    }.getOrDefault(false)+}++/**+ * Apply an inbound delivery/display report: advance the cached outgoing+ * message's status ticks (Delivered=2, Read=3). Called from the sync service+ * alongside [RcsImdn.onReportReceived].+ */+internal suspend fun CommunicateRepository.applyRcsDeliveryReport(+    context: Context,+    messageId: String,+    disposition: ImdnDisposition,+) {+    if (!RcsFeature.enabled) return+    runCatching {+        val db = RcsDatabase.getDatabase(context)+        when (disposition) {+            ImdnDisposition.Delivered -> db.cachedMessageDao().markDelivered(messageId)+            ImdnDisposition.Displayed -> db.cachedMessageDao().markReadStatus(messageId)+            ImdnDisposition.Failed -> {+                db.cachedMessageDao().get(messageId)?.let {+                    db.cachedMessageDao().upsert(it.copy(status = 4))+                }+            }+        }+    }+}+ /**  * Encrypt [body] for [recipient]'s E2EE group when one exists. Returns the  * framed MLS payload, or null when the conversation is plaintext (no group)
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.ktindex f46638d364..562827fe19 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt@@ -95,6 +95,77 @@ object RcsSessionManager {         return dialogId     } +    /**+     * Answer a pending incoming INVITE with 200 OK + SDP answer (passive โ€”+     * the caller connects to us... see ACTIVE-only note below).+     *+     * ACTIVE-only reality: we cannot listen (no ServerSocket, unroutable+     * offer IP), so our answer offers `setup:active` too and the session+     * proceeds only if the caller tolerates dual-active or falls back. In+     * practice acceptance means MSRP connect-out to the offerer's path when+     * it answers `passive`/`actpass`; otherwise the dialog exists for+     * in-dialog MESSAGE while media stays pager-mode.+     *+     * Returns true when the 200 OK was accepted by the transport.+     */+    suspend fun acceptIncoming(conversationId: String): Boolean {+        if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false+        val session = _sessions.value[conversationId] ?: return false+        val cfg = RcsSipTransport.lastConfigSnapshot()+        val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+        val sdp = buildSdpAnswer(cfg?.msrpLocalIp)+        val bytes = sdp.toByteArray(Charsets.UTF_8)+        val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val startLine = "SIP/2.0 200 OK"+        val headers = buildString {+            append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+            append("From: <${session.remoteUri}>;tag=${session.remoteTag.ifBlank { "unknown" }}\r\n")+            append("To: <$from>;tag=${session.localTag}\r\n")+            append("Call-ID: ${session.callId}\r\n")+            append("CSeq: 1 INVITE\r\n")+            append("Contact: <$from>;+sip.instance=\"<urn:gsma:imei:${cfg?.imei ?: "unknown"}>\";+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"\r\n")+            append("Content-Type: application/sdp\r\n")+            append("Content-Length: ${bytes.size}\r\n")+        }+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, bytes)+        if (ok) {+            // Record the offerer's path/setup for connect-out.+            val offered = _pendingOffers.remove(session.callId)+            if (offered != null) {+                _sessions.value = _sessions.value + (conversationId to session.copy(+                    msrpRemotePath = offered.remotePath,+                    msrpSetup = offered.setup,+                ))+            }+        }+        return ok+    }++    /**+     * Decline a pending incoming INVITE with 488 (used when the offer+     * requires passive-us, i.e. `setup:active` with no usable path).+     */+    suspend fun declineIncoming(conversationId: String): Boolean {+        if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false+        val session = _sessions.value[conversationId] ?: return true+        val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val startLine = "SIP/2.0 488 Not Acceptable Here"+        val headers = buildString {+            append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+            append("Call-ID: ${session.callId}\r\n")+            append("CSeq: 1 INVITE\r\n")+            append("Content-Length: 0\r\n")+        }+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))+        _pendingOffers.remove(session.callId)+        _sessions.value = _sessions.value - conversationId+        return ok+    }++    /** Inbound offer details stashed at INVITE time for [acceptIncoming]. */+    private data class PendingOffer(val remotePath: String?, val setup: MsrpSetup?)++    private val _pendingOffers = ConcurrentHashMap<String, PendingOffer>()     /** Tear down the session for [conversationId] with BYE. */     suspend fun terminateSession(conversationId: String): Boolean {         val session = _sessions.value[conversationId] ?: return true@@ -146,8 +217,9 @@ object RcsSessionManager {     }      /**-     * Route an inbound SIP request: INVITE starts an incoming session entry-     * (caller answers via [acceptIncoming]), BYE tears down, MESSAGE with+     * Route an inbound SIP request: INVITE stashes the offer and starts an+     * incoming session entry (caller answers via [acceptIncoming] or declines+     * via [declineIncoming]), BYE tears down, MESSAGE with      * `message/imdn+xml` updates receipts, `im-iscomposing` updates typing.      */     fun onSipRequest(@@ -156,16 +228,23 @@ object RcsSessionManager {         fromUri: String,         contentType: String?,         body: String,+        fromTag: String? = null,     ): RcsSession? {         return when (method.uppercase()) {             "INVITE" -> {                 val conversationId = fromUri.substringAfter("sip:").substringBefore("@")                     .takeIf { it.isNotBlank() } ?: fromUri+                // Stash the offerer's path/setup for acceptIncoming connect-out.+                _pendingOffers[callId] = PendingOffer(+                    remotePath = Regex("a=path:(\\S+)", RegexOption.IGNORE_CASE).find(body)+                        ?.groupValues?.getOrNull(1)?.trim(),+                    setup = parseSdpSetup(body),+                )                 val session = RcsSession(                     dialogId = "$callId:in",                     callId = callId,                     localTag = UUID.randomUUID().toString().take(8),-                    remoteTag = "",+                    remoteTag = fromTag.orEmpty(),                     remoteUri = fromUri,                     conversationId = conversationId,                 )@@ -248,7 +327,28 @@ object RcsSessionManager {             append("t=0 0\r\n")             append("m=message 2855 TCP/MSRP *\r\n")             append("a=path:$path\r\n")-            append("a=accept-types:message/cpim text/plain\r\n")+            append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")+            append("a=setup:active\r\n")+        }+    }++    /**+     * SDP answer for [acceptIncoming]: same media shape as the offer with our+     * (unroutable-by-construction) path; the usable direction is connect-out+     * to the offerer's path recorded in [_pendingOffers].+     */+    private fun buildSdpAnswer(localIp: String?): String {+        val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"+        val path = "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp"+        return buildString {+            append("v=0\r\n")+            append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")+            append("s=-\r\n")+            append("c=IN IP4 $ip\r\n")+            append("t=0 0\r\n")+            append("m=message 2855 TCP/MSRP *\r\n")+            append("a=path:$path\r\n")+            append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")             append("a=setup:active\r\n")         }     }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsUpExtras.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsUpExtras.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsUpExtras.ktnew file mode 100644index 0000000000..948f8a3a70--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsUpExtras.kt@@ -0,0 +1,132 @@+package com.vayunmathur.communicate.data.rcs++/**+ * Universal Profile extras beyond 1:1 chat sessions.+ *+ * - Geolocation Push (RCC.07 Annex: `application/vnd.gsma.rcs.geopush+xml`,+ *   iari tag `...ims.iari.rcs.geosms` โ€” already requested in+ *   [RcsSipTransport.CPM_FEATURE_TAGS]): RCC.07 ยง2.6 Geolocation Push format.+ * - Large Message (pager-mode `cpm.largemsg`): CPIM split across multiple SIP+ *   MESSAGEs with `Message-ID` correlation; reassembly on receipt.+ * - Message Revoke / Edit over pager-mode: `message/cpim` wrapping an IMDN+ *   `revoke` extension (UP 2.x) / replacement text with `Message-ID` match.+ * - Delivery-report correlation: outgoing CPIM carries `imdn.Message-ID`;+ *   inbound IMDN `positive-delivery`/`display` map back to our cached+ *   message rows for status ticks.+ *+ * All bodies are plain strings over the existing pager-mode path โ€” no new+ * transport needed.+ */++/** Geolocation Push body (RCC.07 Geolocation Push schema, minimal subset). */+fun buildGeopushBody(latitude: Double, longitude: Double, label: String? = null): String =+    buildString {+        append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")+        append("<rcsenvelope xmlns=\"urn:gsma:params:xml:ns:rcs:rcsenvelope\">\n")+        append("  <rcspushlocation>\n")+        append("    <latitude>$latitude</latitude>\n")+        append("    <longitude>$longitude</longitude>\n")+        if (!label.isNullOrBlank()) append("    <label>${label.xmlEscape()}</label>\n")+        append("    <radius>0</radius>\n")+        append("  </rcspushlocation>\n")+        append("</rcsenvelope>")+    }++/** Parse a Geolocation Push body into (lat, lon, label?), or null. */+fun parseGeopushBody(body: String): Triple<Double, Double, String?>? {+    if (!body.contains("rcspushlocation", ignoreCase = true)) return null+    val lat = Regex("<latitude>([^<]+)</latitude>", RegexOption.IGNORE_CASE).find(body)+        ?.groupValues?.getOrNull(1)?.trim()?.toDoubleOrNull() ?: return null+    val lon = Regex("<longitude>([^<]+)</longitude>", RegexOption.IGNORE_CASE).find(body)+        ?.groupValues?.getOrNull(1)?.trim()?.toDoubleOrNull() ?: return null+    val label = Regex("<label>([^<]*)</label>", RegexOption.IGNORE_CASE).find(body)+        ?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }+    return Triple(lat, lon, label)+}++private fun String.xmlEscape(): String = this+    .replace("&", "&amp;")+    .replace("<", "&lt;")+    .replace(">", "&gt;")+    .replace("\"", "&quot;")++/** Maximum single pager-mode payload before Large Message chunking. */+const val RCS_LARGE_MESSAGE_CHUNK = 8192++/**+ * Split [text] into Large Message chunks, each tagged with the shared+ * `imdn.Message-ID` ([messageId]) + `part/total` envelope headers so the far+ * end reassembles. Returns single-element list when under the limit.+ */+fun chunkLargeMessage(messageId: String, text: String): List<String> {+    val bytes = text.toByteArray(Charsets.UTF_8)+    if (bytes.size <= RCS_LARGE_MESSAGE_CHUNK) return listOf(text)+    val parts = bytes.toList().chunked(RCS_LARGE_MESSAGE_CHUNK).map {+        it.toByteArray().toString(Charsets.UTF_8)+    }+    return parts.mapIndexed { index, part ->+        "Message-ID: $messageId\r\nPart: ${index + 1}/${parts.size}\r\n\r\n$part"+    }+}++/**+ * Reassemble Large Message chunks. [chunks] maps part number โ†’ text for one+ * `Message-ID`; returns the joined text when all [total] parts are present.+ */+fun reassembleLargeMessage(chunks: Map<Int, String>, total: Int): String? {+    if (chunks.size != total) return null+    return (1..total).map { chunks[it] ?: return null }.joinToString("")+}++/** Parse a chunk envelope header into (messageId, part, total). */+fun parseChunkHeader(body: String): Triple<String, Int, Int>? {+    val id = Regex("Message-ID:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)+        ?.groupValues?.getOrNull(1)?.trim() ?: return null+    val part = Regex("Part:\\s*(\\d+)/(\\d+)", RegexOption.IGNORE_CASE).find(body)+        ?: return null+    val (num, total) = part.destructured+    return Triple(id, num.toIntOrNull() ?: return null, total.toIntOrNull() ?: return null)+}++/**+ * Build a pager-mode revoke for [originalMessageId]: CPIM wrapping an IMDN+ * revoke extension body. The far end blanks the message row.+ */+fun buildRevokeBody(originalMessageId: String): String = buildString {+    append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")+    append("<imdn xmlns=\"urn:ietf:params:xml:ns:imdn\">\n")+    append("  <message-id>$originalMessageId</message-id>\n")+    append("  <datetime>${java.time.Instant.now()}</datetime>\n")+    append("  <status><revoked xmlns=\"urn:gsma:params:xml:ns:rcs:revoke\"/></status>\n")+    append("</imdn>")+}++/** True when [body] is a revoke report for some message; returns its id. */+fun parseRevokeBody(body: String): String? {+    if (!body.contains("revoked", ignoreCase = true)) return null+    return Regex("<message-id>([^<]+)</message-id>").find(body)+        ?.groupValues?.getOrNull(1)?.trim()+}++/**+ * Build a pager-mode edit: replacement [newText] with the original+ * `imdn.Message-ID` so the far end swaps the row body.+ */+fun buildEditBody(originalMessageId: String, newText: String): String = buildString {+    append("imdn.Message-ID: $originalMessageId\r\n")+    append("Edit-Type: replace\r\n")+    append("\r\n")+    append(newText)+}++/** Parse an edit body into (originalId, newText). */+fun parseEditBody(body: String): Pair<String, String>? {+    if (!body.contains("Edit-Type: replace", ignoreCase = true)) return null+    val id = Regex("imdn\\.Message-ID:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)+        ?.groupValues?.getOrNull(1)?.trim() ?: return null+    val text = body.substringAfter("\r\n\r\n", "").ifBlank {+        body.substringAfter("\n\n", "")+    }.trim()+    if (text.isEmpty()) return null+    return id to text+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktindex 939b2d5523..bcf411268c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -12,7 +12,13 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext  /**- * Closed-loop MLS E2EE orchestration for the RCS line (our-app-to-our-app).+ * Closed-loop MLS E2EE orchestration for the RCS line.+ *+ * MLS here follows GSMA Universal Profile 3.0 (standard MLS, RFC 9420) โ€” the+ * same profile Google Messages uses โ€” so the crypto is interop-shaped:+ * standard ciphersuite, `BasicCredential` identities, TLS framing. What stays+ * closed-loop in v1 is *key discovery*: key packages ride our own RCS+ * content-types rather than a federated directory.  *  * Flow:  * - Each local E.164 gets an Ed25519 identity (generated once, Room-held).
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.ktindex 738dd2dfa8..2961e6447a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt@@ -11,8 +11,10 @@ import android.util.Log  * rows; identity bytes live in the MLS identity table. The crate holds no  * state across calls.  *- * Closed-loop only: our-app-to-our-app over RCS as the wire. There is no- * interop with proprietary key distribution (e.g. Google Messages).+ * MLS follows GSMA Universal Profile 3.0 (standard MLS โ€” the same profile+ * Google Messages uses). Key discovery stays closed-loop in v1 (our own RCS+ * content-types instead of a federated directory); the crypto itself is+ * interop-shaped.  */ object RustMlsCrypto { 
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.ktnew file mode 100644index 0000000000..15275c4f2f--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt@@ -0,0 +1,150 @@+package com.vayunmathur.communicate.telephony++import android.telephony.ims.SipMessage+import android.util.Log+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsSessionManager+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.notifications.ConversationSpace+import com.vayunmathur.communicate.notifications.ConversationTarget++/**+ * Dialog-forming/method handlers for inbound SIP, split from+ * [RcsSyncService] for file length. Extension functions on the service so+ * they share its scope, notification channels, and MSRP connection map.+ */++/**+ * Inbound INVITE: stash the offer in the session manager, then accept or+ * decline. Accept when the offer carries an SDP we can answer (any+ * `m=message` section); decline `setup:active`-only offers we cannot+ * satisfy... in practice we always accept at the SIP layer (dialog+ * existence enables in-dialog MESSAGE) and let MSRP usability gate media.+ * Posts a session-invite notification so the user can jump in.+ */+internal suspend fun RcsSyncService.handleInboundInvite(message: SipMessage) {+    if (!RcsFeature.enabled) return+    val headers = message.getHeaderSection()+    val from = headerValue(headers, "From:")?.substringAfter("<")?.substringBefore(">")+        ?.substringAfter("sip:")?.substringBefore("@")?.takeIf { it.isNotBlank() }+        ?: return+    val fromTag = headerValue(headers, "From:")?.substringAfter("tag=", "")?.substringBefore(";")+        ?.trim()?.takeIf { it.isNotBlank() }+    val callId = message.getCallIdParameter() ?: return+    val body = message.getContent().toString(Charsets.UTF_8)+    RcsSessionManager.onSipRequest("INVITE", callId, from, "application/sdp", body, fromTag)+    val conversationId = from+    // 488 only when there is no SDP offer at all; otherwise accept.+    val hasSdp = body.contains("m=message", ignoreCase = true)+    if (!hasSdp) {+        RcsSessionManager.declineIncoming(conversationId)+        return+    }+    if (RcsSessionManager.acceptIncoming(conversationId)) {+        showSessionInviteNotification(conversationId, from)+    }+}++/** Inbound BYE: tear down the session + MSRP connection. */+internal suspend fun RcsSyncService.handleInboundBye(message: SipMessage) {+    if (!RcsFeature.enabled) return+    val callId = message.getCallIdParameter() ?: return+    RcsSessionManager.onSipRequest("BYE", callId, "", null, "")+    // Close connections whose sessions went away.+    closeDeadMsrpConnections()+    Log.i(RcsSyncService.TAG, "BYE processed callId=$callId")+}++/**+ * Inbound REFER (UP conference join): the focus (or a peer) asks us to+ * INVITE the conference URI in `Refer-To`. We start an outgoing group+ * session to it, which joins the conference dialog.+ */+internal suspend fun RcsSyncService.handleInboundRefer(message: SipMessage) {+    if (!RcsFeature.enabled) return+    val headers = message.getHeaderSection()+    val referTo = headerValue(headers, "Refer-To:")?.substringAfter("<")?.substringBefore(">")+        ?.takeIf { it.isNotBlank() } ?: return+    val callId = message.getCallIdParameter().orEmpty()+    // Accept the referral, then join.+    sendReferResponse(message, 202, "Accepted")+    val conversationId = "conf:${referTo.hashCode()}"+    RcsSessionManager.startGroupSession(referTo, "", conversationId)+    Log.i(RcsSyncService.TAG, "REFER accepted, joining focus callId=$callId")+}++/**+ * Inbound OPTIONS (capability ping): answer 200 OK with our CPM feature+ * tags in Accept-Contact, so peers' UCE/OPTIONS probes see us as capable.+ */+internal suspend fun RcsSyncService.handleInboundOptions(message: SipMessage) {+    if (!RcsFeature.enabled) return+    val headers = message.getHeaderSection()+    val from = headerValue(headers, "From:") ?: return+    val callId = message.getCallIdParameter() ?: return+    val cseq = headerValue(headers, "CSeq:") ?: "1 OPTIONS"+    val branch = "z9hG4bK${java.util.UUID.randomUUID().toString().replace("-", "").take(16)}"+    val tags = RcsSipTransport.CPM_FEATURE_TAGS.joinToString(", ")+    val startLine = "SIP/2.0 200 OK"+    val outHeaders = buildString {+        append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+        append("From: $from\r\n")+        val cfg = RcsSipTransport.lastConfigSnapshot()+        val me = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+        append("To: <$me>\r\n")+        append("Call-ID: $callId\r\n")+        append("CSeq: $cseq\r\n")+        append("Accept-Contact: *;$tags\r\n")+        append("Content-Length: 0\r\n")+    }+    RcsSipTransport.sendSipMessage(startLine, outHeaders, ByteArray(0))+}++/** Minimal final response to a REFER (no dialog needed). */+internal suspend fun RcsSyncService.sendReferResponse(message: SipMessage, code: Int, reason: String) {+    val headers = message.getHeaderSection()+    val from = headerValue(headers, "From:") ?: return+    val callId = message.getCallIdParameter() ?: return+    val cseq = headerValue(headers, "CSeq:") ?: "1 REFER"+    val branch = "z9hG4bK${java.util.UUID.randomUUID().toString().replace("-", "").take(16)}"+    val startLine = "SIP/2.0 $code $reason"+    val outHeaders = buildString {+        append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+        append("From: $from\r\n")+        append("Call-ID: $callId\r\n")+        append("CSeq: $cseq\r\n")+        append("Content-Length: 0\r\n")+    }+    RcsSipTransport.sendSipMessage(startLine, outHeaders, ByteArray(0))+}++internal fun RcsSyncService.showSessionInviteNotification(conversationId: String, from: String) {+    val target = ConversationTarget(+        line = CommunicateLine.Rcs,+        address = conversationId,+        remoteId = conversationId,+        isGroup = false,+        personName = from,+    )+    ConversationSpace.notifyIncoming(+        context = this,+        target = target,+        channelId = RcsSyncService.INCOMING_CHANNEL_ID,+        body = getString(R.string.rcs_session_invite),+        timestamp = System.currentTimeMillis(),+        smallIcon = R.mipmap.ic_launcher,+    )+}++/** Parse a header value out of a SIP header section (case-insensitive name + colon). */+internal fun headerValue(headers: String, name: String): String? {+    for (line in headers.lineSequence()) {+        val trimmed = line.trim()+        if (trimmed.startsWith(name, ignoreCase = true)) {+            return trimmed.substringAfter(":").trim().takeIf { it.isNotEmpty() }+        }+    }+    return null+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.ktindex fdfe76888c..e1a2810918 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -17,8 +17,10 @@ import com.vayunmathur.communicate.MainActivity import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.applyRcsDeliveryReport import com.vayunmathur.communicate.data.cacheInboundRcs import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.RcsDatabase import com.vayunmathur.communicate.data.rcs.RcsFeature import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsImdn@@ -34,8 +36,12 @@ import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys import com.vayunmathur.communicate.data.rcs.e2e.RcsPendingGroups import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto import com.vayunmathur.communicate.data.rcs.extractImdnMessageId+import com.vayunmathur.communicate.data.rcs.parseChunkHeader+import com.vayunmathur.communicate.data.rcs.parseEditBody+import com.vayunmathur.communicate.data.rcs.parseGeopushBody import com.vayunmathur.communicate.data.rcs.parseImdnBody import com.vayunmathur.communicate.data.rcs.parseIsComposingBody+import com.vayunmathur.communicate.data.rcs.parseRevokeBody import com.vayunmathur.communicate.notifications.ConversationSpace import com.vayunmathur.communicate.notifications.ConversationTarget import com.vayunmathur.library.util.ensureNotificationChannel@@ -56,7 +62,14 @@ class RcsSyncService : Service() {     private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)      /** MSRP connections per conversation, owned by this service's lifecycle. */-    private val msrpConnections = java.util.concurrent.ConcurrentHashMap<String, RcsMsrp.MsrpConnection>()+    internal val msrpConnections = java.util.concurrent.ConcurrentHashMap<String, RcsMsrp.MsrpConnection>()++    /** Close MSRP connections whose sessions went away. */+    internal fun closeDeadMsrpConnections() {+        msrpConnections.keys.filter { RcsSessionManager.sessionFor(it) == null }.forEach { id ->+            msrpConnections.remove(id)?.close()+        }+    }      override fun onCreate() {         super.onCreate()@@ -136,6 +149,27 @@ class RcsSyncService : Service() {     }      private suspend fun handleInbound(message: SipMessage) {+        val startLine = message.getStartLine()+        val method = startLine.substringBefore(" ").trim().uppercase()+        // Dialog-forming and dialog methods route before MESSAGE handling.+        when (method) {+            "INVITE" -> {+                handleInboundInvite(message)+                return+            }+            "BYE" -> {+                handleInboundBye(message)+                return+            }+            "REFER" -> {+                handleInboundRefer(message)+                return+            }+            "OPTIONS" -> {+                handleInboundOptions(message)+                return+            }+        }         val envelope = parseEnvelope(message) ?: return         // E2EE control + data payloads route before plaintext handling.         handleE2EEInbound(envelope)?.let { e2ee ->@@ -179,6 +213,15 @@ class RcsSyncService : Service() {         }     } +    /** Inbound BYE: tear down the session + MSRP connection. */+    private suspend fun handleInboundBye(message: SipMessage) {+        if (!RcsFeature.enabled) return+        val callId = message.getCallIdParameter() ?: return+        RcsSessionManager.onSipRequest("BYE", callId, "", null, "")+        closeDeadMsrpConnections()+        Log.i(TAG, "BYE processed callId=$callId")+    }+     /**      * Inbound MSRP chunk: CPIM text becomes an inbox row (+ notification);      * IMDN/typing ride their trackers. Reuses the SIP parse helpers by@@ -281,10 +324,15 @@ class RcsSyncService : Service() {             val from = envelope.from             val contentType = envelope.contentType             val raw = envelope.raw-            // IMDN reports and is-composing route to their trackers, not the inbox.+            // IMDN reports update delivery ticks AND route to the tracker.             if (contentType?.contains("imdn", ignoreCase = true) == true ||                 parseImdnBody(raw) != null             ) {+                parseImdnBody(raw)?.let { (id, disposition) ->+                    serviceScope.launch {+                        CommunicateRepository.applyRcsDeliveryReport(this@RcsSyncService, id, disposition)+                    }+                }                 RcsImdn.onReportReceived(raw)                 return InboundRcs(                     conversationId = from,@@ -308,6 +356,76 @@ class RcsSyncService : Service() {             }             val body = extractTextBody(envelope.raw.toByteArray(Charsets.UTF_8)) ?: return null             if (body.isBlank()) return null+            // Revoke: blank the referenced row, no inbox row.+            parseRevokeBody(body)?.let { revokedId ->+                serviceScope.launch {+                    runCatching {+                        val db = RcsDatabase.getDatabase(this@RcsSyncService)+                        db.cachedMessageDao().get(revokedId)?.let {+                            db.cachedMessageDao().upsert(it.copy(body = ""))+                        }+                    }+                }+                return InboundRcs(+                    conversationId = from,+                    body = "",+                    senderId = from,+                    messageId = "in-${envelope.callId}",+                    kind = InboundKind.Receipt,+                )+            }+            // Edit: swap the referenced row body, no new inbox row.+            parseEditBody(body)?.let { (originalId, newText) ->+                serviceScope.launch {+                    runCatching {+                        val db = RcsDatabase.getDatabase(this@RcsSyncService)+                        db.cachedMessageDao().get(originalId)?.let {+                            db.cachedMessageDao().upsert(it.copy(body = newText))+                        }+                    }+                }+                return InboundRcs(+                    conversationId = from,+                    body = "",+                    senderId = from,+                    messageId = "in-${envelope.callId}",+                    kind = InboundKind.Receipt,+                )+            }+            // Geolocation Push โ†’ location row.+            parseGeopushBody(body)?.let { (lat, lon, label) ->+                return InboundRcs(+                    conversationId = from,+                    body = label ?: "๐Ÿ“ $lat, $lon",+                    senderId = from,+                    messageId = "in-${envelope.callId}-${envelope.viaBranch}",+                    kind = InboundKind.Text,+                    ftUrl = "geo:$lat,$lon",+                    ftMime = "application/vnd.gsma.rcs.geopush+xml",+                    imdnMessageId = extractImdnMessageId(raw),+                )+            }+            // Large Message chunks: buffer per Message-ID; emit only when complete.+            parseChunkHeader(body)?.let { (chunkId, part, total) ->+                val complete = bufferLargeChunk(from, chunkId, part, total, body)+                if (complete == null) {+                    return InboundRcs(+                        conversationId = from,+                        body = "",+                        senderId = from,+                        messageId = "in-${envelope.callId}",+                        kind = InboundKind.Receipt,+                    )+                }+                return InboundRcs(+                    conversationId = from,+                    body = complete,+                    senderId = from,+                    messageId = "in-$chunkId",+                    kind = InboundKind.Text,+                    imdnMessageId = extractImdnMessageId(raw),+                )+            }             // FT-over-HTTP descriptors expose URL + mime for the renderer.             val ft = RcsFileTransferHttp.parseFtBody(body)             InboundRcs(@@ -415,6 +533,34 @@ class RcsSyncService : Service() {         )     } +    /** Large-message reassembly buffers: conversation โ†’ messageId โ†’ part โ†’ text. */+    private val largeChunks = java.util.concurrent.ConcurrentHashMap<String, MutableMap<String, MutableMap<Int, String>>>()++    /**+     * Buffer one Large Message chunk; return the joined text once all [total]+     * parts for ([conversationId], [chunkId]) arrived, else null.+     */+    private fun bufferLargeChunk(+        conversationId: String,+        chunkId: String,+        part: Int,+        total: Int,+        body: String,+    ): String? {+        if (total <= 0 || part <= 0 || part > total) return null+        val text = body.substringAfter("\r\n\r\n", "").ifBlank {+            body.substringAfter("\n\n", "")+        }.trim()+        val convo = largeChunks.getOrPut(conversationId) { java.util.concurrent.ConcurrentHashMap() }+        val parts = convo.getOrPut(chunkId) { java.util.concurrent.ConcurrentHashMap() }+        parts[part] = text+        if (parts.size != total) return null+        val complete = (1..total).map { parts[it] ?: return null }.joinToString("")+        convo.remove(chunkId)+        if (convo.isEmpty()) largeChunks.remove(conversationId)+        return complete.ifBlank { null }+    }+     /** Base64-decode a CPIM-wrapped binary payload body. */     private fun decodePayloadBody(body: String): ByteArray? {         val b64 = if (body.contains("\r\n\r\n")) {@@ -553,10 +699,10 @@ class RcsSyncService : Service() {     }      companion object {-        private const val TAG = "RcsSync"+        internal const val TAG = "RcsSync"         private const val SYNC_NOTIFICATION_ID = 4723         private const val SYNC_CHANNEL_ID = "rcs_sync"-        private const val INCOMING_CHANNEL_ID = "rcs_messages_incoming"+        internal const val INCOMING_CHANNEL_ID = "rcs_messages_incoming"         private const val ACTION_STOP = "com.vayunmathur.communicate.rcs.STOP_SYNC"         const val EXTRA_OPEN_RCS_THREAD = "open_rcs_thread" @@ -572,16 +718,5 @@ class RcsSyncService : Service() {                 Intent(context, RcsSyncService::class.java).apply { action = ACTION_STOP },             )         }--        /** Parse a header value out of a SIP header section (case-sensitive name + colon). */-        private fun headerValue(headers: String, name: String): String? {-            for (line in headers.lineSequence()) {-                val trimmed = line.trim()-                if (trimmed.startsWith(name, ignoreCase = true)) {-                    return trimmed.substringAfter(":").trim().takeIf { it.isNotEmpty() }-                }-            }-            return null-        }     } }
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 ca3aa0ced8..6c77bb7b36 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -178,6 +178,7 @@     <string name="rcs_encrypted_group_hint">Only members running this app can read messages. Set up once everyone\'s keys arrive.</string>     <string name="rcs_encrypted_banner">๐Ÿ”’ Encrypted โ€” only members can read these messages</string>     <string name="rcs_encrypted_pending">๐Ÿ”’ Waiting for members\' keys โ€” messages send plaintext until then</string>+    <string name="rcs_session_invite">๐Ÿ“ž Incoming chat session โ€” open to join</string>     <string name="inapp_ongoing_call">Ongoing call</string>     <string name="inapp_call_channel_name">Calls</string>     <string name="inapp_incoming_call_channel_name">Incoming calls</string>
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.ktindex 0951341ea7..189d45314a 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt@@ -1,12 +1,21 @@ package com.vayunmathur.communicate.rcs  import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.buildEditBody+import com.vayunmathur.communicate.data.rcs.buildGeopushBody import com.vayunmathur.communicate.data.rcs.buildImdnBody import com.vayunmathur.communicate.data.rcs.buildIsComposingBody+import com.vayunmathur.communicate.data.rcs.buildRevokeBody+import com.vayunmathur.communicate.data.rcs.chunkLargeMessage import com.vayunmathur.communicate.data.rcs.extractImdnMessageId import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory+import com.vayunmathur.communicate.data.rcs.parseChunkHeader+import com.vayunmathur.communicate.data.rcs.parseEditBody+import com.vayunmathur.communicate.data.rcs.parseGeopushBody import com.vayunmathur.communicate.data.rcs.parseImdnBody import com.vayunmathur.communicate.data.rcs.parseIsComposingBody+import com.vayunmathur.communicate.data.rcs.parseRevokeBody+import com.vayunmathur.communicate.data.rcs.reassembleLargeMessage import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -78,4 +87,50 @@ class RcsUpFramingTest {             ) != null,         )     }++    @Test+    fun geopushRoundTrip() {+        val body = buildGeopushBody(37.42, -122.08, "HQ")+        val parsed = parseGeopushBody(body)+        assertEquals(Triple(37.42, -122.08, "HQ"), parsed)+        assertNull(parseGeopushBody("plain text"))+    }++    @Test+    fun largeMessageChunksReassemble() {+        val text = "x".repeat(20000)+        val chunks = chunkLargeMessage("m1", text)+        assertTrue(chunks.size > 1)+        val map = mutableMapOf<Int, String>()+        var total = 0+        for (chunk in chunks) {+            val (id, part, t) = parseChunkHeader(chunk) ?: error("no header")+            assertEquals("m1", id)+            total = t+            map[part] = chunk.substringAfter("\r\n\r\n")+        }+        assertEquals(text, reassembleLargeMessage(map, total))+        assertNull(reassembleLargeMessage(mapOf(1 to "a"), 2))+    }++    @Test+    fun smallMessageNotChunked() {+        val chunks = chunkLargeMessage("m2", "hi")+        assertEquals(listOf("hi"), chunks)+    }++    @Test+    fun revokeRoundTrip() {+        val body = buildRevokeBody("orig-9")+        assertEquals("orig-9", parseRevokeBody(body))+        assertNull(parseRevokeBody("hello"))+    }++    @Test+    fun editRoundTrip() {+        val (id, text) = parseEditBody(buildEditBody("orig-7", "fixed")) ?: error("no edit")+        assertEquals("orig-7", id)+        assertEquals("fixed", text)+        assertNull(parseEditBody("plain"))+    } }