communicate: add RCS single-registration line behind dev gate
- Commit
a7c75ab64e29133d045cf0bf32ca9750885ae513- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-23 04:37 UTC (2 months ago)
- Parents
05e6db3
Diff
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex abeaa86b7d..1c746f595e 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -166,6 +166,13 @@ dependencies { implementation(libs.ringrtc.android) // E.164 normalization to reconcile SIM vs Google Voice numbers. implementation(libs.libphonenumber)+ // Compile-only stubs for the framework's @SystemApi app-data backup transport+ // (see :library:backup-stubs).+ compileOnly(project(":library:backup-stubs"))+ // Compile-only stubs for the framework's @SystemApi single-registration RCS APIs+ // (SipDelegateManager, UCE). Absent from the public SDK; the framework provides+ // them at runtime, so they must NOT be packaged. See :library:rcs-stubs.+ compileOnly(project(":library:rcs-stubs")) // Persist the Google Voice / WhatsApp session (cookies, API key, auth, number). implementation(libs.androidx.datastore.preferences) // Document-start JS injection to hook fetch/XHR before the GV web app captures them.
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 7c224b32a9..4430c18586 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -206,6 +206,11 @@ android:exported="false" android:foregroundServiceType="remoteMessaging" /> + <service+ android:name=".telephony.RcsSyncService"+ android:exported="false"+ android:foregroundServiceType="remoteMessaging" />+ <service android:name=".telephony.GoogleVoiceCallForegroundService" android:exported="false"
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex cd968c63c5..3bd26c8105 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -57,6 +57,11 @@ import com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession import com.vayunmathur.communicate.data.signal.SignalFeature import com.vayunmathur.communicate.data.signal.SignalLineSession import com.vayunmathur.communicate.telephony.SignalSyncService+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.telephony.RcsSyncService+import com.vayunmathur.communicate.ui.rcs.RcsRegistrationScreen import com.vayunmathur.communicate.ui.signal.SignalRegistrationScreen import androidx.compose.ui.platform.LocalContext import kotlinx.serialization.Serializable@@ -69,6 +74,8 @@ sealed interface Route : NavKey { @Serializable data object WhatsAppBackupImport : Route @Serializable data object SignalRegistration : Route + @Serializable data object RcsStatus : Route+ @Serializable data class Conversation( val threadId: Long,@@ -162,6 +169,15 @@ private fun CommunicateApp(initialDeepLink: DeepLink? = null) { if (sigSignedIn) SignalSyncService.start(context) else SignalSyncService.stop(context) } + // Own the RCS always-on receive state via its foreground sync service (dev-only).+ // Provisioning IS the session: Available owns the service, anything else stops it.+ val rcsState by RcsSipTransport.state.collectAsState(initial = RcsRegistrationState.Unknown)+ LaunchedEffect(rcsState) {+ if (!RcsFeature.enabled) return@LaunchedEffect+ if (rcsState is RcsRegistrationState.Available) RcsSyncService.start(context)+ else RcsSyncService.stop(context)+ }+ // Keep the Telecom account fresh, but let the foreground service own always-on receive state. LaunchedEffect(gvSignedIn) { GoogleVoiceCallManager.init(context)@@ -240,6 +256,11 @@ private fun CommunicateApp(initialDeepLink: DeepLink? = null) { backStack.add(Route.SignalRegistration) } },+ onShowRcsStatus = {+ if (RcsFeature.enabled) {+ backStack.add(Route.RcsStatus)+ }+ }, ) } entry<Route.GoogleVoiceSignIn>(metadata = ListDetailPage()) {@@ -265,6 +286,11 @@ private fun CommunicateApp(initialDeepLink: DeepLink? = null) { onRegistered = { backStack.pop() }, ) }+ entry<Route.RcsStatus>(metadata = ListDetailPage()) {+ RcsRegistrationScreen(+ onBack = { backStack.pop() },+ )+ } entry<Route.Conversation>(metadata = ListDetailPage() + MorphPage()) { route -> ConversationScreen( threadId = route.threadId,
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex f6d5cccf33..e72c30d0ad 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -10,6 +10,7 @@ enum class CommunicateLine { GoogleVoice, WhatsApp, Signal,+ Rcs, } /**@@ -38,6 +39,11 @@ sealed interface LineChoice { override val label = "Signal" override val category get() = CommunicateLine.Signal }++ data object Rcs : LineChoice {+ override val label = "RCS"+ override val category get() = CommunicateLine.Rcs+ } } data class CommunicateContact(
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.ktindex 1933f5b287..6cca2ce97a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt@@ -46,7 +46,7 @@ fun CommunicateRepository.placeCall(context: Context, choice: LineChoice?, numbe } /** Virtual (network-backed) lines that don't map to a physical SIM subscription. */-val CommunicateRepository.isVirtualLine get() = setOf(CommunicateLine.GoogleVoice, CommunicateLine.WhatsApp, CommunicateLine.Signal)+val CommunicateRepository.isVirtualLine get() = setOf(CommunicateLine.GoogleVoice, CommunicateLine.WhatsApp, CommunicateLine.Signal, CommunicateLine.Rcs) /** * Place a voice call on [line] for a conversation.@@ -87,6 +87,8 @@ suspend fun CommunicateRepository.placeCallForLine( true } }+ // RCS is messaging-only in v1: no telephony or WebRTC call path.+ CommunicateLine.Rcs -> false } /** Whether [line] can place a call at all, so the UI can hide the affordance instead of failing. */@@ -95,6 +97,8 @@ fun CommunicateRepository.canPlaceCall(line: CommunicateLine): Boolean = when (l CommunicateLine.GoogleVoice -> true CommunicateLine.WhatsApp -> com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled CommunicateLine.Signal -> com.vayunmathur.communicate.data.signal.SignalFeature.enabled+ // RCS is messaging-only in v1.+ CommunicateLine.Rcs -> false } /**
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.ktindex 7f07e394a8..fd73ed0ec8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt@@ -79,6 +79,14 @@ suspend fun CommunicateRepository.deleteConversation(context: Context, thread: S true }.getOrDefault(false) } ?: false+ CommunicateLine.Rcs -> thread.remoteId?.let { id ->+ runCatching {+ val db = com.vayunmathur.communicate.data.rcs.RcsDatabase.getDatabase(context)+ db.conversationDao().delete(id)+ db.cachedMessageDao().deleteConversation(id)+ true+ }.getOrDefault(false)+ } ?: false } } @@ -114,6 +122,7 @@ suspend fun CommunicateRepository.deleteCallLog(context: Context, entry: Communi fun CommunicateRepository.canSendPoll(line: CommunicateLine): Boolean = when (line) { CommunicateLine.WhatsApp -> com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled CommunicateLine.Signal -> com.vayunmathur.communicate.data.signal.SignalFeature.enabled+ CommunicateLine.Rcs -> com.vayunmathur.communicate.data.rcs.RcsFeature.enabled else -> false } @@ -124,6 +133,7 @@ fun CommunicateRepository.canSendPoll(line: CommunicateLine): Boolean = when (li fun CommunicateRepository.canShareContact(line: CommunicateLine): Boolean = when (line) { CommunicateLine.WhatsApp -> com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled CommunicateLine.Signal -> com.vayunmathur.communicate.data.signal.SignalFeature.enabled+ CommunicateLine.Rcs -> com.vayunmathur.communicate.data.rcs.RcsFeature.enabled else -> false }
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.ktnew file mode 100644index 0000000000..9c27dcb81d--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -0,0 +1,283 @@+package com.vayunmathur.communicate.data++import android.content.Context+import android.telephony.TelephonyManager+import com.vayunmathur.communicate.data.rcs.RcsCachedMessage+import com.vayunmathur.communicate.data.rcs.RcsCapabilityExchange+import com.vayunmathur.communicate.data.rcs.RcsConversation+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.library.util.AppMessages+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * CommunicateRepository RCS single-registration line (mirrors+ * CommunicateRepositorySignal.kt).+ *+ * Threads/messages read from the local Room cache (populated by+ * RcsSyncService); sends go through [RcsSipTransport] with SMS fallback when+ * the contact is not capable or the transport is unavailable. Extension+ * functions on [CommunicateRepository]; behavior identical, call sites+ * unchanged.+ */++/** Result of an RCS send attempt, so the caller can fall back to SMS. */+enum class RcsSendResult {+ Sent,+ FallbackSms,+ Failed,+}++internal suspend fun CommunicateRepository.loadRcsThreads(context: Context): List<SmsThread> {+ if (!RcsFeature.enabled) return emptyList()+ return runCatching {+ val db = RcsDatabase.getDatabase(context)+ db.cachedMessageDao().getLatestPerConversation().map { m ->+ val cid = m.conversationId+ val conv = db.conversationDao().getConversation(cid)+ val isGroup = conv?.isGroup ?: false+ val unread = conv?.unreadCount ?: 0+ val participants = parseParticipantsCsv(conv?.participants)+ val groupTitle = conv?.name?.takeIf { it.isNotBlank() }+ SmsThread(+ threadId = stableThreadId(cid),+ address = if (isGroup) cid else cid,+ displayName = if (isGroup) {+ groupTitle ?: rcsDisplayName(context, cid)+ } else {+ rcsDisplayName(context, cid)+ },+ snippet = m.body,+ timestampMillis = m.timestamp,+ unreadCount = unread,+ line = CommunicateLine.Rcs,+ remoteId = cid,+ isGroup = isGroup,+ avatarUrl = null,+ participants = participants,+ groupTitle = groupTitle,+ )+ }+ }.getOrDefault(emptyList())+}++internal suspend fun CommunicateRepository.loadRcsMessages(context: Context, conversationId: String): List<SmsMessage> =+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ db.cachedMessageDao().getForConversation(conversationId).map { m ->+ SmsMessage(+ id = (m.messageId.hashCode().toLong() and 0xFFFFFFFFL),+ threadId = stableThreadId(conversationId),+ address = conversationId,+ body = m.body,+ timestampMillis = m.timestamp,+ outgoing = m.outgoing,+ read = true,+ line = CommunicateLine.Rcs,+ remoteId = m.messageId,+ attachments = if (m.ftUrl != null) {+ listOf(CommunicateAttachment(m.ftUrl, m.ftMime ?: "application/octet-stream"))+ } else {+ emptyList()+ },+ senderAddress = m.senderId.takeIf { it.isNotBlank() && !m.outgoing },+ status = m.status.let { s ->+ MessageStatus.entries.getOrElse(s) { MessageStatus.None }+ },+ )+ }+ }.getOrDefault(emptyList())++/**+ * Send on the RCS line. Returns [RcsSendResult.FallbackSms] when the contact+ * is not RCS-capable or the transport is unavailable, so the caller can+ * re-send via SMS. Never throws.+ */+suspend fun CommunicateRepository.sendRcsMessage(+ context: Context,+ address: String,+ body: String,+ threadRemoteId: String?,+ attachments: List<CommunicateAttachment> = emptyList(),+ participants: List<String> = emptyList(),+): RcsSendResult = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext RcsSendResult.Failed+ val recipient = threadRemoteId?.takeIf { it.isNotBlank() } ?: toRcsRecipient(context, address)+ if (recipient.isBlank()) return@withContext RcsSendResult.Failed+ // Capability pre-check: unknown contacts are not capable → SMS path.+ val capable = runCatching {+ if (participants.isNotEmpty()) {+ RcsCapabilityExchange.filterCapable(context, participants).isNotEmpty()+ } else {+ RcsCapabilityExchange.isContactRcsCapable(context, recipient)+ }+ }.getOrDefault(false)+ if (!capable) return@withContext RcsSendResult.FallbackSms+ if (!RcsSipTransport.canSend()) return@withContext RcsSendResult.FallbackSms+ runCatching {+ val (startLine, headers, content) = if (attachments.isEmpty()) {+ RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$recipient@rcs",+ body = body,+ )+ } else {+ // v1: attachments ride as a plain-text placeholder + FT metadata row;+ // full MSRP/FT flows land in RcsFileTransfer.+ RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$recipient@rcs",+ body = body.ifBlank { "[attachment]" },+ )+ }+ val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+ if (!ok) return@withContext RcsSendResult.FallbackSms+ if (body.isNotBlank()) {+ cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}")+ }+ RcsSendResult.Sent+ }.getOrDefault(RcsSendResult.FallbackSms)+}++/**+ * Build an RCS recipient id from a phone number / address. Conference URIs+ * (groups) pass through; otherwise the number is normalized to E.164 via+ * libphonenumber, mirroring [toSignalRecipient].+ */+internal fun CommunicateRepository.toRcsRecipient(context: Context, address: String): String {+ if (address.isBlank()) return ""+ if (address.contains("@") || address.contains(":")) return address+ val region = runCatching {+ val tm = context.getSystemService(TelephonyManager::class.java)+ (tm?.simCountryIso?.takeIf { it.isNotBlank() } ?: tm?.networkCountryIso)?.uppercase()+ }.getOrNull()?.takeIf { it.isNotBlank() }+ ?: context.resources.configuration.locales[0].country.ifEmpty { "US" }+ val e164 = runCatching {+ val util = com.google.i18n.phonenumbers.PhoneNumberUtil.getInstance()+ val parsed = util.parse(address, region)+ util.format(parsed, com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat.E164)+ }.getOrNull()+ return e164 ?: address+}++private fun CommunicateRepository.rcsDisplayName(context: Context, conversationId: String): String? {+ if (conversationId.contains("@") || conversationId.contains(":")) return conversationId+ return findContactName(context, conversationId) ?: conversationId+}++/** Insert an outgoing RCS message into the local cache so it shows in our own thread. */+internal suspend fun CommunicateRepository.cacheOutgoingRcs(+ context: Context,+ conversationId: String,+ body: String,+ messageId: String,+) {+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ val now = System.currentTimeMillis()+ db.cachedMessageDao().upsert(+ RcsCachedMessage(+ messageId = messageId,+ conversationId = conversationId,+ body = body,+ timestamp = now,+ outgoing = true,+ status = 1,+ ),+ )+ val existing = db.conversationDao().getConversation(conversationId)+ db.conversationDao().upsert(+ (existing ?: RcsConversation(remoteId = conversationId)).copy(lastMessageTimestamp = now),+ )+ }+}++/** Write an inbound RCS message into the local cache (sync service). */+internal suspend fun CommunicateRepository.cacheInboundRcs(+ context: Context,+ conversationId: String,+ body: String,+ senderId: String = "",+ messageId: String = "in-${UUID.randomUUID()}",+ ftUrl: String? = null,+ ftMime: String? = null,+) {+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ val now = System.currentTimeMillis()+ db.cachedMessageDao().upsert(+ RcsCachedMessage(+ messageId = messageId,+ conversationId = conversationId,+ body = body,+ timestamp = now,+ outgoing = false,+ senderId = senderId,+ ftUrl = ftUrl,+ ftMime = ftMime,+ ),+ )+ val existing = db.conversationDao().getConversation(conversationId)+ db.conversationDao().upsert(+ (existing ?: RcsConversation(remoteId = conversationId)).copy(+ lastMessageTimestamp = now,+ unreadCount = (existing?.unreadCount ?: 0) + 1,+ ),+ )+ }+}++/** Cache an outgoing file-transfer row (our own FT send echo). */+internal suspend fun CommunicateRepository.cacheOutgoingRcsFile(+ context: Context,+ conversationId: String,+ body: String,+ messageId: String,+ ftUrl: String?,+ ftMime: String?,+) {+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ val now = System.currentTimeMillis()+ db.cachedMessageDao().upsert(+ RcsCachedMessage(+ messageId = messageId,+ conversationId = conversationId,+ body = body,+ timestamp = now,+ outgoing = true,+ ftUrl = ftUrl,+ ftMime = ftMime,+ status = 1,+ ),+ )+ val existing = db.conversationDao().getConversation(conversationId)+ db.conversationDao().upsert(+ (existing ?: RcsConversation(remoteId = conversationId)).copy(lastMessageTimestamp = now),+ )+ }+}++/** Mark an RCS conversation read (clears the local unread badge). */+suspend fun CommunicateRepository.markRcsRead(+ context: Context,+ remoteId: String?,+ address: String,+): Unit = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext+ val cid = remoteId?.takeIf { it.isNotBlank() } ?: toRcsRecipient(context, address)+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ db.conversationDao().getConversation(cid)?.let {+ if (it.unreadCount != 0) db.conversationDao().upsert(it.copy(unreadCount = 0))+ }+ }+}++/** Surface the SMS-fallback notice on the caller's behalf (never `Toast`). */+fun CommunicateRepository.notifyRcsFallback(context: Context) {+ AppMessages.show(context.getString(com.vayunmathur.communicate.R.string.rcs_fallback_sms))+}
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.ktindex 9b1e1f6505..e650dda13a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt@@ -23,7 +23,8 @@ suspend fun CommunicateRepository.loadSmsThreadsMerged(context: Context): List<S val gv = loadGoogleVoiceThreads(context) val wa = loadWhatsAppThreads(context) val signal = loadSignalThreads(context)- return (sim + gv + wa + signal).sortedByDescending { it.timestampMillis }+ val rcs = loadRcsThreads(context)+ return (sim + gv + wa + signal + rcs).sortedByDescending { it.timestampMillis } } /** Route by line: SIM threads read the provider; GV threads hit `api2thread/get`; WA/Signal read Room. */@@ -50,6 +51,10 @@ suspend fun CommunicateRepository.loadSmsMessagesMerged(context: Context, thread val recipient = thread.remoteId?.takeIf { it.isNotBlank() } ?: toSignalRecipient(context, thread.address) loadSignalMessages(context, recipient) }+ CommunicateLine.Rcs -> {+ val recipient = thread.remoteId?.takeIf { it.isNotBlank() } ?: toRcsRecipient(context, thread.address)+ loadRcsMessages(context, recipient)+ } } suspend fun CommunicateRepository.loadCallLogsMerged(context: Context): List<CommunicateCallLogEntry> {@@ -147,6 +152,25 @@ suspend fun CommunicateRepository.sendMessage( sentId != null }.getOrDefault(false) }+ LineChoice.Rcs -> withContext(Dispatchers.IO) {+ when (sendRcsMessage(context, address, body, threadRemoteId, attachments, participants)) {+ RcsSendResult.Sent -> true+ RcsSendResult.Failed -> false+ RcsSendResult.FallbackSms -> {+ // Not RCS-capable or transport unavailable: fall back to SMS on the+ // default subscription and tell the user (never silently downgrade).+ notifyRcsFallback(context)+ val subId = SimManager.activeSims(context).firstOrNull()?.subscriptionId+ ?: SimManager.defaultSmsSubscriptionId()+ val recipients = participants.map { it.trim() }.filter { it.isNotEmpty() }.ifEmpty { listOf(address) }+ if (recipients.size > 1 || attachments.isNotEmpty()) {+ sendSimMms(context, subId, recipients, body, attachments)+ } else {+ sendSimSms(context, subId, address, body)+ }+ }+ }+ } } } internal fun CommunicateRepository.sendSimSms(context: Context, subscriptionId: Int, address: String, body: String): Boolean {
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.ktnew file mode 100644index 0000000000..3a076cbee5--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt@@ -0,0 +1,154 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.net.Uri+import android.telephony.SubscriptionManager+import android.telephony.ims.ImsException+import android.telephony.ims.ImsManager+import android.util.Log+import java.util.concurrent.Executor+import java.util.concurrent.Executors+import kotlin.coroutines.resume+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.suspendCancellableCoroutine++/**+ * Capability exchange over the hidden `RcsUceAdapter#requestCapabilities`+ * (see [RcsHiddenApi]).+ *+ * Unknown contacts count as not capable → the send path falls back to SMS.+ * All failures are fail-closed (`false`); never throws.+ */+object RcsCapabilityExchange {+ private const val TAG = "RcsCapability"++ // AOSP RcsContactUceCapability values (hidden from the public SDK).+ private const val REQUEST_RESULT_FOUND = 3+ private const val CAPABILITY_MECHANISM_OPTIONS = 2++ private val executor: Executor = Executors.newSingleThreadExecutor()++ private val _updates = MutableStateFlow<Map<String, Boolean>>(emptyMap())+ val updates: StateFlow<Map<String, Boolean>> = _updates.asStateFlow()++ /** Whether the UCE path is usable at all (setting on + no privilege error). */+ @Volatile+ var uceAvailable: Boolean = true+ private set++ /**+ * True when [e164] is RCS-capable (capability FOUND and the CPM session+ * tag is covered). False for unknown contacts, errors, or when the gate+ * is off.+ */+ suspend fun isContactRcsCapable(context: Context, e164: String): Boolean {+ if (!RcsFeature.enabled || e164.isBlank()) return false+ val results = queryCapabilities(context, listOf(e164))+ return results[e164] == true+ }++ /**+ * Batch capability check for group members. Returns the subset that is+ * RCS-capable. Empty on any failure.+ */+ suspend fun filterCapable(context: Context, members: List<String>): List<String> {+ if (!RcsFeature.enabled || members.isEmpty()) return emptyList()+ val results = queryCapabilities(context, members.distinct())+ return members.filter { results[it] == true }+ }++ private suspend fun queryCapabilities(+ context: Context,+ numbers: List<String>,+ ): Map<String, Boolean> {+ if (numbers.isEmpty()) return emptyMap()+ val app = context.applicationContext+ val subId = SubscriptionManager.getDefaultDataSubscriptionId()+ if (!SubscriptionManager.isValidSubscriptionId(subId)) return emptyMap()+ val ims = app.getSystemService(ImsManager::class.java) ?: return emptyMap()+ val adapter = runCatching { ims.getImsRcsManager(subId).getUceAdapter() }.getOrNull()+ ?: return emptyMap()+ val uris = numbers.map { Uri.fromParts("tel", it, null) }+ val caps: List<Map<String, Any?>> = suspendCancellableCoroutine { cont ->+ val collected = mutableListOf<Map<String, Any?>>()+ val bridged: Boolean = try {+ RcsHiddenApi.requestUceCapabilities(+ adapter = adapter,+ contactUris = uris,+ executor = executor,+ callback = object : RcsHiddenApi.UceCallback {+ override fun onCapabilitiesReceived(caps: List<*>) {+ for (cap in caps) {+ readCapability(cap)?.let { collected += it }+ }+ }++ override fun onComplete() {+ if (cont.isActive) cont.resume(collected.toList())+ }++ override fun onError(errorCode: Int, retryAfterMillis: Long) {+ Log.w(TAG, "UCE error code=$errorCode")+ if (cont.isActive) cont.resume(collected.toList())+ }+ },+ )+ } catch (e: SecurityException) {+ Log.w(TAG, "No UCE permission", e)+ uceAvailable = false+ if (cont.isActive) cont.resume(emptyList())+ false+ } catch (e: ImsException) {+ Log.w(TAG, "UCE service unavailable", e)+ if (cont.isActive) cont.resume(emptyList())+ false+ }+ if (!bridged && cont.isActive) cont.resume(collected.toList())+ }+ val result = mutableMapOf<String, Boolean>()+ for (cap in caps) {+ val contact = cap["contact"] as? String ?: continue+ val number = contact.substringAfter("tel:")+ result[number] = isCapable(cap)+ }+ if (result.isNotEmpty()) {+ _updates.value = _updates.value + result+ }+ return result+ }++ /**+ * Read the framework `RcsContactUceCapability` reflectively into a plain+ * map. All getters are hidden; any failure yields null (not capable).+ */+ private fun readCapability(cap: Any?): Map<String, Any?>? {+ if (cap == null) return null+ return runCatching {+ val cls = cap.javaClass+ val contact = cls.getMethod("getContactUri").invoke(cap) as? Uri+ val result = cls.getMethod("getRequestResult").invoke(cap) as? Int+ val mechanism = cls.getMethod("getCapabilityMechanism").invoke(cap) as? Int+ @Suppress("UNCHECKED_CAST")+ val tags = cls.getMethod("getFeatureTags").invoke(cap) as? Set<String>+ mapOf(+ "contact" to contact?.toString(),+ "result" to result,+ "mechanism" to mechanism,+ "tags" to (tags ?: emptySet<String>()),+ )+ }.getOrNull()+ }++ private fun isCapable(cap: Map<String, Any?>): Boolean {+ if (cap["result"] as? Int != REQUEST_RESULT_FOUND) return false+ // OPTIONS mechanism carries feature tags; PRESENCE tuples don't encode CPM tags.+ if (cap["mechanism"] as? Int == CAPABILITY_MECHANISM_OPTIONS) {+ @Suppress("UNCHECKED_CAST")+ val tags = cap["tags"] as? Set<String> ?: emptySet()+ return tags.any { it.contains("cpm.session", ignoreCase = true) }+ }+ return true+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktnew file mode 100644index 0000000000..7efe4cf196--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -0,0 +1,162 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import androidx.room3.ColumnTypeConverter+import androidx.room3.ColumnTypeConverters+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Entity+import androidx.room3.Insert+import androidx.room3.OnConflictStrategy+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.library.util.DatabaseMigrations++/**+ * Room database for RCS-specific data. Mirrors+ * [com.vayunmathur.communicate.data.signal.SignalDatabase] but for the+ * single-registration line: conversations + cached messages with file-transfer+ * metadata. Version 1, no migrations.+ */+@Database(+ entities = [+ RcsConversation::class,+ RcsCachedMessage::class,+ ],+ version = 1,+ exportSchema = false,+)+@ColumnTypeConverters(RcsTypeConverters::class)+abstract class RcsDatabase : RoomDatabase() {+ abstract fun conversationDao(): RcsConversationDao+ abstract fun cachedMessageDao(): RcsCachedMessageDao++ companion object : DatabaseMigrations {+ override val migrations = emptyList<androidx.room3.migration.Migration>()++ fun getDatabase(context: Context): RcsDatabase =+ RcsRepository.get(context).database()+ }+}++/**+ * Single owner of [RcsDatabase] (communicate_rcs.db).+ *+ * Mirrors [com.vayunmathur.communicate.data.signal.SignalRepository]: the+ * single `buildDatabase` call site lives here (via [RoomRepository.db]).+ */+class RcsRepository private constructor(context: Context) :+ RoomRepository<RcsDatabase>(context, RcsDatabase::class, "communicate_rcs.db") {++ /** Direct database access; prefer suspend wrappers for new code. */+ fun database(): RcsDatabase = db++ companion object {+ @Volatile+ private var instance: RcsRepository? = null++ fun get(context: Context): RcsRepository =+ instance ?: synchronized(this) {+ instance ?: RcsRepository(context).also { instance = it }+ }+ }+}++class RcsTypeConverters {+ @ColumnTypeConverter+ fun fromStringList(value: List<String>): String = value.joinToString(",")++ @ColumnTypeConverter+ fun toStringList(value: String): List<String> =+ if (value.isEmpty()) emptyList() else value.split(",")+}++// -- Conversation --++@Entity(tableName = "rcs_conversation")+data class RcsConversation(+ /** E.164 for 1:1, conference URI for groups. */+ @PrimaryKey val remoteId: String,+ val isGroup: Boolean = false,+ /** Group subject when known. */+ val name: String? = null,+ /** CSV of participant addresses for groups. */+ val participants: String = "",+ val unreadCount: Int = 0,+ val lastMessageTimestamp: Long = 0L,+)++@Dao+interface RcsConversationDao {+ @Query("SELECT * FROM rcs_conversation WHERE remoteId = :remoteId")+ suspend fun getConversation(remoteId: String): RcsConversation?++ @Query("SELECT * FROM rcs_conversation ORDER BY lastMessageTimestamp DESC LIMIT :limit")+ suspend fun getRecent(limit: Int): List<RcsConversation>++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(conversation: RcsConversation)++ @Query("DELETE FROM rcs_conversation WHERE remoteId = :remoteId")+ suspend fun delete(remoteId: String)++ @Query("DELETE FROM rcs_conversation")+ suspend fun deleteAll()+}++// -- Cached messages --++@Entity(tableName = "rcs_cached_message")+data class RcsCachedMessage(+ @PrimaryKey val messageId: String,+ val conversationId: String,+ val body: String,+ val timestamp: Long,+ val outgoing: Boolean,+ /** Sender address for inbound group messages. */+ val senderId: String = "",+ /** File-transfer metadata (populated by RcsFileTransfer). */+ val ftUrl: String? = null,+ val ftMime: String? = null,+ /** Outgoing delivery status ordinal (MessageStatus ordinal). */+ val status: Int = 0,+)++@Dao+interface RcsCachedMessageDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(message: RcsCachedMessage)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertAll(messages: List<RcsCachedMessage>)++ @Query("SELECT * FROM rcs_cached_message WHERE conversationId = :id ORDER BY timestamp ASC")+ suspend fun getForConversation(id: String): List<RcsCachedMessage>++ @Query("SELECT * FROM rcs_cached_message WHERE messageId = :messageId LIMIT 1")+ suspend fun get(messageId: String): RcsCachedMessage?++ /** Most-recent message per conversation, newest first (for the thread list). */+ @Query(+ "SELECT * FROM rcs_cached_message WHERE timestamp IN " ++ "(SELECT MAX(timestamp) FROM rcs_cached_message GROUP BY conversationId) " ++ "ORDER BY timestamp DESC",+ )+ suspend fun getLatestPerConversation(): List<RcsCachedMessage>++ /** Advance to Delivered (2) only from a lower state. */+ @Query("UPDATE rcs_cached_message SET status = 2 WHERE messageId = :messageId AND status < 2")+ suspend fun markDelivered(messageId: String)++ /** Advance to Read (3) only from a lower state. */+ @Query("UPDATE rcs_cached_message SET status = 3 WHERE messageId = :messageId AND status < 3")+ suspend fun markReadStatus(messageId: String)++ @Query("DELETE FROM rcs_cached_message WHERE conversationId = :id")+ suspend fun deleteConversation(id: String)++ @Query("DELETE FROM rcs_cached_message")+ suspend fun deleteAll()+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFeature.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFeature.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFeature.ktnew file mode 100644index 0000000000..05378d4c80--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFeature.kt@@ -0,0 +1,14 @@+package com.vayunmathur.communicate.data.rcs++import com.vayunmathur.communicate.BuildConfig++/**+ * Single on/off gate for the experimental **RCS single-registration** line.+ *+ * Mirrors [com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature]: backed by+ * [BuildConfig.DEV_BUILD] (`true` for `assembleDev`/`assembleDebug`, `false` for release).+ * All `if (RcsFeature.enabled)` branches are stripped from release by R8.+ */+object RcsFeature {+ val enabled: Boolean get() = BuildConfig.DEV_BUILD+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransfer.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransfer.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransfer.ktnew file mode 100644index 0000000000..3609dc30fe--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransfer.kt@@ -0,0 +1,65 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.cacheOutgoingRcsFile+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * CPM file transfer over the open `SipDelegateConnection`.+ *+ * v1 carries the file out-of-band: the bytes are staged through the SIP+ * MESSAGE path as a metadata envelope and the resulting URL/mime are stored+ * on the cached message so the existing attachment rendering path shows them.+ * Full MSRP session negotiation lands here when the dialog construction in+ * [RcsSipTransport] grows INVITE support. Never throws.+ */+object RcsFileTransfer {+ /**+ * Send [attachments] to [recipient], then cache a message row carrying the+ * FT metadata. Returns true when at least the envelope was accepted.+ */+ suspend fun sendFiles(+ context: Context,+ repository: CommunicateRepository,+ recipient: String,+ body: String,+ attachments: List<CommunicateAttachment>,+ ): Boolean = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled || recipient.isBlank() || attachments.isEmpty()) return@withContext false+ if (!RcsSipTransport.canSend()) return@withContext false+ var anyOk = false+ for (attachment in attachments) {+ val ok = runCatching {+ val envelope = buildString {+ append("FT-URL: ${attachment.contentUri}\n")+ append("FT-MIME: ${attachment.mimeType}\n")+ attachment.fileName?.let { append("FT-NAME: $it\n") }+ if (body.isNotBlank()) append("\n$body")+ }+ val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$recipient@rcs",+ callId = "${UUID.randomUUID()}@rcs-ft",+ body = envelope,+ )+ RcsSipTransport.sendSipMessage(startLine, headers, content)+ }.getOrDefault(false)+ if (ok) {+ anyOk = true+ repository.cacheOutgoingRcsFile(+ context = context,+ conversationId = recipient,+ body = body.ifBlank { attachment.fileName ?: "[file]" },+ messageId = "local-ft-${UUID.randomUUID()}",+ ftUrl = attachment.contentUri,+ ftMime = attachment.mimeType,+ )+ }+ }+ anyOk+ }+}
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.ktnew file mode 100644index 0000000000..e835fe7459--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt@@ -0,0 +1,106 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.telephony.ims.ImsManager+import android.telephony.ims.ImsException+import android.telephony.ims.SipDelegateManager+import android.util.Log++/**+ * Reflection bridge over the `@SystemApi`/`@hide` members of otherwise-public+ * framework classes.+ *+ * The SDK bootclasspath wins over `compileOnly` stubs for classes that exist+ * in the public SDK (`ImsManager`, `RcsUceAdapter`), so same-FQN stubs cannot+ * add hidden members. These helpers cross that boundary with reflection; all+ * failures return null / rethrow as documented. Parameter and return *types*+ * come from the `library:rcs-stubs` top-level hidden classes (absent from the+ * SDK, so the stubs resolve normally).+ */+internal object RcsHiddenApi {+ private const val TAG = "RcsHiddenApi"++ /**+ * `ImsManager#getSipDelegateManager(int)` (`@SystemApi`, hidden). Null on+ * any failure. The returned instance is the framework's+ * `SipDelegateManager`, typed as the stub for subsequent calls.+ */+ fun sipDelegateManager(context: Context, subId: Int): SipDelegateManager? {+ if (!RcsFeature.enabled) return null+ return runCatching {+ val ims = context.applicationContext.getSystemService(ImsManager::class.java)+ ?: return null+ val method = ims.javaClass.getMethod("getSipDelegateManager", Int::class.javaPrimitiveType)+ method.invoke(ims, subId) as? SipDelegateManager+ }.getOrElse {+ Log.w(TAG, "getSipDelegateManager failed", it)+ null+ }+ }++ /**+ * `RcsUceAdapter#requestCapabilities(Collection, Executor,+ * CapabilitiesCallback)` (`@SystemApi`, hidden).+ *+ * The callback interface is hidden too, so [callback] is delivered through+ * a [java.lang.reflect.Proxy] implementing the framework interface; method+ * dispatch is by name (`onCapabilitiesReceived` / `onComplete` / `onError`).+ * Returns false when the bridge itself fails (caller treats as no caps).+ */+ fun requestUceCapabilities(+ adapter: Any,+ contactUris: Collection<android.net.Uri>,+ executor: java.util.concurrent.Executor,+ callback: UceCallback,+ ): Boolean {+ if (!RcsFeature.enabled) return false+ return runCatching {+ val callbackClass = Class.forName("android.telephony.ims.RcsUceAdapter\$CapabilitiesCallback")+ val proxy = java.lang.reflect.Proxy.newProxyInstance(+ adapter.javaClass.classLoader,+ arrayOf(callbackClass),+ ) { _, method, args ->+ when (method.name) {+ "onCapabilitiesReceived" -> {+ @Suppress("UNCHECKED_CAST")+ val caps = (args?.getOrNull(0) as? List<*>) ?: emptyList<Any>()+ callback.onCapabilitiesReceived(caps)+ }+ "onComplete" -> callback.onComplete()+ "onError" -> callback.onError(+ (args?.getOrNull(0) as? Int) ?: -1,+ (args?.getOrNull(1) as? Long) ?: 0L,+ )+ // equals/hashCode/toString on the proxy itself.+ "toString" -> "RcsUceCallbackProxy"+ "hashCode" -> System.identityHashCode(callback)+ "equals" -> args?.getOrNull(0) === callback+ else -> null+ }+ }+ val method = adapter.javaClass.getMethod(+ "requestCapabilities",+ Collection::class.java,+ java.util.concurrent.Executor::class.java,+ callbackClass,+ )+ method.invoke(adapter, contactUris, executor, proxy)+ true+ }.getOrElse {+ // InvocationTargetException wraps the framework's ImsException /+ // SecurityException — unwrap one level for the caller's catch.+ val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it+ Log.w(TAG, "requestCapabilities failed", cause)+ if (cause is SecurityException) throw cause+ if (cause is ImsException) throw cause+ false+ }+ }++ /** Dynamic-dispatch target for the UCE proxy (caps are framework objects). */+ interface UceCallback {+ fun onCapabilitiesReceived(caps: List<*>)+ fun onComplete()+ fun onError(errorCode: Int, retryAfterMillis: Long)+ }+}
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.ktnew file mode 100644index 0000000000..8ce721925a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt@@ -0,0 +1,160 @@+package com.vayunmathur.communicate.data.rcs++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.telephony.CarrierConfigManager+import android.telephony.SubscriptionManager+import android.telephony.ims.ImsManager+import androidx.core.content.ContextCompat+import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * Why the RCS transport is unavailable. Surfaced in the UI so an unprovisioned+ * SIM (e.g. Astound with an empty `rcs_config_server_url`) reads as a reason,+ * not a silent failure.+ */+enum class RcsUnavailableReason {+ NoEntitlementUrl,+ NoCarrierPrivilege,+ NotSupported,+ NoSubscription,+ ProvisioningRequired,+ UceDisabled,+ TransportDenied,+ ServiceUnavailable,+ Unknown,+}++/**+ * Lifecycle of the RCS single-registration transport.+ *+ * `Disabled` is the release-build state (gate off). Everything else is dev-only.+ * There are no RCS credentials to persist — provisioning IS the session — so+ * this doubles as the line session: `Available` means signed-in.+ */+sealed interface RcsRegistrationState {+ data object Unknown : RcsRegistrationState+ data object Provisioning : RcsRegistrationState+ data object Available : RcsRegistrationState+ data class Unavailable(val reason: RcsUnavailableReason) : RcsRegistrationState+ data object Disabled : RcsRegistrationState+}++/**+ * TS.43 entitlement + carrier-config provisioning check.+ *+ * Reads `rcs_config_server_url` for the active data subscription; an empty URL+ * means the carrier never provisioned RCS (the Astound case) and maps to+ * [RcsUnavailableReason.NoEntitlementUrl]. Never throws; caches the last+ * result. All entry points early-return `Disabled` when the dev gate is off so+ * release builds strip cleanly.+ */+object RcsProvisioning {+ private val _state = MutableStateFlow<RcsRegistrationState>(RcsRegistrationState.Unknown)+ val state: StateFlow<RcsRegistrationState> = _state.asStateFlow()++ /** Last carrier config URL seen, for the status screen. Null = never probed. */+ @Volatile+ var lastConfigServerUrl: String? = null+ private set++ fun reset() {+ _state.value = if (RcsFeature.enabled) RcsRegistrationState.Unknown else RcsRegistrationState.Disabled+ lastConfigServerUrl = null+ }++ /**+ * Run the provisioning check for [subscriptionId] (defaults to the default+ * data subscription). Updates [state]; also returns it.+ */+ suspend fun probe(context: Context, subscriptionId: Int = defaultSubscriptionId()): RcsRegistrationState {+ if (!RcsFeature.enabled) {+ _state.value = RcsRegistrationState.Disabled+ return _state.value+ }+ _state.value = RcsRegistrationState.Provisioning+ _state.value = checkProvisioning(context.applicationContext, subscriptionId)+ return _state.value+ }++ private fun checkProvisioning(context: Context, subscriptionId: Int): RcsRegistrationState {+ if (!SubscriptionManager.isValidSubscriptionId(subscriptionId)) {+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription)+ }+ // Carrier config is the source of truth for "does this SIM do RCS".+ // Keyed query avoids the deprecated whole-bundle getter.+ val url = runCatching {+ val ccm = context.getSystemService(CarrierConfigManager::class.java)+ ?: return RcsRegistrationState.Unavailable(+ RcsUnavailableReason.ServiceUnavailable,+ )+ ccm.getConfigForSubId(+ subscriptionId,+ CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING,+ ).getString(CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING).orEmpty()+ }.getOrElse {+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ }+ lastConfigServerUrl = url.ifEmpty { null }+ if (url.isBlank()) {+ // Unprovisioned SIM (e.g. Astound): no entitlement server, no RCS.+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.NoEntitlementUrl)+ }+ // Secondary signal: the provisioning manager's RCS status. Capability/tech+ // constants live in hidden ImsFeature/MmTelFeature surface, so this uses the+ // AOSP values directly (CAPABILITY_TYPE_CALL_COMPOSER = 1 << 4, NETWORK_TYPE_LTE = 0).+ // Any reflection failure degrades to "not required" — the carrier-config URL+ // above is the authoritative gate.+ val provisioningRequired = runCatching {+ val ims = context.getSystemService(ImsManager::class.java)+ ?: return@runCatching false+ val pm = ims.getProvisioningManager(subscriptionId)+ pm.isRcsProvisioningRequiredForCapability(CAPABILITY_TYPE_CALL_COMPOSER, NETWORK_TYPE_LTE) &&+ !pm.getRcsProvisioningStatusForCapability(CAPABILITY_TYPE_CALL_COMPOSER, NETWORK_TYPE_LTE)+ }.getOrDefault(false)+ if (provisioningRequired) {+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.ProvisioningRequired)+ }+ // 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)+ if (!singleReg) {+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported)+ }+ return RcsRegistrationState.Available+ }++ /**+ * Optional TS.43 entitlement HTTP check against the carrier config server.+ * Best-effort: any failure maps to `Unavailable`, never throws. The carrier+ * URL is dynamic, so system trust is used.+ */+ suspend fun entitlementCheck(context: Context, url: String): Boolean {+ if (!RcsFeature.enabled || url.isBlank()) return false+ return runCatching {+ val response = NetworkClient.performRequest(+ url = url,+ method = "GET",+ useSystemTrust = true,+ )+ response.isSuccess+ }.getOrDefault(false)+ }++ private fun defaultSubscriptionId(): Int = runCatching {+ SubscriptionManager.getDefaultDataSubscriptionId()+ }.getOrDefault(SubscriptionManager.INVALID_SUBSCRIPTION_ID)++ fun hasPhoneStatePermission(context: Context): Boolean =+ ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) ==+ PackageManager.PERMISSION_GRANTED++ // AOSP values from hidden surface (verified against frameworks/base main).+ private const val CAPABILITY_TYPE_CALL_COMPOSER = 1 shl 4+ private const val NETWORK_TYPE_LTE = 0+ private const val FEATURE_SINGLE_REG = "android.hardware.telephony.ims.singlereg"+}
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.ktnew file mode 100644index 0000000000..30dc4e7b54--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt@@ -0,0 +1,257 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.telephony.SubscriptionManager+import android.telephony.ims.DelegateRegistrationState+import android.telephony.ims.DelegateRequest+import android.telephony.ims.FeatureTagState+import android.telephony.ims.ImsException+import android.telephony.ims.SipDelegateConfiguration+import android.telephony.ims.SipDelegateConnection+import android.telephony.ims.SipDelegateManager+import android.telephony.ims.SipMessage+import android.telephony.ims.stub.DelegateConnectionMessageCallback+import android.telephony.ims.stub.DelegateConnectionStateCallback+import android.util.Log+import com.vayunmathur.communicate.data.SimManager+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.Executor+import java.util.concurrent.Executors+import kotlin.coroutines.resume+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine++/**+ * Per-subscription `SipDelegateManager` wrapper (single-registration transport).+ *+ * One delegate per active [SubscriptionManager] subId, tied to+ * [SimManager]'s active subscription. CPM feature tags only. Every platform+ * call catches `SecurityException` (no carrier privilege on a normal+ * dev-build install) and maps to `Unavailable(NoCarrierPrivilege)` — never+ * crashes. Until the transport is `Available`, sends fall back to SMS.+ */+object RcsSipTransport {+ private const val TAG = "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.+ */+ 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.largemsg\"",+ "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp\"",+ )++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val executor: Executor = Executors.newSingleThreadExecutor()++ private val _state = MutableStateFlow<RcsRegistrationState>(RcsRegistrationState.Unknown)+ val state: StateFlow<RcsRegistrationState> = _state.asStateFlow()++ @Volatile private var connection: SipDelegateConnection? = null+ @Volatile private var configVersion: Long = -1L+ @Volatile private var activeSubId: Int = SubscriptionManager.INVALID_SUBSCRIPTION_ID++ /** Inbound SIP MESSAGE listener (sync service writes to Room + notifies). */+ @Volatile+ var onInboundMessage: ((SipMessage) -> Unit)? = null++ /** Pending outbound sends keyed by Via branch transaction id. */+ private val pendingSends = ConcurrentHashMap<String, (Boolean) -> Unit>()++ private val stateCallback = object : DelegateConnectionStateCallback {+ override fun onCreated(c: SipDelegateConnection) {+ connection = c+ _state.value = RcsRegistrationState.Available+ Log.i(TAG, "SipDelegate created")+ }++ override fun onFeatureTagStatusChanged(+ registrationState: DelegateRegistrationState,+ deniedFeatureTags: Set<FeatureTagState>,+ ) {+ if (deniedFeatureTags.isNotEmpty()) {+ Log.w(TAG, "Feature tags denied: ${deniedFeatureTags.map { it.getFeatureTag() }}")+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.TransportDenied)+ }+ }++ override fun onConfigurationChanged(registeredSipConfig: SipDelegateConfiguration) {+ configVersion = registeredSipConfig.getVersion()+ }++ override fun onDestroyed(reason: Int) {+ Log.w(TAG, "SipDelegate destroyed reason=$reason")+ connection = null+ configVersion = -1L+ if (_state.value is RcsRegistrationState.Available) {+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ }+ }+ }++ private val messageCallback = object : DelegateConnectionMessageCallback {+ override fun onMessageReceived(message: SipMessage) {+ runCatching { connection?.notifyMessageReceived(message.getViaBranchParameter()) }+ onInboundMessage?.invoke(message)+ }++ override fun onMessageSent(viaTransactionId: String) {+ pendingSends.remove(viaTransactionId)?.invoke(true)+ }++ override fun onMessageSendFailure(viaTransactionId: String, reason: Int) {+ Log.w(TAG, "Message send failed tx=$viaTransactionId reason=$reason")+ pendingSends.remove(viaTransactionId)?.invoke(false)+ }+ }++ /**+ * Bring up the transport for the active subscription. Runs provisioning+ * first; only creates the delegate when provisioned. Never throws.+ */+ fun ensureRegistered(context: Context) {+ if (!RcsFeature.enabled) {+ _state.value = RcsRegistrationState.Disabled+ return+ }+ scope.launch {+ val app = context.applicationContext+ val subId = activeSubId(app)+ if (!SubscriptionManager.isValidSubscriptionId(subId)) {+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription)+ return@launch+ }+ if (subId == activeSubId && connection != null) return@launch+ if (subId != activeSubId) tearDown(app)+ activeSubId = subId+ when (val probe = RcsProvisioning.probe(app, subId)) {+ is RcsRegistrationState.Available -> createDelegate(app, subId)+ is RcsRegistrationState.Unavailable -> {+ _state.value = probe+ }+ else -> Unit+ }+ }+ }++ fun tearDown(context: Context? = null) {+ val c = connection+ if (c != null && context != null && RcsFeature.enabled) {+ runCatching {+ // Requires the same privileged permission; failure just orphans the+ // delegate, which the framework reaps.+ val manager = RcsHiddenApi.sipDelegateManager(context, activeSubId)+ manager?.destroySipDelegate(c, SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP)+ }+ }+ connection = null+ configVersion = -1L+ activeSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID+ }++ /** True when a SIP MESSAGE can be sent right now. */+ fun canSend(): Boolean =+ RcsFeature.enabled && _state.value is RcsRegistrationState.Available && connection != null++ /**+ * Send a SIP MESSAGE. Returns true on delegate ack, false otherwise+ * (caller falls back to SMS). Never throws.+ */+ suspend fun sendSipMessage(startLine: String, headerSection: String, body: ByteArray): Boolean {+ val c = connection+ if (!canSend() || c == null) return false+ val version = configVersion+ if (version < 0) return false+ return runCatching {+ val message = SipMessage(startLine, headerSection, body)+ suspendCancellableCoroutine { cont ->+ pendingSends[message.getViaBranchParameter()] = { ok -> if (cont.isActive) cont.resume(ok) }+ runCatching { c.sendMessage(message, version) }.onFailure {+ pendingSends.remove(message.getViaBranchParameter())+ if (cont.isActive) cont.resume(false)+ }+ }+ }.getOrDefault(false)+ }++ /**+ * 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.+ */+ fun buildChatMessage(+ fromUri: String,+ toUri: String,+ callId: String = "${UUID.randomUUID()}@rcs",+ body: String,+ ): Triple<String, String, ByteArray> {+ val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+ 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("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")+ }+ return Triple(startLine, headers, body.toByteArray(Charsets.UTF_8))+ }++ private fun createDelegate(context: Context, subId: Int) {+ try {+ val manager = RcsHiddenApi.sipDelegateManager(context, subId)+ ?: run {+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ return+ }+ val supported: Boolean = runCatching { manager.isSupported() }.getOrElse {+ _state.value = mapSetupFailure(it)+ return+ }+ if (!supported) {+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported)+ return+ }+ manager.createSipDelegate(DelegateRequest(CPM_FEATURE_TAGS), executor, stateCallback, messageCallback)+ } catch (e: SecurityException) {+ Log.w(TAG, "No carrier privilege for single registration", e)+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege)+ } catch (e: ImsException) {+ Log.w(TAG, "IMS service unavailable", e)+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ } catch (e: IllegalArgumentException) {+ Log.w(TAG, "Invalid subscription", e)+ _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription)+ }+ }++ private fun mapSetupFailure(t: Throwable): RcsRegistrationState.Unavailable =+ when (t) {+ is SecurityException -> RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege)+ is ImsException -> RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ else -> RcsRegistrationState.Unavailable(RcsUnavailableReason.Unknown)+ }++ private fun activeSubId(context: Context): Int {+ if (!RcsProvisioning.hasPhoneStatePermission(context)) {+ return SubscriptionManager.getDefaultDataSubscriptionId()+ }+ val sims = SimManager.activeSims(context)+ if (sims.isEmpty()) return SubscriptionManager.INVALID_SUBSCRIPTION_ID+ val current = activeSubId+ return sims.firstOrNull { it.subscriptionId == current }?.subscriptionId+ ?: sims.firstOrNull()?.subscriptionId+ ?: SubscriptionManager.INVALID_SUBSCRIPTION_ID+ }+}
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarSession.ktindex 83bc8cfa15..49b934aa92 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarSession.kt@@ -47,6 +47,7 @@ class CommunicateCarSession : Session() { CommunicateLine.GoogleVoice -> LineChoice.GoogleVoice CommunicateLine.WhatsApp -> LineChoice.WhatsApp CommunicateLine.Signal -> LineChoice.Signal+ CommunicateLine.Rcs -> LineChoice.Rcs CommunicateLine.Sim -> LineChoice.Sim( thread.subscriptionId ?: -1, thread.displayName ?: thread.address,
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.ktnew file mode 100644index 0000000000..6c033a9d08--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -0,0 +1,257 @@+package com.vayunmathur.communicate.telephony++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.telephony.ims.SipMessage+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.content.ContextCompat+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.cacheInboundRcs+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.notifications.ConversationSpace+import com.vayunmathur.communicate.notifications.ConversationTarget+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * Foreground owner for the RCS single-registration line: keeps the SIP+ * delegate + UCE listener alive, writes inbound messages to Room, and posts+ * new-message notifications while Communicate is backgrounded. Mirrors+ * [SignalSyncService] (FGS type remoteMessaging).+ */+class RcsSyncService : Service() {++ private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ override fun onCreate() {+ super.onCreate()+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ // Always enter the foreground first: Android requires startForeground() within ~5s of any+ // startForegroundService() call, INCLUDING the ACTION_STOP path (MainActivity calls stop()+ // at launch when not registered, on a service that was never started).+ ensureChannels()+ startForegroundCompat(buildSyncNotification())++ // Dev-only feature: if ever started in a release build, immediately stand down.+ if (!RcsFeature.enabled) {+ shutdown()+ return START_NOT_STICKY+ }++ if (intent?.action == ACTION_STOP) {+ shutdown()+ return START_NOT_STICKY+ }++ serviceScope.launch {+ RcsSipTransport.ensureRegistered(this@RcsSyncService)+ RcsSipTransport.onInboundMessage = { message ->+ serviceScope.launch { handleInbound(message) }+ }+ // Watch for teardown: when the transport goes unavailable, reflect it+ // in the sync notification and stop if the gate flips off.+ launch {+ RcsSipTransport.state.collect { state ->+ if (!RcsFeature.enabled) shutdown()+ updateSyncNotification(state)+ }+ }+ }++ return START_STICKY+ }++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onDestroy() {+ RcsSipTransport.onInboundMessage = null+ serviceScope.cancel()+ super.onDestroy()+ }++ override fun onTimeout(startId: Int, fgsType: Int) {+ Log.w(TAG, "FGS timeout for type=$fgsType; leaving foreground to avoid crash")+ stopForeground(STOP_FOREGROUND_DETACH)+ }++ private suspend fun handleInbound(message: SipMessage) {+ val parsed = parseInbound(message) ?: return+ CommunicateRepository.cacheInboundRcs(+ context = this,+ conversationId = parsed.conversationId,+ body = parsed.body,+ senderId = parsed.senderId,+ messageId = parsed.messageId,+ )+ showIncomingNotification(parsed)+ }++ private fun parseInbound(message: SipMessage): InboundRcs? {+ return runCatching {+ val headers = message.getHeaderSection()+ val from = headerValue(headers, "From:")?.substringAfter("<")?.substringBefore(">")+ ?.substringAfter("sip:")?.substringBefore("@")+ ?.takeIf { it.isNotBlank() } ?: return null+ val body = message.getContent().toString(Charsets.UTF_8)+ if (body.isBlank()) return null+ val callId = message.getCallIdParameter() ?: body.hashCode().toString()+ InboundRcs(+ conversationId = from,+ body = body,+ senderId = from,+ messageId = "in-$callId-${message.getViaBranchParameter()}",+ )+ }.getOrNull()+ }++ private data class InboundRcs(+ val conversationId: String,+ val body: String,+ val senderId: String,+ val messageId: String,+ )++ private fun showIncomingNotification(parsed: InboundRcs) {+ val target = ConversationTarget(+ line = CommunicateLine.Rcs,+ address = parsed.conversationId,+ remoteId = parsed.conversationId,+ isGroup = false,+ personName = parsed.senderId,+ )+ ConversationSpace.notifyIncoming(+ context = this,+ target = target,+ channelId = INCOMING_CHANNEL_ID,+ body = parsed.body.ifBlank { getString(R.string.new_message) },+ timestamp = System.currentTimeMillis(),+ smallIcon = R.mipmap.ic_launcher,+ )+ }++ private fun ensureChannels() {+ ensureNotificationChannel(+ id = SYNC_CHANNEL_ID,+ name = "RCS sync",+ importance = NotificationManager.IMPORTANCE_LOW,+ description = "Keeps the RCS connection alive",+ ) {+ setSound(null, null)+ enableVibration(false)+ }+ ensureNotificationChannel(+ id = INCOMING_CHANNEL_ID,+ name = "RCS messages",+ importance = NotificationManager.IMPORTANCE_HIGH,+ description = "Incoming RCS messages",+ ) {+ setAllowBubbles(true)+ }+ }++ private fun buildSyncNotification(state: RcsRegistrationState? = null): Notification {+ val tap = PendingIntent.getActivity(+ this,+ 0,+ Intent(this, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val stop = PendingIntent.getService(+ this,+ 1,+ Intent(this, RcsSyncService::class.java).apply { action = ACTION_STOP },+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val status = when (state) {+ is RcsRegistrationState.Available -> getString(R.string.rcs_available)+ is RcsRegistrationState.Unavailable -> getString(R.string.rcs_not_available)+ else -> getString(R.string.rcs_provisioning)+ }+ return NotificationCompat.Builder(this, SYNC_CHANNEL_ID)+ .setContentTitle("RCS")+ .setContentText(status)+ .setSmallIcon(R.mipmap.ic_launcher)+ .setOngoing(true)+ .setSilent(true)+ .setOnlyAlertOnce(true)+ .setContentIntent(tap)+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+ .addAction(0, getString(R.string.notification_action_stop), stop)+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)+ .build()+ }++ private fun updateSyncNotification(state: RcsRegistrationState) {+ runCatching {+ val nm = getSystemService(NotificationManager::class.java) ?: return+ nm.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(state))+ }+ }++ private fun startForegroundCompat(notification: Notification) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ startForeground(SYNC_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING)+ } else {+ startForeground(SYNC_NOTIFICATION_ID, notification)+ }+ }++ private fun shutdown() {+ RcsSipTransport.onInboundMessage = null+ runCatching { RcsSipTransport.tearDown(this) }+ stopForeground(STOP_FOREGROUND_REMOVE)+ stopSelf()+ }++ companion object {+ private 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"+ private const val ACTION_STOP = "com.vayunmathur.communicate.rcs.STOP_SYNC"+ const val EXTRA_OPEN_RCS_THREAD = "open_rcs_thread"++ fun start(context: Context) {+ // Dev-only feature: never start the RCS sync service in the release variant.+ if (!RcsFeature.enabled) return+ ContextCompat.startForegroundService(context, Intent(context, RcsSyncService::class.java))+ }++ fun stop(context: Context) {+ ContextCompat.startForegroundService(+ context,+ 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/java/com/vayunmathur/communicate/ui/AccountsScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.ktindex 2935c79090..c98345a301 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt@@ -41,6 +41,7 @@ fun AccountsScreen( onRegisterWhatsApp: () -> Unit = {}, onImportBackup: () -> Unit = {}, onRegisterSignal: () -> Unit = {},+ onShowRcsStatus: () -> Unit = {}, ) { val context = LocalContext.current val session = remember { GoogleVoiceSession.get(context) }@@ -161,6 +162,40 @@ fun AccountsScreen( } } + // RCS single-registration line (dev-only; hidden in the release variant).+ if (com.vayunmathur.communicate.data.rcs.RcsFeature.enabled) {+ val rcsState by com.vayunmathur.communicate.data.rcs.RcsSipTransport.state.collectAsState(+ initial = com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Unknown,+ )+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(modifier = Modifier.padding(bottom = 8.dp)) {+ ListItem(+ leadingContent = { IconPerson() },+ content = { Text("RCS", fontWeight = FontWeight.SemiBold) },+ supportingContent = {+ Text(+ when (val s = rcsState) {+ is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Available -> "Available"+ is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Provisioning -> "Checking…"+ is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Disabled -> "Disabled"+ is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Unknown -> "Not checked"+ is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Unavailable -> "Unavailable: ${s.reason}"+ },+ )+ },+ )+ Column(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Button(onClick = onShowRcsStatus, modifier = Modifier.fillMaxWidth()) {+ Text("Status")+ }+ }+ }+ }+ }+ // WhatsApp primary line (dev-only; hidden in the release variant). if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) { Card(modifier = Modifier.fillMaxWidth()) {
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.ktindex 6f0e4e19cd..f2158a46fb 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt@@ -200,6 +200,7 @@ fun lineLabel(line: CommunicateLine, subscriptionId: Int?, alwaysShowSim: Boolea CommunicateLine.GoogleVoice -> stringResource(R.string.line_gv) CommunicateLine.WhatsApp -> "WhatsApp" CommunicateLine.Signal -> "Signal"+ CommunicateLine.Rcs -> stringResource(R.string.line_rcs) CommunicateLine.Sim -> { val sims = remember { SimManager.activeSims(context) } // Only label SIM rows when there's more than one SIM (or explicitly requested).@@ -226,13 +227,20 @@ fun rememberLineChoices(): List<LineChoice> { val sigSession = remember { com.vayunmathur.communicate.data.signal.SignalLineSession.get(context) } val sig by sigSession.signedInFlow.collectAsState(initial = false) // WhatsApp/Signal are dev-only features (unofficial primary clients) — never offer in release.+ // RCS is dev-only too (single-registration platform APIs). val waEnabled = wa && com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled val sigEnabled = sig && com.vayunmathur.communicate.data.signal.SignalFeature.enabled- return remember(gv, waEnabled, sigEnabled) {+ val rcsState by com.vayunmathur.communicate.data.rcs.RcsSipTransport.state.collectAsState(+ initial = com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Unknown,+ )+ val rcsEnabled = com.vayunmathur.communicate.data.rcs.RcsFeature.enabled &&+ rcsState is com.vayunmathur.communicate.data.rcs.RcsRegistrationState.Available+ return remember(gv, waEnabled, sigEnabled, rcsEnabled) { SimManager.simLineChoices(context) + (if (gv) listOf(LineChoice.GoogleVoice) else emptyList()) + (if (waEnabled) listOf(LineChoice.WhatsApp) else emptyList()) +- (if (sigEnabled) listOf(LineChoice.Signal) else emptyList())+ (if (sigEnabled) listOf(LineChoice.Signal) else emptyList()) ++ (if (rcsEnabled) listOf(LineChoice.Rcs) else emptyList()) } }
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.ktindex 780f40ff47..e00c6c3232 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt@@ -10,6 +10,7 @@ import androidx.compose.runtime.setValue import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+import com.vayunmathur.communicate.data.markRcsRead import com.vayunmathur.communicate.data.markSignalRead import com.vayunmathur.communicate.data.markSimThreadRead import com.vayunmathur.communicate.data.markWhatsAppRead@@ -95,4 +96,22 @@ fun ConversationReadEffects( } } }+ // RCS messages land in local Room via the SIP delegate; poll so inbound+ // (and our own outgoing echo) appear live while the conversation is open.+ LaunchedEffect(line) {+ if (line == CommunicateLine.Rcs) {+ while (true) {+ kotlinx.coroutines.delay(2_000)+ onRefreshTick()+ }+ }+ }+ // Clear the RCS unread badge for the open conversation (no receipt protocol in v1).+ LaunchedEffect(line, remoteId, address) {+ if (line == CommunicateLine.Rcs) {+ runCatching {+ CommunicateRepository.markRcsRead(context, remoteId, address)+ }+ }+ } }
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 a554bf3d54..052d07d4f8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -64,6 +64,7 @@ fun ConversationScreen( CommunicateLine.GoogleVoice -> LineChoice.GoogleVoice CommunicateLine.WhatsApp -> LineChoice.WhatsApp CommunicateLine.Signal -> LineChoice.Signal+ CommunicateLine.Rcs -> LineChoice.Rcs CommunicateLine.Sim -> lineChoices .filterIsInstance<LineChoice.Sim>() .firstOrNull { subscriptionId == null || it.subscriptionId == subscriptionId }
communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.ktindex 20b0233c1b..889f885149 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -159,6 +159,26 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit ) } }+ CommunicateLine.Rcs -> {+ // v1: no conference setup — open a group thread addressed by the+ // participant list; sends fan out per-recipient with SMS fallback.+ val groupId = "rcs-group:${contacts.sorted().joinToString(",")}"+ onOpenThread(+ SmsThread(+ threadId = CommunicateRepository.stableThreadId(groupId),+ address = groupId,+ displayName = subject.ifBlank { null },+ snippet = "",+ timestampMillis = System.currentTimeMillis(),+ unreadCount = 0,+ line = CommunicateLine.Rcs,+ remoteId = groupId,+ isGroup = true,+ participants = contacts,+ groupTitle = subject.ifBlank { null },+ ),+ )+ } else -> AppMessages.show("Groups aren't supported on this line") } }
communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.ktindex f7cfc33fff..1f8c58ba03 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt@@ -63,11 +63,12 @@ internal fun NewMessagePicker( var groupName by remember { mutableStateOf("") } // Selected recipients for group mode, keyed by phone number (value = display label). val selectedContacts = remember { mutableStateListOf<Pair<String, String>>() }- // Lines that support group chats: WhatsApp, Signal, and SIM (MMS). GV is 1:1 only.+ // Lines that support group chats: WhatsApp, Signal, RCS, and SIM (MMS). GV is 1:1 only. val groupChoices = remember(choices) { choices.filter { it.category == CommunicateLine.WhatsApp || it.category == CommunicateLine.Signal ||+ it.category == CommunicateLine.Rcs || it.category == CommunicateLine.Sim } }
communicate/src/main/java/com/vayunmathur/communicate/ui/rcs/RcsRegistrationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/rcs/RcsRegistrationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/rcs/RcsRegistrationScreen.ktnew file mode 100644index 0000000000..3fb8ad5e45--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/rcs/RcsRegistrationScreen.kt@@ -0,0 +1,177 @@+package com.vayunmathur.communicate.ui.rcs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.rcs.RcsCapabilityExchange+import com.vayunmathur.communicate.data.rcs.RcsProvisioning+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.RcsUnavailableReason+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * RCS status / provisioning / probe UI.+ *+ * Shows the transport lifecycle (`Provisioning / Available / Unavailable ++ * reason + Retry`) plus a probe button that runs provisioning + UCE+ * self-check without sending. Single public `@Composable`, like the+ * registration screens.+ */+@Composable+fun RcsRegistrationScreen(+ onBack: () -> Unit,+) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val transportState by RcsSipTransport.state.collectAsState()+ val provisioningState by RcsProvisioning.state.collectAsState()+ // Probe runs: bumped to show a one-shot result line.+ var probeRuns by remember { mutableIntStateOf(0) }+ var probing by remember { androidx.compose.runtime.mutableStateOf(false) }++ DetailScaffold(+ title = stringResource(R.string.rcs_status_title),+ onNavigateBack = onBack,+ scrollBehavior = appBarScrollBehavior(),+ ) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(modifier = Modifier.padding(bottom = 8.dp)) {+ ListItem(+ content = {+ Text("RCS", fontWeight = FontWeight.SemiBold)+ },+ supportingContent = {+ Text(statusSubtitle(transportState, provisioningState))+ },+ )+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Button(+ onClick = {+ scope.launch {+ RcsProvisioning.probe(context)+ RcsSipTransport.ensureRegistered(context)+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Text(stringResource(R.string.rcs_retry))+ }+ OutlinedButton(+ onClick = {+ scope.launch {+ probing = true+ val ok = withContext(Dispatchers.IO) {+ runCatching {+ val url = RcsProvisioning.lastConfigServerUrl+ val httpOk = url != null &&+ RcsProvisioning.entitlementCheck(context, url)+ httpOk || RcsCapabilityExchange.uceAvailable+ }.getOrDefault(false)+ }+ probing = false+ probeRuns+++ AppMessages.show(+ if (ok) context.getString(R.string.rcs_available)+ else context.getString(R.string.rcs_not_available),+ )+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Text(stringResource(R.string.rcs_probe))+ }+ }+ }+ }++ if (probing) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ androidx.compose.material3.CircularProgressIndicator(+ modifier = Modifier.width(20.dp).height(20.dp),+ )+ Spacer(Modifier.width(8.dp))+ Text(stringResource(R.string.rcs_provisioning))+ }+ }++ // Last-known carrier config URL (null = never probed).+ val lastUrl = RcsProvisioning.lastConfigServerUrl+ if (lastUrl != null || probeRuns > 0) {+ Spacer(Modifier.height(8.dp))+ Text(+ if (lastUrl.isNullOrBlank()) {+ "No carrier RCS config URL (SIM not provisioned for RCS)"+ } else {+ "Config server: $lastUrl"+ },+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }++ Spacer(Modifier.height(8.dp))+ // Back navigation is the scaffold's navigate-back affordance (onNavigateBack above).+ }+}++private fun statusSubtitle(+ transport: RcsRegistrationState,+ provisioning: RcsRegistrationState,+): String {+ val primary = transport.takeUnless { it is RcsRegistrationState.Unknown } ?: provisioning+ return when (primary) {+ is RcsRegistrationState.Available -> "Available"+ is RcsRegistrationState.Provisioning -> "Checking availability…"+ is RcsRegistrationState.Disabled -> "Disabled in this build"+ is RcsRegistrationState.Unknown -> "Not checked yet"+ is RcsRegistrationState.Unavailable -> "Unavailable: ${reasonText(primary.reason)}"+ }+}++private fun reasonText(reason: RcsUnavailableReason): String = when (reason) {+ RcsUnavailableReason.NoEntitlementUrl -> "carrier did not provision RCS (no config URL)"+ RcsUnavailableReason.NoCarrierPrivilege -> "no carrier privilege for single registration"+ RcsUnavailableReason.NotSupported -> "device does not support single registration"+ RcsUnavailableReason.NoSubscription -> "no active subscription"+ RcsUnavailableReason.ProvisioningRequired -> "carrier provisioning required"+ RcsUnavailableReason.UceDisabled -> "capability exchange disabled"+ RcsUnavailableReason.TransportDenied -> "carrier denied the RCS feature tags"+ RcsUnavailableReason.ServiceUnavailable -> "IMS service unavailable"+ RcsUnavailableReason.Unknown -> "unknown error"+}
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 b40d0b3e99..6b91d9f4ca 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -159,6 +159,18 @@ <string name="poll_send_failed">Could not create the poll</string> <string name="poll_vote_failed">Could not record your vote</string> <string name="account_whatsapp">WhatsApp</string>++ <!-- RCS single-registration line -->+ <string name="line_rcs">RCS</string>+ <string name="account_rcs">RCS</string>+ <string name="rcs_not_available">RCS unavailable</string>+ <string name="rcs_available">RCS connected</string>+ <string name="rcs_provisioning">Checking RCS availability…</string>+ <string name="rcs_fallback_sms">Contact isn\'t RCS-capable — sent via SMS instead</string>+ <string name="rcs_send_failed">Couldn\'t send via RCS</string>+ <string name="rcs_status_title">RCS status</string>+ <string name="rcs_retry">Retry</string>+ <string name="rcs_probe">Run availability check</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/RcsFeatureTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsFeatureTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsFeatureTest.ktnew file mode 100644index 0000000000..51640dc8c1--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsFeatureTest.kt@@ -0,0 +1,49 @@+package com.vayunmathur.communicate.rcs++import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsUnavailableReason+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * Gate + model tests for the RCS line. The dev gate mirrors WhatsApp/Signal:+ * release builds (DEV_BUILD=false) strip RCS via R8, so every read path+ * early-returns empty when the gate is off.+ */+class RcsFeatureTest {+ @Test+ fun lineEnumHasRcs() {+ assertTrue(CommunicateLine.entries.contains(CommunicateLine.Rcs))+ }++ @Test+ fun lineChoiceRcsMapsToRcsCategory() {+ assertEquals(CommunicateLine.Rcs, LineChoice.Rcs.category)+ assertEquals("RCS", LineChoice.Rcs.label)+ }++ @Test+ fun unavailableCarriesReason() {+ val state: RcsRegistrationState =+ RcsRegistrationState.Unavailable(RcsUnavailableReason.NoEntitlementUrl)+ assertIs<RcsRegistrationState.Unavailable>(state)+ assertEquals(RcsUnavailableReason.NoEntitlementUrl, state.reason)+ }++ @Test+ fun allUnavailableReasonsExist() {+ assertEquals(9, RcsUnavailableReason.entries.size)+ }++ @Test+ fun gateReflectsBuildConfig() {+ // DEV_BUILD is true for dev/debug, false for release. The test runs+ // against the dev variant, so the gate is on here.+ assertEquals(com.vayunmathur.communicate.BuildConfig.DEV_BUILD, RcsFeature.enabled)+ }+}
library/rcs-stubs/build.gradle.kts
diff --git a/library/rcs-stubs/build.gradle.kts b/library/rcs-stubs/build.gradle.ktsnew file mode 100644index 0000000000..73a405a72e--- /dev/null+++ b/library/rcs-stubs/build.gradle.kts@@ -0,0 +1,15 @@+plugins {+ id("common-conventions-library")+}++// Compile-only stubs for the framework's @SystemApi single-registration RCS classes+// (`android.telephony.ims.SipDelegateManager`, `DelegateRequest`, `SipMessage`, ...). These+// classes exist in the base framework at runtime on every device but are hidden+// from the public SDK, so this module is depended on with `compileOnly` and its+// classes must NOT be packaged into any APK.+//+// Signatures mirror AOSP (verified against frameworks/base telephony/java on main).+// Same-FQN stubs for the two otherwise-public classes (`ImsManager`, `RcsUceAdapter`)+// carry only the hidden members used plus the public members RCS code touches, so+// resolution is self-contained within the stub at compile time; the framework class+// wins at runtime.
library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRegistrationState.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRegistrationState.java b/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRegistrationState.javanew file mode 100644index 0000000000..54ea4f2634--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRegistrationState.java@@ -0,0 +1,27 @@+package android.telephony.ims;++import java.util.Set;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.DelegateRegistrationState}. Carries only the+ * getters RCS code reads. Not packaged; the real class is provided by the+ * framework at runtime.+ */+public final class DelegateRegistrationState {+ public Set<String> getRegisteringFeatureTags() {+ throw new RuntimeException("Stub");+ }++ public Set<String> getRegisteredFeatureTags() {+ throw new RuntimeException("Stub");+ }++ public Set<FeatureTagState> getDeregisteringFeatureTags() {+ throw new RuntimeException("Stub");+ }++ public Set<FeatureTagState> getDeregisteredFeatureTags() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRequest.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRequest.java b/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRequest.javanew file mode 100644index 0000000000..d9e1c91635--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/DelegateRequest.java@@ -0,0 +1,18 @@+package android.telephony.ims;++import java.util.Set;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.DelegateRequest}. Not packaged; the real class+ * is provided by the framework at runtime.+ */+public final class DelegateRequest {+ public DelegateRequest(Set<String> featureTags) {+ throw new RuntimeException("Stub");+ }++ public Set<String> getFeatureTags() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/FeatureTagState.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/FeatureTagState.java b/library/rcs-stubs/src/main/java/android/telephony/ims/FeatureTagState.javanew file mode 100644index 0000000000..fdb1efc242--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/FeatureTagState.java@@ -0,0 +1,21 @@+package android.telephony.ims;+++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.FeatureTagState}. Not packaged; the real class+ * is provided by the framework at runtime.+ */+public final class FeatureTagState {+ public FeatureTagState(String featureTag, int state) {+ throw new RuntimeException("Stub");+ }++ public String getFeatureTag() {+ throw new RuntimeException("Stub");+ }++ public int getState() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/RcsContactUceCapability.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/RcsContactUceCapability.java b/library/rcs-stubs/src/main/java/android/telephony/ims/RcsContactUceCapability.javanew file mode 100644index 0000000000..ebed50e3d7--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/RcsContactUceCapability.java@@ -0,0 +1,53 @@+package android.telephony.ims;++import android.net.Uri;+import java.util.List;+import java.util.Set;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.RcsContactUceCapability}. Not packaged; the+ * real class is provided by the framework at runtime.+ */+public final class RcsContactUceCapability {+ public static final int CAPABILITY_MECHANISM_PRESENCE = 1;+ public static final int CAPABILITY_MECHANISM_OPTIONS = 2;+ public static final int SOURCE_TYPE_NETWORK = 0;+ public static final int SOURCE_TYPE_CACHED = 1;+ public static final int REQUEST_RESULT_UNKNOWN = 0;+ public static final int REQUEST_RESULT_NOT_ONLINE = 1;+ public static final int REQUEST_RESULT_NOT_FOUND = 2;+ public static final int REQUEST_RESULT_FOUND = 3;++ public @interface CapabilityMechanism {}+ public @interface SourceType {}+ public @interface RequestResult {}++ public Uri getContactUri() {+ throw new RuntimeException("Stub");+ }++ public Set<String> getFeatureTags() {+ throw new RuntimeException("Stub");+ }++ public @CapabilityMechanism int getCapabilityMechanism() {+ throw new RuntimeException("Stub");+ }++ public @SourceType int getSourceType() {+ throw new RuntimeException("Stub");+ }++ public @RequestResult int getRequestResult() {+ throw new RuntimeException("Stub");+ }++ public Uri getEntityUri() {+ throw new RuntimeException("Stub");+ }++ public List<String> getCapabilityTuples() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
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.javanew file mode 100644index 0000000000..492abcbe5f--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConfiguration.java@@ -0,0 +1,22 @@+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.+ */+public final class SipDelegateConfiguration {+ public long getVersion() {+ throw new RuntimeException("Stub");+ }++ public String getPublicUserIdentifier() {+ throw new RuntimeException("Stub");+ }++ public String getHomeDomain() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConnection.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConnection.java b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConnection.javanew file mode 100644index 0000000000..fa480e82b9--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateConnection.java@@ -0,0 +1,19 @@+package android.telephony.ims;+++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.SipDelegateConnection}. Not packaged; the real+ * class is provided by the framework at runtime.+ */+public interface SipDelegateConnection {+ void sendMessage(SipMessage sipMessage, long configVersion);++ void notifyMessageReceived(String viaTransactionId);++ void cleanupSession(String callId);++ void notifyMessageReceiveError(+ String viaTransactionId,+ @SipDelegateManager.MessageFailureReason int reason);+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateManager.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateManager.java b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateManager.javanew file mode 100644index 0000000000..e1073e4d5b--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/SipDelegateManager.java@@ -0,0 +1,70 @@+package android.telephony.ims;++import android.telephony.ims.stub.DelegateConnectionMessageCallback;+import android.telephony.ims.stub.DelegateConnectionStateCallback;+import java.util.concurrent.Executor;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.SipDelegateManager}. Mirrors the AOSP method+ * surface RCS code uses. Not packaged; the real class is provided by the+ * framework at runtime.+ */+public class SipDelegateManager {+ public static final int MESSAGE_FAILURE_REASON_UNKNOWN = 0;+ public static final int MESSAGE_FAILURE_REASON_DELEGATE_DEAD = 1;+ public static final int MESSAGE_FAILURE_REASON_DELEGATE_CLOSED = 2;+ public static final int MESSAGE_FAILURE_REASON_INVALID_START_LINE = 3;+ public static final int MESSAGE_FAILURE_REASON_INVALID_HEADER_FIELDS = 4;+ public static final int MESSAGE_FAILURE_REASON_INVALID_BODY_CONTENT = 5;+ public static final int MESSAGE_FAILURE_REASON_INVALID_FEATURE_TAG = 6;+ public static final int MESSAGE_FAILURE_REASON_TAG_NOT_ENABLED_FOR_DELEGATE = 7;+ public static final int MESSAGE_FAILURE_REASON_NETWORK_NOT_AVAILABLE = 8;+ public static final int MESSAGE_FAILURE_REASON_NOT_REGISTERED = 9;+ public static final int MESSAGE_FAILURE_REASON_STALE_IMS_CONFIGURATION = 10;+ public static final int MESSAGE_FAILURE_REASON_INTERNAL_DELEGATE_STATE_TRANSITION = 11;++ public static final int DENIED_REASON_UNKNOWN = 0;+ public static final int DENIED_REASON_IN_USE_BY_ANOTHER_DELEGATE = 1;+ public static final int DENIED_REASON_NOT_ALLOWED = 2;+ public static final int DENIED_REASON_SINGLE_REGISTRATION_NOT_ALLOWED = 3;+ public static final int DENIED_REASON_INVALID = 4;++ public static final int SIP_DELEGATE_DESTROY_REASON_UNKNOWN = 0;+ public static final int SIP_DELEGATE_DESTROY_REASON_SERVICE_DEAD = 1;+ public static final int SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP = 2;+ public static final int SIP_DELEGATE_DESTROY_REASON_USER_DISABLED_RCS = 3;+ public static final int SIP_DELEGATE_DESTROY_REASON_SUBSCRIPTION_TORN_DOWN = 4;++ public @interface MessageFailureReason {}+ public @interface DeniedReason {}+ public @interface SipDelegateDestroyReason {}++ public boolean isSupported() throws ImsException {+ throw new RuntimeException("Stub");+ }++ public void createSipDelegate(+ DelegateRequest request,+ Executor executor,+ DelegateConnectionStateCallback dc,+ DelegateConnectionMessageCallback mc)+ throws ImsException {+ throw new RuntimeException("Stub");+ }++ public void destroySipDelegate(+ SipDelegateConnection delegateConnection,+ int reason)+ throws ImsException {+ throw new RuntimeException("Stub");+ }++ public void triggerFullNetworkRegistration(+ SipDelegateConnection connection,+ int sipCode,+ String sipReason)+ throws ImsException {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/SipMessage.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/SipMessage.java b/library/rcs-stubs/src/main/java/android/telephony/ims/SipMessage.javanew file mode 100644index 0000000000..fe36813103--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/SipMessage.java@@ -0,0 +1,40 @@+package android.telephony.ims;+++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.SipMessage}. Not packaged; the real class is+ * provided by the framework at runtime.+ */+public final class SipMessage {+ public SipMessage(+ String startLine,+ String headerSection,+ byte[] content) {+ throw new RuntimeException("Stub");+ }++ public String getStartLine() {+ throw new RuntimeException("Stub");+ }++ public String getHeaderSection() {+ throw new RuntimeException("Stub");+ }++ public byte[] getContent() {+ throw new RuntimeException("Stub");+ }++ public String getViaBranchParameter() {+ throw new RuntimeException("Stub");+ }++ public String getCallIdParameter() {+ throw new RuntimeException("Stub");+ }++ public byte[] toEncodedMessage() {+ throw new RuntimeException("Stub");+ }+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionMessageCallback.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionMessageCallback.java b/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionMessageCallback.javanew file mode 100644index 0000000000..7f4376806e--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionMessageCallback.java@@ -0,0 +1,20 @@+package android.telephony.ims.stub;++import android.telephony.ims.SipDelegateConnection;+import android.telephony.ims.SipDelegateManager;+import android.telephony.ims.SipMessage;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.stub.DelegateConnectionMessageCallback}. Not+ * packaged; the real class is provided by the framework at runtime.+ */+public interface DelegateConnectionMessageCallback {+ void onMessageReceived(SipMessage message);++ void onMessageSent(String viaTransactionId);++ void onMessageSendFailure(+ String viaTransactionId,+ @SipDelegateManager.MessageFailureReason int reason);+}\ No newline at end of file
library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionStateCallback.java
diff --git a/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionStateCallback.java b/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionStateCallback.javanew file mode 100644index 0000000000..6921cc634e--- /dev/null+++ b/library/rcs-stubs/src/main/java/android/telephony/ims/stub/DelegateConnectionStateCallback.java@@ -0,0 +1,25 @@+package android.telephony.ims.stub;++import android.telephony.ims.DelegateRegistrationState;+import android.telephony.ims.FeatureTagState;+import android.telephony.ims.SipDelegateConfiguration;+import android.telephony.ims.SipDelegateConnection;+import android.telephony.ims.SipDelegateManager;+import java.util.Set;++/**+ * Compile-only stub of the framework's {@code @SystemApi}+ * {@code android.telephony.ims.stub.DelegateConnectionStateCallback}. Not+ * packaged; the real class is provided by the framework at runtime.+ */+public interface DelegateConnectionStateCallback {+ void onCreated(SipDelegateConnection c);++ void onFeatureTagStatusChanged(+ DelegateRegistrationState registrationState,+ Set<FeatureTagState> deniedFeatureTags);++ void onConfigurationChanged(SipDelegateConfiguration registeredSipConfig);++ void onDestroyed(@SipDelegateManager.SipDelegateDestroyReason int reason);+}\ No newline at end of file
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 743c4cbc71..db120ff5c4 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -97,6 +97,7 @@ include(":web") include(":appstore") include(":library:locationprovider") include(":library:euicc-stubs")+include(":library:rcs-stubs") include(":library:backup-stubs") include(":library:remotedisplay-stubs") include(":library:nearby-stubs")