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

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsCapabilityExchange.kt

RcsCapabilityExchange.kt228 lines · 9.7 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import android.content.Context
4import android.net.Uri
5import android.telephony.SubscriptionManager
6import android.telephony.ims.ImsException
7import android.telephony.ims.ImsManager
8import com.vayunmathur.library.log.Log
9import java.util.concurrent.Executor
10import java.util.concurrent.Executors
11import kotlin.coroutines.resume
12import kotlinx.coroutines.flow.MutableStateFlow
13import kotlinx.coroutines.flow.StateFlow
14import kotlinx.coroutines.flow.asStateFlow
15import kotlinx.coroutines.suspendCancellableCoroutine
16
17/**
18 * Capability exchange over the hidden `RcsUceAdapter#requestCapabilities`
19 * (see [RcsHiddenApi]).
20 *
21 * Unknown contacts count as not capable → the send path falls back to SMS.
22 * All failures are fail-closed (`false`); never throws.
23 */
24object RcsCapabilityExchange {
25 private const val TAG = "RcsCapability"
26
27 // AOSP RcsContactUceCapability values (hidden from the public SDK).
28 private const val REQUEST_RESULT_FOUND = 3
29 private const val CAPABILITY_MECHANISM_OPTIONS = 2
30
31 private val executor: Executor = Executors.newSingleThreadExecutor()
32
33 private val _updates = MutableStateFlow<Map<String, Boolean>>(emptyMap())
34 val updates: StateFlow<Map<String, Boolean>> = _updates.asStateFlow()
35
36 /** Whether the UCE path is usable at all (setting on + no privilege error). */
37 @Volatile
38 var uceAvailable: Boolean = true
39 private set
40
41 /**
42 * True when [e164] is RCS-capable (capability FOUND and the CPM session
43 * tag is covered). False for unknown contacts, errors, or when the gate
44 * is off.
45 */
46 suspend fun isContactRcsCapable(context: Context, e164: String): Boolean {
47 if (!RcsFeature.enabled || e164.isBlank()) return false
48 // Fast path: single-contact availability (cheaper than capabilities,
49 // §7.3). Falls back to the full query when the bridge is missing.
50 if (runCatching { isContactAvailable(context, e164) }.getOrDefault(false)) return true
51 val results = queryCapabilities(context, listOf(e164))
52 return results[e164] == true
53 }
54
55 /**
56 * Single-contact availability via `requestAvailability` (§7.3): cheaper
57 * than `requestCapabilities` (presence-style, no feature-tag fetch).
58 * Fail-closed false on any error. Throws SecurityException/ImsException
59 * for the caller to map (mirrors the capabilities path).
60 */
61 private suspend fun isContactAvailable(context: Context, e164: String): Boolean {
62 val app = context.applicationContext
63 val subId = SubscriptionManager.getDefaultSmsSubscriptionId()
64 if (!SubscriptionManager.isValidSubscriptionId(subId)) return false
65 val ims = app.getSystemService(ImsManager::class.java) ?: return false
66 val adapter = runCatching { ims.getImsRcsManager(subId).getUceAdapter() }.getOrNull()
67 ?: return false
68 val uri = Uri.fromParts("tel", e164, null)
69 val caps: List<Map<String, Any?>> = suspendCancellableCoroutine { cont ->
70 val collected = mutableListOf<Map<String, Any?>>()
71 val bridged: Boolean = try {
72 RcsHiddenApi.requestUceAvailability(
73 adapter = adapter,
74 contactUri = uri,
75 executor = executor,
76 callback = object : RcsHiddenApi.UceCallback {
77 override fun onCapabilitiesReceived(caps: List<*>) {
78 for (cap in caps) {
79 readCapability(cap)?.let { collected += it }
80 }
81 }
82
83 override fun onComplete() {
84 if (cont.isActive) cont.resume(collected.toList())
85 }
86
87 override fun onError(errorCode: Int, retryAfterMillis: Long) {
88 Log.status(TAG, "UCE availability error code=$errorCode")
89 if (cont.isActive) cont.resume(collected.toList())
90 }
91 },
92 )
93 } catch (expected: SecurityException) {
94 uceAvailable = false
95 if (cont.isActive) cont.resume(emptyList())
96 false
97 } catch (expected: ImsException) {
98 if (cont.isActive) cont.resume(emptyList())
99 false
100 }
101 if (!bridged && cont.isActive) cont.resume(collected.toList())
102 }
103 return caps.any { isStrictlyCapable(it) }
104 }
105
106 /**
107 * Batch capability check for group members. Returns the subset that is
108 * RCS-capable. Empty on any failure.
109 */
110 suspend fun filterCapable(context: Context, members: List<String>): List<String> {
111 if (!RcsFeature.enabled || members.isEmpty()) return emptyList()
112 val results = queryCapabilities(context, members.distinct())
113 return members.filter { results[it] == true }
114 }
115
116 private suspend fun queryCapabilities(
117 context: Context,
118 numbers: List<String>,
119 ): Map<String, Boolean> {
120 if (numbers.isEmpty()) return emptyMap()
121 val app = context.applicationContext
122 // TestRcsApp keys everything off the default SMS subscription.
123 val subId = SubscriptionManager.getDefaultSmsSubscriptionId()
124 if (!SubscriptionManager.isValidSubscriptionId(subId)) return emptyMap()
125 val ims = app.getSystemService(ImsManager::class.java) ?: return emptyMap()
126 val adapter = runCatching { ims.getImsRcsManager(subId).getUceAdapter() }.getOrNull()
127 ?: return emptyMap()
128 val uris = numbers.map { Uri.fromParts("tel", it, null) }
129 val caps: List<Map<String, Any?>> = requestCapabilities(adapter, uris)
130 val result = mutableMapOf<String, Boolean>()
131 for (cap in caps) {
132 val contact = cap["contact"] as? String ?: continue
133 val number = contact.substringAfter("tel:")
134 result[number] = isCapable(cap)
135 }
136 if (result.isNotEmpty()) {
137 _updates.value = _updates.value + result
138 }
139 return result
140 }
141
142 /** Request capabilities via the hidden UCE API, collecting results. */
143 private suspend fun requestCapabilities(
144 adapter: Any,
145 uris: List<Uri>,
146 ): List<Map<String, Any?>> = suspendCancellableCoroutine { cont ->
147 val collected = mutableListOf<Map<String, Any?>>()
148 val bridged: Boolean = try {
149 RcsHiddenApi.requestUceCapabilities(
150 adapter = adapter,
151 contactUris = uris,
152 executor = executor,
153 callback = object : RcsHiddenApi.UceCallback {
154 override fun onCapabilitiesReceived(caps: List<*>) {
155 for (cap in caps) {
156 readCapability(cap)?.let { collected += it }
157 }
158 }
159
160 override fun onComplete() {
161 if (cont.isActive) cont.resume(collected.toList())
162 }
163
164 override fun onError(errorCode: Int, retryAfterMillis: Long) {
165 Log.status(TAG, "UCE error code=$errorCode")
166 if (cont.isActive) cont.resume(collected.toList())
167 }
168 },
169 )
170 } catch (e: SecurityException) {
171 Log.status(TAG, "No UCE permission", e)
172 uceAvailable = false
173 if (cont.isActive) cont.resume(emptyList())
174 false
175 } catch (e: ImsException) {
176 Log.status(TAG, "UCE service unavailable", e)
177 if (cont.isActive) cont.resume(emptyList())
178 false
179 }
180 if (!bridged && cont.isActive) cont.resume(collected.toList())
181 }
182
183 /**
184 * Read the framework `RcsContactUceCapability` reflectively into a plain
185 * map. All getters are hidden; any failure yields null (not capable).
186 */
187 private fun readCapability(cap: Any?): Map<String, Any?>? {
188 if (cap == null) return null
189 return runCatching {
190 val cls = cap.javaClass
191 val contact = cls.getMethod("getContactUri").invoke(cap) as? Uri
192 val result = cls.getMethod("getRequestResult").invoke(cap) as? Int
193 val mechanism = cls.getMethod("getCapabilityMechanism").invoke(cap) as? Int
194 @Suppress("UNCHECKED_CAST")
195 val tags = cls.getMethod("getFeatureTags").invoke(cap) as? Set<String>
196 mapOf(
197 "contact" to contact?.toString(),
198 "result" to result,
199 "mechanism" to mechanism,
200 "tags" to (tags ?: emptySet<String>()),
201 )
202 }.getOrNull()
203 }
204
205 private fun isCapable(cap: Map<String, Any?>): Boolean {
206 if (cap["result"] as? Int != REQUEST_RESULT_FOUND) return false
207 // OPTIONS mechanism carries feature tags; PRESENCE tuples don't encode CPM tags.
208 if (cap["mechanism"] as? Int == CAPABILITY_MECHANISM_OPTIONS) {
209 @Suppress("UNCHECKED_CAST")
210 val tags = cap["tags"] as? Set<String> ?: emptySet()
211 return tags.any { it.contains("cpm.session", ignoreCase = true) }
212 }
213 return true
214 }
215
216 /**
217 * Strict variant for the availability fast path (§7.3): presence-style
218 * FOUND without CPM tags does NOT short-circuit true (an RCS-presence
219 * contact may still lack the CPM session tag — the full query decides).
220 */
221 private fun isStrictlyCapable(cap: Map<String, Any?>): Boolean {
222 if (cap["result"] as? Int != REQUEST_RESULT_FOUND) return false
223 if (cap["mechanism"] as? Int != CAPABILITY_MECHANISM_OPTIONS) return false
224 @Suppress("UNCHECKED_CAST")
225 val tags = cap["tags"] as? Set<String> ?: emptySet()
226 return tags.any { it.contains("cpm.session", ignoreCase = true) }
227 }
228}