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

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

RcsHiddenApi.kt292 lines · 12.4 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import android.annotation.SuppressLint
4import android.content.Context
5import android.telephony.ims.ImsManager
6import android.telephony.ims.ImsException
7import android.telephony.ims.SipDelegateManager
8import com.vayunmathur.library.log.Log
9
10/**
11 * Reflection bridge over the `@SystemApi`/`@hide` members of otherwise-public
12 * framework classes.
13 *
14 * The SDK bootclasspath wins over `compileOnly` stubs for classes that exist
15 * in the public SDK (`ImsManager`, `RcsUceAdapter`), so same-FQN stubs cannot
16 * add hidden members. These helpers cross that boundary with reflection; all
17 * failures return null / rethrow as documented. Parameter and return *types*
18 * come from the `library:aosp-stubs` top-level hidden classes (absent from the
19 * SDK, so the stubs resolve normally).
20 */
21object RcsHiddenApi {
22 private const val TAG = "RcsHiddenApi"
23
24 /**
25 * `ImsManager#getSipDelegateManager(int)` (`@SystemApi`, hidden). Null on
26 * any failure. The returned instance is the framework's
27 * `SipDelegateManager`, typed as the stub for subsequent calls.
28 */
29 fun sipDelegateManager(context: Context, subId: Int): SipDelegateManager? {
30 if (!RcsFeature.enabled) return null
31 return runCatching {
32 val ims = context.applicationContext.getSystemService(ImsManager::class.java)
33 ?: return null
34 val method = ims.javaClass.getMethod("getSipDelegateManager", Int::class.javaPrimitiveType)
35 method.invoke(ims, subId) as? SipDelegateManager
36 }.getOrElse {
37 Log.status(TAG, "getSipDelegateManager failed", it)
38 null
39 }
40 }
41
42 /**
43 * `RcsUceAdapter#requestCapabilities(Collection, Executor,
44 * CapabilitiesCallback)` (`@SystemApi`, hidden).
45 *
46 * The callback interface is hidden too, so [callback] is delivered through
47 * a [java.lang.reflect.Proxy] implementing the framework interface; method
48 * dispatch is by name (`onCapabilitiesReceived` / `onComplete` / `onError`).
49 * Returns false when the bridge itself fails (caller treats as no caps).
50 */
51 // Hidden @SystemApi surface (see file header): no public SDK accessor
52 // exists for this callback registration, so reflection is the only path;
53 // every call is feature-gated and failure-degrading.
54 @SuppressLint("PrivateApi")
55 fun requestUceCapabilities(
56 adapter: Any,
57 contactUris: Collection<android.net.Uri>,
58 executor: java.util.concurrent.Executor,
59 callback: UceCallback,
60 ): Boolean {
61 if (!RcsFeature.enabled) return false
62 return runCatching {
63 val callbackClass = Class.forName("android.telephony.ims.RcsUceAdapter\$CapabilitiesCallback")
64 val proxy = buildUceProxy(adapter, callbackClass, callback)
65 val method = adapter.javaClass.getMethod(
66 "requestCapabilities",
67 Collection::class.java,
68 java.util.concurrent.Executor::class.java,
69 callbackClass,
70 )
71 method.invoke(adapter, contactUris, executor, proxy)
72 true
73 }.getOrElse {
74 // InvocationTargetException wraps the framework's ImsException /
75 // SecurityException — unwrap one level for the caller's catch.
76 val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it
77 Log.status(TAG, "requestCapabilities failed", cause)
78 if (cause is SecurityException) throw cause
79 if (cause is ImsException) throw cause
80 false
81 }
82 }
83
84 /** Dynamic proxy bridging the hidden callback to [UceCallback]. */
85 private fun buildUceProxy(adapter: Any, callbackClass: Class<*>, callback: UceCallback): Any =
86 java.lang.reflect.Proxy.newProxyInstance(
87 adapter.javaClass.classLoader,
88 arrayOf(callbackClass),
89 ) { _, method, args ->
90 when (method.name) {
91 "onCapabilitiesReceived" -> {
92 @Suppress("UNCHECKED_CAST")
93 val caps = (args?.getOrNull(0) as? List<*>) ?: emptyList<Any>()
94 callback.onCapabilitiesReceived(caps)
95 }
96 "onComplete" -> callback.onComplete()
97 "onError" -> callback.onError(
98 (args?.getOrNull(0) as? Int) ?: -1,
99 (args?.getOrNull(1) as? Long) ?: 0L,
100 )
101 // equals/hashCode/toString on the proxy itself.
102 "toString" -> "RcsUceCallbackProxy"
103 "hashCode" -> System.identityHashCode(callback)
104 "equals" -> args?.getOrNull(0) === callback
105 else -> null
106 }
107 }
108
109 /** Dynamic-dispatch target for the UCE proxy (caps are framework objects). */
110 interface UceCallback {
111 fun onCapabilitiesReceived(caps: List<*>)
112 fun onComplete()
113 fun onError(errorCode: Int, retryAfterMillis: Long)
114 }
115
116 /**
117 * `RcsUceAdapter#requestAvailability(Uri, Executor, CapabilitiesCallback)`
118 * (`@SystemApi`, hidden; verified against frameworks/base on main).
119 * Same callback interface as `requestCapabilities`, single contact.
120 * Cheaper than a full capability fetch — use for the send-path
121 * pre-check; full capabilities stay for group setup. Returns false when
122 * the bridge itself fails.
123 */
124 // Hidden @SystemApi surface (see file header): no public SDK accessor
125 // exists for this callback registration, so reflection is the only path;
126 // every call is feature-gated and failure-degrading.
127 @SuppressLint("PrivateApi")
128 fun requestUceAvailability(
129 adapter: Any,
130 contactUri: android.net.Uri,
131 executor: java.util.concurrent.Executor,
132 callback: UceCallback,
133 ): Boolean {
134 if (!RcsFeature.enabled) return false
135 return runCatching {
136 val callbackClass = Class.forName("android.telephony.ims.RcsUceAdapter\$CapabilitiesCallback")
137 val proxy = java.lang.reflect.Proxy.newProxyInstance(
138 adapter.javaClass.classLoader,
139 arrayOf(callbackClass),
140 ) { _, method, args ->
141 dispatchUceCall(method.name, args, callback, "RcsUceAvailabilityProxy")
142 }
143 val method = adapter.javaClass.getMethod(
144 "requestAvailability",
145 android.net.Uri::class.java,
146 java.util.concurrent.Executor::class.java,
147 callbackClass,
148 )
149 method.invoke(adapter, contactUri, executor, proxy)
150 true
151 }.getOrElse {
152 val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it
153 Log.status(TAG, "requestAvailability failed", cause)
154 if (cause is SecurityException) throw cause
155 if (cause is ImsException) throw cause
156 false
157 }
158 }
159
160 /** Dispatch one proxied UCE callback method. */
161 private fun dispatchUceCall(
162 name: String,
163 args: Array<out Any?>?,
164 callback: UceCallback,
165 proxyName: String,
166 ): Any? = when (name) {
167 "onCapabilitiesReceived" -> {
168 @Suppress("UNCHECKED_CAST")
169 val caps = (args?.getOrNull(0) as? List<*>) ?: emptyList<Any>()
170 callback.onCapabilitiesReceived(caps)
171 }
172 "onComplete" -> callback.onComplete()
173 "onError" -> callback.onError(
174 (args?.getOrNull(0) as? Int) ?: -1,
175 (args?.getOrNull(1) as? Long) ?: 0L,
176 )
177 "toString" -> proxyName
178 "hashCode" -> System.identityHashCode(callback)
179 "equals" -> args?.getOrNull(0) === callback
180 else -> null
181 }
182
183 /** Dynamic-dispatch target for the provisioning proxy (config is raw XML bytes). */
184 interface ProvisioningCallback {
185 fun onConfigurationChanged(configXml: ByteArray)
186 fun onConfigurationReset()
187 fun onRemoved()
188 }
189
190 /**
191 * `ProvisioningManager.createForSubscriptionId(int)` (hidden static).
192 * Returns the framework manager as `Any` — all further calls go through
193 * the helpers below. Null on any failure.
194 */
195 fun provisioningManager(subId: Int): Any? {
196 if (!RcsFeature.enabled) return null
197 return runCatching {
198 val pmClass = Class.forName("android.telephony.ims.ProvisioningManager")
199 val factory = pmClass.getMethod("createForSubscriptionId", Int::class.javaPrimitiveType)
200 factory.invoke(null, subId)
201 }.getOrElse {
202 Log.status(TAG, "createForSubscriptionId failed", it)
203 null
204 }
205 }
206
207 /**
208 * `ProvisioningManager#isRcsVolteSingleRegistrationCapable()` (hidden).
209 * Tri-state: true/false from the service, null when the bridge itself
210 * failed (e.g. missing permission) so callers can treat it as "unknown"
211 * rather than "not capable".
212 */
213 fun isSingleRegCapable(provisioningManager: Any): Boolean? {
214 return runCatching {
215 val method = provisioningManager.javaClass.getMethod("isRcsVolteSingleRegistrationCapable")
216 method.invoke(provisioningManager) as? Boolean
217 }.getOrElse {
218 Log.status(TAG, "isRcsVolteSingleRegistrationCapable failed", it)
219 null
220 }
221 }
222
223 /**
224 * `setRcsClientConfiguration` + `registerRcsProvisioningCallback` (hidden).
225 * The callback is a concrete hidden *class*, not an interface — Proxy
226 * cannot implement it (verified on-device), so [callback] is delivered
227 * through a concrete subclass resolved against the same-FQN stub (same
228 * mechanism as the GBA bootstrap path). Returns false when the bridge
229 * itself fails.
230 */
231 fun registerProvisioningCallback(
232 provisioningManager: Any,
233 executor: java.util.concurrent.Executor,
234 rcsVersion: String,
235 rcsProfile: String,
236 callback: ProvisioningCallback,
237 ): Boolean {
238 if (!RcsFeature.enabled) return false
239 return runCatching {
240 val pmClass = provisioningManager.javaClass
241 val configClass = Class.forName("android.telephony.ims.RcsClientConfiguration")
242 val callbackClass = Class.forName(
243 "android.telephony.ims.ProvisioningManager\$RcsProvisioningCallback",
244 )
245 val config = configClass
246 .getConstructor(String::class.java, String::class.java, String::class.java, String::class.java)
247 .newInstance(rcsVersion, rcsProfile, "Vayun", "Communicate-1.0")
248 pmClass.getMethod("setRcsClientConfiguration", configClass).invoke(provisioningManager, config)
249 // Concrete subclass (dynamic proxy cannot implement a class).
250 // The anonymous object extends the stub, which binary-links to the
251 // framework nested class at runtime.
252 val subclass = object : android.telephony.ims.`ProvisioningManager$RcsProvisioningCallback`() {
253 override fun onConfigurationChanged(configXml: ByteArray) {
254 callback.onConfigurationChanged(configXml)
255 }
256
257 override fun onAutoConfigurationErrorReceived(errorCode: Int, errorString: String) {
258 Log.status(TAG, "RCS auto-config error $errorCode: $errorString")
259 }
260
261 override fun onConfigurationReset() {
262 callback.onConfigurationReset()
263 }
264
265 override fun onRemoved() {
266 callback.onRemoved()
267 }
268 }
269 pmClass.getMethod(
270 "registerRcsProvisioningCallback",
271 java.util.concurrent.Executor::class.java,
272 callbackClass,
273 ).invoke(provisioningManager, executor, subclass)
274 true
275 }.getOrElse {
276 val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it
277 Log.status(TAG, "registerRcsProvisioningCallback failed", cause)
278 false
279 }
280 }
281
282 fun unregisterProvisioningCallback(provisioningManager: Any, callbackProxy: Any? = null) {
283 runCatching {
284 // Unregister by callback instance when we hold the proxy; otherwise best-effort no-op.
285 if (callbackProxy != null) {
286 provisioningManager.javaClass
287 .getMethod("unregisterRcsProvisioningCallback", callbackProxy.javaClass.interfaces.first())
288 .invoke(provisioningManager, callbackProxy)
289 }
290 }
291 }
292}