Modern Apps git

← Modern-Apps.git

communicate: align RCS with TestRcsApp reference

Commit
34235f56692f354a17f412c306810f628aae1a97
Author
vayun-mathur <[email protected]>
When
2026-09-23 06:01 UTC (2 months ago)
Parents
31bacfc

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.ktindex 3a076cbee5..a25bea27ca 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt@@ -65,7 +65,8 @@ object RcsCapabilityExchange {     ): Map<String, Boolean> {         if (numbers.isEmpty()) return emptyMap()         val app = context.applicationContext-        val subId = SubscriptionManager.getDefaultDataSubscriptionId()+        // TestRcsApp keys everything off the default SMS subscription.+        val subId = SubscriptionManager.getDefaultSmsSubscriptionId()         if (!SubscriptionManager.isValidSubscriptionId(subId)) return emptyMap()         val ims = app.getSystemService(ImsManager::class.java) ?: return emptyMap()         val adapter = runCatching { ims.getImsRcsManager(subId).getUceAdapter() }.getOrNull()
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.ktindex e835fe7459..8866b0eca7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt@@ -103,4 +103,105 @@ internal object RcsHiddenApi {         fun onComplete()         fun onError(errorCode: Int, retryAfterMillis: Long)     }++    /** Dynamic-dispatch target for the provisioning proxy (config is raw XML bytes). */+    interface ProvisioningCallback {+        fun onConfigurationChanged(configXml: ByteArray)+        fun onConfigurationReset()+        fun onRemoved()+    }++    /**+     * `ProvisioningManager.createForSubscriptionId(int)` (hidden static).+     * Returns the framework manager as `Any` — all further calls go through+     * the helpers below. Null on any failure.+     */+    fun provisioningManager(subId: Int): Any? {+        if (!RcsFeature.enabled) return null+        return runCatching {+            val pmClass = Class.forName("android.telephony.ims.ProvisioningManager")+            val factory = pmClass.getMethod("createForSubscriptionId", Int::class.javaPrimitiveType)+            factory.invoke(null, subId)+        }.getOrElse {+            Log.w(TAG, "createForSubscriptionId failed", it)+            null+        }+    }++    /**+     * `ProvisioningManager#isRcsVolteSingleRegistrationCapable()` (hidden).+     * Tri-state: true/false from the service, null when the bridge itself+     * failed (e.g. missing permission) so callers can treat it as "unknown"+     * rather than "not capable".+     */+    fun isSingleRegCapable(provisioningManager: Any): Boolean? {+        return runCatching {+            val method = provisioningManager.javaClass.getMethod("isRcsVolteSingleRegistrationCapable")+            method.invoke(provisioningManager) as? Boolean+        }.getOrElse {+            Log.w(TAG, "isRcsVolteSingleRegistrationCapable failed", it)+            null+        }+    }++    /**+     * `setRcsClientConfiguration` + `registerRcsProvisioningCallback` (hidden).+     * The callback interface is hidden, so it is delivered through a Proxy+     * like the UCE path. Returns false when the bridge itself fails.+     */+    fun registerProvisioningCallback(+        provisioningManager: Any,+        executor: java.util.concurrent.Executor,+        rcsVersion: String,+        rcsProfile: String,+        callback: ProvisioningCallback,+    ): Boolean {+        if (!RcsFeature.enabled) return false+        return runCatching {+            val pmClass = provisioningManager.javaClass+            val configClass = Class.forName("android.telephony.ims.RcsClientConfiguration")+            val callbackClass = Class.forName("android.telephony.ims.ProvisioningManager\$RcsProvisioningCallback")+            val config = configClass+                .getConstructor(String::class.java, String::class.java, String::class.java, String::class.java)+                .newInstance(rcsVersion, rcsProfile, "Vayun", "Communicate-1.0")+            pmClass.getMethod("setRcsClientConfiguration", configClass).invoke(provisioningManager, config)+            val proxy = java.lang.reflect.Proxy.newProxyInstance(+                pmClass.classLoader,+                arrayOf(callbackClass),+            ) { _, method, args ->+                when (method.name) {+                    "onConfigurationChanged" -> callback.onConfigurationChanged(+                        (args?.getOrNull(0) as? ByteArray) ?: ByteArray(0),+                    )+                    "onConfigurationReset" -> callback.onConfigurationReset()+                    "onRemoved" -> callback.onRemoved()+                    "toString" -> "RcsProvisioningCallbackProxy"+                    "hashCode" -> System.identityHashCode(callback)+                    "equals" -> args?.getOrNull(0) === callback+                    else -> null+                }+            }+            pmClass.getMethod(+                "registerRcsProvisioningCallback",+                java.util.concurrent.Executor::class.java,+                callbackClass,+            ).invoke(provisioningManager, executor, proxy)+            true+        }.getOrElse {+            val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it+            Log.w(TAG, "registerRcsProvisioningCallback failed", cause)+            false+        }+    }++    fun unregisterProvisioningCallback(provisioningManager: Any, callbackProxy: Any? = null) {+        runCatching {+            // Unregister by callback instance when we hold the proxy; otherwise best-effort no-op.+            if (callbackProxy != null) {+                provisioningManager.javaClass+                    .getMethod("unregisterRcsProvisioningCallback", callbackProxy.javaClass.interfaces.first())+                    .invoke(provisioningManager, callbackProxy)+            }+        }+    } }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.ktindex 8ce721925a..9bbcbe2d9b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt@@ -69,7 +69,7 @@ object RcsProvisioning {      /**      * Run the provisioning check for [subscriptionId] (defaults to the default-     * data subscription). Updates [state]; also returns it.+     * SMS subscription, mirroring TestRcsApp). Updates [state]; also returns it.      */     suspend fun probe(context: Context, subscriptionId: Int = defaultSubscriptionId()): RcsRegistrationState {         if (!RcsFeature.enabled) {@@ -119,6 +119,18 @@ object RcsProvisioning {         if (provisioningRequired) {             return RcsRegistrationState.Unavailable(RcsUnavailableReason.ProvisioningRequired)         }+        // Tertiary signal (TestRcsApp ProvisioningActivity): the hidden+        // isRcsVolteSingleRegistrationCapable() on the per-sub manager. Tri-state —+        // null (bridge failure, e.g. role not yet granted) means "unknown", not+        // "not capable", so it never blocks on permission errors.+        val singleRegCapable = runCatching {+            val pm = RcsHiddenApi.provisioningManager(subscriptionId)+                ?: return@runCatching null+            RcsHiddenApi.isSingleRegCapable(pm)+        }.getOrDefault(null)+        if (singleRegCapable == false) {+            return RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported)+        }         // Single-registration support gate: without it there is no delegate to create.         // The feature constant is @SystemApi/hidden; the AOSP value is used directly.         val singleReg = context.packageManager.hasSystemFeature(FEATURE_SINGLE_REG)@@ -146,7 +158,8 @@ object RcsProvisioning {     }      private fun defaultSubscriptionId(): Int = runCatching {-        SubscriptionManager.getDefaultDataSubscriptionId()+        // TestRcsApp keys everything off the default SMS subscription.+        SubscriptionManager.getDefaultSmsSubscriptionId()     }.getOrDefault(SubscriptionManager.INVALID_SUBSCRIPTION_ID)      fun hasPhoneStatePermission(context: Context): Boolean =
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.ktindex 30dc4e7b54..38dc105657 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt@@ -43,11 +43,14 @@ object RcsSipTransport {     /**      * CPM feature tags for RCS chat + file transfer (RCC.07 §2.6.1.3). Must be      * allowed by the carrier (`KEY_RCS_FEATURE_TAG_ALLOWED_STRING_ARRAY`) or-     * the request is denied.+     * the request is denied. Tag set mirrors TestRcsApp's DelegateActivity:+     * session + pager-mode variants + FT.      */     val CPM_FEATURE_TAGS: Set<String> = setOf(         "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"",+        "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.msg\"",         "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.largemsg\"",+        "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.deferred\"",         "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp\"",     ) @@ -60,6 +63,8 @@ object RcsSipTransport {     @Volatile private var connection: SipDelegateConnection? = null     @Volatile private var configVersion: Long = -1L     @Volatile private var activeSubId: Int = SubscriptionManager.INVALID_SUBSCRIPTION_ID+    /** Last IMS configuration (identity, server, route headers for sends). */+    @Volatile private var lastConfig: SipDelegateConfiguration? = null      /** Inbound SIP MESSAGE listener (sync service writes to Room + notifies). */     @Volatile@@ -87,12 +92,14 @@ object RcsSipTransport {          override fun onConfigurationChanged(registeredSipConfig: SipDelegateConfiguration) {             configVersion = registeredSipConfig.getVersion()+            lastConfig = registeredSipConfig         }          override fun onDestroyed(reason: Int) {             Log.w(TAG, "SipDelegate destroyed reason=$reason")             connection = null             configVersion = -1L+            lastConfig = null             if (_state.value is RcsRegistrationState.Available) {                 _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)             }@@ -187,6 +194,10 @@ object RcsSipTransport {     /**      * Build a pager-mode SIP MESSAGE start line + headers for a 1:1 CPM chat      * message. The branch parameter doubles as the send ack key.+     *+     * The body is a `message/cpim` envelope (TestRcsApp CpimUtils) carrying+     * IMDN metadata; the From identity comes from the delegate configuration+     * (public user identifier) when known, else the [fromUri] fallback.      */     fun buildChatMessage(         fromUri: String,@@ -195,17 +206,38 @@ object RcsSipTransport {         body: String,     ): Triple<String, String, ByteArray> {         val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val from = lastConfig?.getPublicUserIdentifier()?.takeIf { it.isNotBlank() } ?: fromUri+        val cpim = buildCpimBody(body)+        val bytes = cpim.toByteArray(Charsets.UTF_8)         val startLine = "MESSAGE $toUri SIP/2.0"         val headers = buildString {-            append("Via: SIP/2.0/TCP $fromUri;branch=$branch\r\n")-            append("From: <$fromUri>;tag=${UUID.randomUUID().toString().take(8)}\r\n")+            append("Via: SIP/2.0/TCP $from;branch=$branch\r\n")+            append("From: <$from>;tag=${UUID.randomUUID().toString().take(8)}\r\n")             append("To: <$toUri>\r\n")             append("Call-ID: $callId\r\n")             append("CSeq: 1 MESSAGE\r\n")-            append("Content-Type: text/plain;charset=UTF-8\r\n")-            append("Content-Length: ${body.toByteArray(Charsets.UTF_8).size}\r\n")+            append("Content-Type: message/cpim\r\n")+            append("Content-Length: ${bytes.size}\r\n")         }-        return Triple(startLine, headers, body.toByteArray(Charsets.UTF_8))+        return Triple(startLine, headers, bytes)+    }++    /**+     * Minimal `message/cpim` envelope for a text message (TestRcsApp+     * CpimUtils.createForText): IMDN namespace + delivery/display disposition,+     * anonymous From/To (routing uses the SIP headers), ISO-instant DateTime.+     */+    fun buildCpimBody(text: String): String = buildString {+        append("NS: imdn <urn:ietf:params:imdn>\r\n")+        append("imdn.Message-ID: rcs-${UUID.randomUUID()}\r\n")+        append("imdn.Disposition-Notification: positive-delivery, display\r\n")+        append("To: <sip:[email protected]>\r\n")+        append("From: <sip:[email protected]>\r\n")+        append("DateTime: ${java.time.Instant.now()}\r\n")+        append("Content-Type: text/plain;charset=UTF-8\r\n")+        append("Content-Length: ${text.toByteArray(Charsets.UTF_8).size}\r\n")+        append("\r\n")+        append(text)     }      private fun createDelegate(context: Context, subId: Int) {@@ -245,7 +277,8 @@ object RcsSipTransport {      private fun activeSubId(context: Context): Int {         if (!RcsProvisioning.hasPhoneStatePermission(context)) {-            return SubscriptionManager.getDefaultDataSubscriptionId()+            // TestRcsApp keys everything off the default SMS subscription.+            return SubscriptionManager.getDefaultSmsSubscriptionId()         }         val sims = SimManager.activeSims(context)         if (sims.isEmpty()) return SubscriptionManager.INVALID_SUBSCRIPTION_ID
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 6c033a9d08..846111a397 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -107,11 +107,17 @@ class RcsSyncService : Service() {      private fun parseInbound(message: SipMessage): InboundRcs? {         return runCatching {-            val headers = message.getHeaderSection()+            // Modem quirk (TestRcsApp RegistrationControllerImpl.repairHeaderSection):+            // some modems emit "ia:" instead of "Via:".+            var headers = message.getHeaderSection()+            if (headers.startsWith("ia:")) {+                headers = "V$headers"+                Log.w(TAG, "Repaired malformed Via header")+            }             val from = headerValue(headers, "From:")?.substringAfter("<")?.substringBefore(">")                 ?.substringAfter("sip:")?.substringBefore("@")                 ?.takeIf { it.isNotBlank() } ?: return null-            val body = message.getContent().toString(Charsets.UTF_8)+            val body = extractTextBody(message.getContent()) ?: return null             if (body.isBlank()) return null             val callId = message.getCallIdParameter() ?: body.hashCode().toString()             InboundRcs(@@ -123,6 +129,25 @@ class RcsSyncService : Service() {         }.getOrNull()     } +    /**+     * Extract display text from a message body. Pager-mode RCS arrives as+     * `message/cpim` (TestRcsApp CpimUtils); plain `text/plain` passes through.+     */+    private fun extractTextBody(content: ByteArray): String? {+        val raw = content.toString(Charsets.UTF_8)+        if (raw.isBlank()) return null+        if (raw.contains("message/cpim", ignoreCase = true)) {+            // CPIM: headers, blank line, payload. The payload after the last+            // double-CRLF is the text (cpim content with Content-Type text/plain).+            val sections = raw.split("\r\n\r\n")+            if (sections.size >= 2) {+                return sections.last().trim().takeIf { it.isNotEmpty() }+            }+            return null+        }+        return raw+    }+     private data class InboundRcs(         val conversationId: String,         val body: String,
library/rcs-stubs/src/main/java/android/telephony/ims/RcsClientConfiguration.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/RcsClientConfiguration.java b/library/rcs-stubs/src/main/java/android/telephony/ims/RcsClientConfiguration.javanew file mode 100644index 0000000000..ad4ad1e1c7--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/RcsClientConfiguration.java@@ -0,0 +1,34 @@+package android.telephony.ims;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.RcsClientConfiguration}. Passed to+ * `ProvisioningManager#setRcsClientConfiguration` (hidden; see+ * TestRcsApp's ProvisioningActivity). Not packaged; the real class is+ * provided by the framework at runtime.+ */+public final class RcsClientConfiguration {+    public RcsClientConfiguration(+            String rcsVersion,+            String rcsProfile,+            String clientVendor,+            String clientVersion) {+        throw new RuntimeException("Stub");+    }++    public String getRcsVersion() {+        throw new RuntimeException("Stub");+    }++    public String getRcsProfile() {+        throw new RuntimeException("Stub");+    }++    public String getClientVendor() {+        throw new RuntimeException("Stub");+    }++    public String getClientVersion() {+        throw new RuntimeException("Stub");+    }+}
library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.java b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.javaindex 492abcbe5f..2139677ffd 100644--- a/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.java+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.java@@ -1,22 +1,90 @@ package android.telephony.ims; - /**  * Compile-only stub of the framework's {@code @SystemApi}- * {@code android.telephony.ims.SipDelegateConfiguration}. Carries only the- * getters RCS code reads. Not packaged; the real class is provided by the- * framework at runtime.+ * {@code android.telephony.ims.SipDelegateConfiguration}. Carries the getters+ * RCS code reads (mirrors the AOSP surface; see TestRcsApp's+ * RegistrationControllerImpl for the consumer side). Not packaged; the real+ * class is provided by the framework at runtime.  */ public final class SipDelegateConfiguration {+    public static final int SIP_TRANSPORT_UDP = 0;+    public static final int SIP_TRANSPORT_TCP = 1;+    public static final int SIP_TRANSPORT_TLS = 2;+     public long getVersion() {         throw new RuntimeException("Stub");     } +    public int getTransportType() {+        throw new RuntimeException("Stub");+    }+     public String getPublicUserIdentifier() {         throw new RuntimeException("Stub");     } +    public String getPrivateUserIdentifier() {+        throw new RuntimeException("Stub");+    }+     public String getHomeDomain() {         throw new RuntimeException("Stub");     }-}\ No newline at end of file++    public String getImei() {+        throw new RuntimeException("Stub");+    }++    public String getPublicGruuUri() {+        throw new RuntimeException("Stub");+    }++    public String getSipAuthenticationHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipAuthenticationNonce() {+        throw new RuntimeException("Stub");+    }++    public String getSipServiceRouteHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipPathHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipUserAgentHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipContactUserParameter() {+        throw new RuntimeException("Stub");+    }++    public String getSipPaniHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipPlaniHeader() {+        throw new RuntimeException("Stub");+    }++    public String getSipAssociatedUriHeader() {+        throw new RuntimeException("Stub");+    }++    public int getMaxUdpPayloadSizeBytes() {+        throw new RuntimeException("Stub");+    }++    public boolean isSipCompactFormEnabled() {+        throw new RuntimeException("Stub");+    }++    public boolean isSipKeepaliveEnabled() {+        throw new RuntimeException("Stub");+    }+}