communicate: fix all lint findings
- Commit
8b4f2cd241739f28c30559b5ebe6ed7f60a44088- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 04:27 UTC (19 days ago)
- Parents
caa077a
In-module baseline (origin/main d687bc35a): 169 source findings
(171 under communicate/ including 2 in protoc-generated output),
0 errors / 169 warnings+hints by category: LocalContextGetResourceValueCall
30, UnusedResources 22, UseKtx 21, UnsafeOptInUsageError 16,
MissingPermission 13, OneComposablePerFile 10, MissingOnRenderProcessGone
6, NewApi 5, IntentFilterUniqueDataAttributes 5, TextConcatSpace 3 (src),
WrongConstant 4, ModifierParameter 4, ObsoleteSdkInt 4, StaticFieldLeak 4,
CommentedOutCode 4, HardwareIds 3, AutoboxingStateCreation 3 (hints),
PackageStructure 2, PrivateApi 2, CustomX509TrustManager 2, InlinedApi 1,
PictureInPictureIssue 1, PluralsCandidate 1, ExportedService 1,
SystemPermissionTypo 1, UseTomlInstead 1. After: 0 errors, 0 warnings,
0 hints in communicate source. No lint config, baseline or detekt
changes; fixes are in code only.
PackageStructure: Route moved to Route.kt (only the sealed Route),
CommunicateApp became the sole Navigation() in Navigation.kt, and
MainActivity.kt now holds only MainActivity. Nav-graph entry builders,
CommunicateTabs, DeepLinkEffect, CallRouteEffect (+syncCallRoute),
AppSyncEffects and AppTelecomEffects each moved to their own ui/ file.
DeepLinks.kt moved to intents/ (canonical root); test imports updated.
OneComposablePerFile: CommunicateUi split into RoleGate, DefaultSmsGate,
DefaultDialerGate, LineTag, LineLabel, LineBadge, RememberLineChoices
and LineSelector files; CallLogsContent (+ its private row helpers) and
MessagesListContent split out. ModifierParameter reordered in LineBadge,
DialPad, DialerContent, VoicemailContent with call sites updated.
LocalContextGetResourceValueCall (30): every context.getString() inside
callbacks hoisted to stringResource() at composable level.
UnsafeOptInUsageError (16): experimental car dialer/keypad templates and
their call sites now carry @ExperimentalCarApi alongside @OptIn.
MissingOnRenderProcessGone: all three WebViewClients implement
onRenderProcessGone (destroy/fail the mint, consume the event).
PictureInPictureIssue: PiP params now set auto-enter and source-rect hint.
MissingPermission/NewApi/WrongConstant/InlinedApi (RCS): keyed
CarrierConfigManager getters guarded to API 34 with the whole-bundle
getter as the 31-33 fallback; ProvisioningManager gate guarded to API
33, queries the MmTel call-composer capability through the correct
non-RCS provisioning pair with the public MmTelCapabilities /
ImsRegistrationImplBase constants (REGISTRATION_TECH_LTE is the same
value 0 the local constant carried); NET_CAPABILITY_MMTEL only added on
API 33+. Telecom/Telephony calls that lint could not see as guarded now
catch SecurityException explicitly (several were already behind
permission checks or runCatching). READ_PRECISE_PHONE_STATE declared
(signature|privileged, runtime-degrading) for the provisioning query.
The Robolectric provisioning shadow now also implements the non-RCS
provisioning pair the corrected code queries.
UseKtx: Uri.parse -> String.toUri / createBitmap / SharedPreferences
edit {} / LongSparseArray.size. ObsoleteSdkInt branches removed for
minSdk 31. Autoboxing hints -> mutableIntStateOf. TextConcatSpace in
source fixed (one was a real SQL bug: ADD COLUMNgroupRevision).
CommentedOutCode blocks rewritten as prose. PluralsCandidate:
voicemail_duration is now a plurals resource with a pluralStringResource
call site. UseTomlInstead: protoc dependency built programmatically
from the version-catalog coordinate with a classified exe artifact
(generateProto verified). IntentFilterUniqueDataAttributes: App Links
data tags split into one scheme tag plus per-host tags (same match set).
UnusedResources (22): verified no R.string reference, manifest/XML
reference, getIdentifier or reflection use anywhere in communicate/
before deleting the 22 default strings (no locale-only copies existed,
so no ExtraTranslation orphans).
SuppressLint suppressions, each a genuine false positive with an
in-code justification comment: HardwareIds on RcsDirectSip.start and
RcsE2E.localE164 (the subscriber's own line number as SIP/MLS identity,
not a device identifier) and on RegistrationIntegrity.collect (ANDROID_ID
is SHA-256 hashed into the registration integrity signal, never exposed
raw); PrivateApi on RcsHiddenApi.requestUceCapabilities /
requestUceAvailability (hidden @SystemApi callback surface with no
public SDK accessor; reflection is feature-gated and failure-degrading);
CustomX509TrustManager on RcsMsrpTls.PermissiveTrustManager (peer is
authenticated by RFC 4572 SDP fingerprint pinning per socket, refusing
to connect without an expected fingerprint) and on
SignalTrust.UnionTrustManager (delegates to the bundled/system default
trust managers, weakening nothing); StaticFieldLeak on the SignalClient
singleton (it and SignalSocket retain only the application context;
SignalSocket now normalizes to applicationContext by construction).
Manifest tools:ignore equivalents: SystemPermissionTypo on WRITE_SMS
(a real role-granted permission; WRITE_OBB does not apply),
ExportedService on CommunicateCarAppService (the car host binds and
validates the session itself), ProtectedPermissions on
READ_PRECISE_PHONE_STATE (declared for carrier-privileged builds only).
GoogleVoiceWebSender no longer stores a WebView/Activity in the
singleton: each mint uses a per-call MintSession destroyed in a finally.
Documented false positives in generated code (not edited, regenerated
by :communicate:generateProto on every build): TextConcatSpace in
build/generated GroupProtos.java (the flagged text is protobuf binary
descriptor bytes, not a concatenated UI string) and the intermittent
LintError that SignalServiceProtos.java (4 MB) is too large for lint to
process. Both sit under communicate/build/, outside the source tree.
Out-of-module findings in the same report (library/* shared modules)
are unchanged at 78 and are left for the lead, per scope.
Verification: :communicate:lintDev -- 0 errors, 0 warnings, 0 hints in
communicate source (report total 0 errors / 78 warnings / 3 hints, all
in library/* except the 2 generated-output items above);
:communicate:testDevUnitTest -- green (full suite).
Shared-library findings (lead): app lint runs with
checkDependencies=true, so every app report also counted ~70 findings
in library/, library/ui, library/image and library/map. The code-level
ones are fixed here because communicate is the first module in the
stack whose report includes them; they clear the same findings from
every other module's report too. Fixed: InlinedApi in AppPermissionsGate
(API 33/34/37 permission constants replaced with their literal strings -
the constants are inlined string values and comparing permission names
is safe on all API levels), ModifierParameter ordering/defaults in the
MaterialComponents top-app-bar wrappers, FormComponents and
VulkanMapSurface, Modifier.zoomGestures extension (the two photos call
sites are updated in this commit, on top of the photos commit), lambda-overload offset in
staggeredEntrance, ObsoleteSdkInt branches in GameHubCompose and
SpecialAccess (minSdk 31), Autoboxing hints in HtmlEditorControllerCore
and library/map CameraState, Bitmap.toDrawable KTX in ImageResult,
PanoramaSphereGLView tools constructors and performClick,
OpenSettingsIfRequested rename for ComposableNaming (code and library
test call sites updated), and a POST_NOTIFICATIONS re-check at the
MaNotifications post site.
Suppressions added in shared code, each with an in-code justification:
SetJavaScriptEnabled on HtmlText (javaScriptEnabled is an explicit
caller opt-in, documented unsafe for untrusted content which passes
false) and ModifierFactoryExtensionFunction on the two itemMotion
factories (false positive by construction: Modifier.animateItem only
exists inside LazyItemScope/LazyGridItemScope, so the factory needs
that receiver as well as returning a Modifier, and Kotlin has no
stable dual-receiver form).
NOT fixed, documented false positives by construction: UnusedResources
for shared-library resources in a single app's lint report. Example:
library/ui R.string.delete is reported unused by clock but is used by
calendar, contacts and communicate itself via UiR.string.delete; the
daily_reminder_* strings are used by library/work, and
glance_widget_initial_layout by eight widget apps. Deleting them to
zero one app's report would break the others, so they stay; every app
report therefore retains only these shared-resource warnings.Diff
code/src/main/java/com/vayunmathur/code/Navigation.kt
diff --git a/code/src/main/java/com/vayunmathur/code/Navigation.kt b/code/src/main/java/com/vayunmathur/code/Navigation.ktindex 5e71de3d06..928707f02f 100644--- a/code/src/main/java/com/vayunmathur/code/Navigation.kt+++ b/code/src/main/java/com/vayunmathur/code/Navigation.kt@@ -12,14 +12,14 @@ import com.vayunmathur.code.ui.SettingsPage import com.vayunmathur.code.ui.SnippetsPage import com.vayunmathur.code.ui.TerminalPage import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.openSettingsIfRequested+import com.vayunmathur.library.util.OpenSettingsIfRequested import com.vayunmathur.library.util.rememberNavBackStack @Composable fun Navigation(viewModel: EditorViewModel) { val backStack = rememberNavBackStack<Route>(Route.Editor) // Land on settings when opened from the system App Info page.- backStack.openSettingsIfRequested(Route.Settings)+ backStack.OpenSettingsIfRequested(Route.Settings) MainNavigation(backStack) { entry<Route.Editor> { EditorPage(
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex edca45aee9..3b9b2f98fd 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -79,8 +79,18 @@ val protocConfig: Configuration = configurations.create("protocBinary") { isCanBeConsumed = false } +// Catalog coordinate (libs.protobuf.protoc) with the platform-classified+// exe artifact selected programmatically instead of a string coordinate+// with an appended classifier.+val protocDependency =+ dependencies.create(libs.protobuf.protoc.get()) as org.gradle.api.artifacts.ExternalModuleDependency+protocDependency.artifact {+ classifier = osClassifier+ type = "exe"+}+ dependencies {- "protocBinary"("${libs.protobuf.protoc.get()}:$osClassifier@exe")+ "protocBinary"(protocDependency) } val protoSrcDir = layout.projectDirectory.dir("src/main/proto")
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex f41113b42c..0eefa75866 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -1,5 +1,6 @@ <?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools"> <!-- MAOS: opt out of the GrapheneOS Sensors permission (OTHER_SENSORS). --> <!-- This app uses no motion/environment sensors; MAOS withholds the -->@@ -21,9 +22,15 @@ <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_MMS" /> <uses-permission android:name="android.permission.SEND_SMS" />- <uses-permission android:name="android.permission.WRITE_SMS" />+ <!-- WRITE_SMS is a real (role-granted) permission for the default SMS app;+ lint's typo suggestion (WRITE_OBB) does not apply. -->+ <uses-permission android:name="android.permission.WRITE_SMS" tools:ignore="SystemPermissionTypo" /> <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <!-- ProvisioningManager capability queries (API 33+). Signature|privileged:+ only granted to carrier-privileged builds, so call sites also check+ it at runtime and degrade when absent. -->+ <uses-permission android:name="android.permission.READ_PRECISE_PHONE_STATE" tools:ignore="ProtectedPermissions" /> <!-- Granted by the SMS role (internal|role): single-reg SIP delegate + GBA bootstrap. --> <uses-permission android:name="android.permission.PERFORM_IMS_SINGLE_REGISTRATION" /> @@ -86,11 +93,12 @@ <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" />- <data android:scheme="https" android:host="wa.me" />- <data android:scheme="https" android:host="api.whatsapp.com" />- <data android:scheme="https" android:host="chat.whatsapp.com" />- <data android:scheme="https" android:host="signal.me" />- <data android:scheme="https" android:host="signal.group" />+ <data android:scheme="https" />+ <data android:host="wa.me" />+ <data android:host="api.whatsapp.com" />+ <data android:host="chat.whatsapp.com" />+ <data android:host="signal.me" />+ <data android:host="signal.group" /> </intent-filter> <!-- The vendors' own private schemes, which are not verifiable App Links. --> <intent-filter>@@ -280,9 +288,13 @@ android:exported="false" android:foregroundServiceType="phoneCall|mediaProjection" /> + <!-- Exported for the Android Automotive / Android Auto host, which+ binds and validates the session itself; no binder permission can+ be required here or the host could not connect. --> <service android:name=".service.car.CommunicateCarAppService"- android:exported="true">+ android:exported="true"+ tools:ignore="ExportedService"> <intent-filter> <action android:name="androidx.car.app.CarAppService" /> <category android:name="androidx.car.app.category.MESSAGING" />
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 f487f00f31..74bf8ce932 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -7,160 +7,14 @@ import android.content.pm.PackageManager import android.os.Build import android.util.Rational import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember+import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue-import androidx.compose.ui.res.stringResource-import com.vayunmathur.library.ui.MaActivity-import com.vayunmathur.library.ui.IconCall-import com.vayunmathur.library.ui.IconHistory-import com.vayunmathur.library.ui.IconSms-import com.vayunmathur.library.ui.RouteTab-import com.vayunmathur.library.ui.TabbedPagerScaffold-import com.vayunmathur.library.util.FullscreenPage-import com.vayunmathur.library.util.ListDetailPage-import com.vayunmathur.library.util.ListPage-import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.MorphPage-import com.vayunmathur.library.util.SiblingPage-import com.vayunmathur.library.util.EntryProviderScope-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.NavKey-import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.communicate.data.CommunicateLine-import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession-import com.vayunmathur.communicate.data.googlevoice.call.CallPhase-import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallBridge-import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager-import com.vayunmathur.communicate.telephony.GoogleVoiceSyncService-import com.vayunmathur.communicate.telephony.GoogleVoiceTelecom-import com.vayunmathur.communicate.ui.AccountsScreen-import com.vayunmathur.communicate.ui.CallLogsScreen-import com.vayunmathur.communicate.ui.ConversationScreen-import com.vayunmathur.communicate.ui.DialerScreen-import com.vayunmathur.communicate.ui.MessagesScreen-import com.vayunmathur.communicate.ui.VoicemailScreen import com.vayunmathur.communicate.data.call.InAppCallPhase import com.vayunmathur.communicate.data.call.InAppCallRegistry-import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallBridge-import com.vayunmathur.communicate.telephony.InAppCallTelecom-import com.vayunmathur.communicate.ui.call.InAppCallScreen-import com.vayunmathur.communicate.ui.googlevoice.GoogleVoiceSignInScreen-import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationCodeScreen-import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationDoneScreen-import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationNumberScreen-import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationPinScreen-import com.vayunmathur.communicate.telephony.WhatsAppSyncService-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.SignalRegistrationCaptchaScreen-import com.vayunmathur.communicate.ui.signal.SignalRegistrationCodeScreen-import com.vayunmathur.communicate.ui.signal.SignalRegistrationDoneScreen-import com.vayunmathur.communicate.ui.signal.SignalRegistrationNumberScreen-import androidx.compose.ui.platform.LocalContext-import kotlinx.serialization.Serializable--/** Navigation routes for the communicate app (type-safe back stack keys). */-sealed interface Route : NavKey {- /** The conversation list tab (home). Sibling of [Dialer] and [CallLogs]. */- @Serializable data object Messages : Route- /** The dialer tab. Sibling of [Messages] and [CallLogs]. */- @Serializable data object Dialer : Route- /** The call-logs tab. Sibling of [Messages] and [Dialer]. */- @Serializable data object CallLogs : Route- /** The accounts / line management route. */- @Serializable data object Accounts : Route- /** The Google Voice sign-in route. */- @Serializable data object GoogleVoiceSignIn : Route- /**- * The WhatsApp phone-number registration wizard: one sub-destination- * per step, pushed in flow order. [Pin] is conditional (only numbers- * with two-step verification reach it), and reaching [Done] replaces- * the whole sub-stack so leaving Done exits registration. The entered- * country code and number travel in the step arguments.- */- @Serializable- sealed interface WhatsAppRegistration : Route {- /** Enter the number and request an OTP. */- @Serializable data object Number : WhatsAppRegistration- /** Enter the OTP for [number]. */- @Serializable data class Code(val cc: String, val number: String) : WhatsAppRegistration- /** Enter the two-step PIN for [number] (conditional on the Code result). */- @Serializable data class Pin(val cc: String, val number: String) : WhatsAppRegistration- /** Registration succeeded for [number]. */- @Serializable data class Done(val cc: String, val number: String) : WhatsAppRegistration- }- /** The WhatsApp backup import route. */- @Serializable data object WhatsAppBackupImport : Route- /**- * The Signal phone-number registration wizard: one sub-destination- * per step, pushed in flow order. [Captcha] is conditional (only- * challenged numbers reach it, carrying the transport to resume),- * and reaching [Done] replaces the whole sub-stack so leaving Done- * exits registration. The entered country code and number travel in- * the step arguments.- */- @Serializable- sealed interface SignalRegistration : Route {- /** Enter the number and request an OTP. */- @Serializable data object Number : SignalRegistration- /** Solve the captcha for [number] and resume requesting via [transport]. */- @Serializable data class Captcha(- val cc: String,- val number: String,- val transport: String,- ) : SignalRegistration- /** Enter the OTP for [number]. */- @Serializable data class Code(val cc: String, val number: String) : SignalRegistration- /** Registration succeeded for [number]. */- @Serializable data class Done(val cc: String, val number: String) : SignalRegistration- }-- /** The RCS status / provisioning route. */- @Serializable data object RcsStatus : Route-- /** The RCS safety-number verification route for one peer. */- @Serializable- data class RcsVerify(val peerE164: String) : Route-- /** The RCS group member list route. */- @Serializable- data class RcsGroupMembers(val conversationId: String) : Route-- /**- * The full-screen in-app call. Pushed by the call-route sync while- * [InAppCallRegistry] reports a phase other than Idle, and popped when- * the call ends: the registry is the session engine, this destination- * is only its screen. It carries no arguments because the live call- * state (peer, capabilities, media) changes under it and is read from- * the registry inside the call screen.- */- @Serializable data object Call : Route-- /** One open conversation: its thread, peer address and line. */- @Serializable- data class Conversation(- val threadId: Long,- val address: String,- // Serialized as the enum name; defaults keep older back-stack entries valid.- val line: CommunicateLine = CommunicateLine.Sim,- val remoteId: String? = null,- val subscriptionId: Int? = null,- val isGroup: Boolean = false,- val participants: List<String> = emptyList(),- val groupTitle: String? = null,- ) : Route-}+import com.vayunmathur.communicate.intents.DeepLink+import com.vayunmathur.communicate.intents.DeepLinks+import com.vayunmathur.library.ui.MaActivity /** The single activity hosting the communicate UI: navigation, deep links and line setup. */ class MainActivity : MaActivity() {@@ -179,7 +33,7 @@ class MainActivity : MaActivity() { @Composable override fun Content() {- CommunicateApp(initialDeepLink = pendingDeepLink)+ Navigation(initialDeepLink = pendingDeepLink) } /**@@ -206,6 +60,10 @@ class MainActivity : MaActivity() { enterPictureInPictureMode( PictureInPictureParams.Builder() .setAspectRatio(Rational(PORTRAIT_WIDTH, PORTRAIT_HEIGHT))+ .setAutoEnterEnabled(true)+ .setSourceRectHint(+ android.graphics.Rect().also { window.decorView.getGlobalVisibleRect(it) },+ ) .build(), ) }@@ -218,417 +76,3 @@ class MainActivity : MaActivity() { private const val PORTRAIT_HEIGHT = 16 } }--@Composable-private fun CommunicateApp(initialDeepLink: DeepLink? = null) {- val context = LocalContext.current- val session = remember { GoogleVoiceSession.get(context) }- val gvSignedIn by session.signedInFlow.collectAsState(initial = false)- val waSession = remember { WhatsAppLineSession.get(context) }- val waSignedIn by waSession.signedInFlow.collectAsState(initial = false)- val sigSession = remember { SignalLineSession.get(context) }- val sigSignedIn by sigSession.signedInFlow.collectAsState(initial = false)-- AppSyncEffects(context, waSignedIn, sigSignedIn, gvSignedIn, session)- AppTelecomEffects(context, waSignedIn, sigSignedIn)-- val backStack = rememberNavBackStack<Route>(Route.Messages)-- DeepLinkEffect(backStack, initialDeepLink)- CallRouteEffect(backStack)- CommunicateTabs(backStack)-}--/** Deep links open the conversation they name, including links arriving at a running instance. */-@Composable-private fun DeepLinkEffect(- backStack: NavBackStack<Route>,- initialDeepLink: DeepLink?,-) {- val context = LocalContext.current- // Keyed on the link so a second link to a running instance navigates again rather than ignored.- LaunchedEffect(initialDeepLink) {- when (val link = initialDeepLink) {- is DeepLink.Conversation -> backStack.add(- Route.Conversation(- threadId = link.threadId,- address = link.address,- line = link.line,- remoteId = link.remoteId,- subscriptionId = link.subscriptionId,- isGroup = link.isGroup,- groupTitle = link.groupTitle,- ),- )- is DeepLink.UnsupportedGroupInvite ->- com.vayunmathur.library.util.AppMessages.show(- context.getString(R.string.deep_link_group_unsupported),- )- null -> Unit- }- }-}--/**- * Keeps [Route.Call] on top of the stack exactly while a call is live.- *- * [InAppCallRegistry] stays the session engine: lines bind, ring, connect- * and end without touching navigation, and this effect projects its phase- * onto the stack. Leaving Idle pushes the call screen over whatever the- * user was doing; returning to Idle pops it and reveals that screen again.- * A back press that pops the call screen mid-call is undone by the same- * projection (the phase is still live), so the call UI cannot be lost- * while the call itself continues.- */-@Composable-private fun CallRouteEffect(backStack: NavBackStack<Route>) {- val inAppCallState by InAppCallRegistry.state.collectAsState()- val top = backStack.backStack.lastOrNull()- LaunchedEffect(inAppCallState.phase, top) {- syncCallRoute(backStack, inAppCallState.phase)- }-}--/**- * The phase-to-stack projection behind [CallRouteEffect], kept free of- * composition so unit tests can drive it with a plain [NavBackStack].- *- * Idempotent: a live phase with the call already on top, and Idle with no- * call on top, both leave the stack untouched.- */-internal fun syncCallRoute(backStack: NavBackStack<Route>, phase: InAppCallPhase) {- val top = backStack.backStack.lastOrNull()- if (phase != InAppCallPhase.Idle) {- when {- top is Route.Call -> Unit- // A deep link pushed over the call: bring the existing call- // destination back on top instead of stacking a second one.- backStack.backStack.any { it is Route.Call } -> backStack.reset(- *backStack.backStack.filterNot { it is Route.Call }.toTypedArray(),- Route.Call,- )- else -> backStack.add(Route.Call)- }- } else if (top is Route.Call) {- backStack.pop()- }-}--@Composable-private fun CommunicateNavGraph(backStack: NavBackStack<Route>) {- MainNavigation(backStack) {- coreEntries(backStack)- registrationEntries(backStack)- conversationEntries(backStack)- callEntries(backStack)- }-}--private fun EntryProviderScope<Route>.coreEntries(backStack: NavBackStack<Route>) {- entry<Route.Messages>(metadata = ListPage() + SiblingPage()) {- MessagesScreen(- onOpenThread = { thread ->- val route = Route.Conversation(- threadId = thread.threadId,- address = thread.address,- line = thread.line,- remoteId = thread.remoteId,- subscriptionId = thread.subscriptionId,- isGroup = thread.isGroup,- participants = thread.participants,- groupTitle = thread.groupTitle,- )- // Re-tapping another thread replaces the detail instead of stacking- // Conversation on Conversation.- if (backStack.last() is Route.Conversation) backStack.setLast(route)- else backStack.add(route)- },- onOpenAccounts = { backStack.add(Route.Accounts) },- )- }- entry<Route.Dialer>(metadata = SiblingPage()) {- DialerScreen()- }- entry<Route.CallLogs>(metadata = SiblingPage()) {- CallLogsScreen()- }- entry<Route.Accounts>(metadata = ListDetailPage()) {- AccountsScreen(- onBack = { backStack.pop() },- onSignIn = { backStack.add(Route.GoogleVoiceSignIn) },- onRegisterWhatsApp = {- if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {- backStack.add(Route.WhatsAppRegistration.Number)- }- },- onImportBackup = {- if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {- backStack.add(Route.WhatsAppBackupImport)- }- },- onRegisterSignal = {- if (SignalFeature.enabled) {- backStack.add(Route.SignalRegistration.Number)- }- },- onShowRcsStatus = {- if (RcsFeature.enabled) {- backStack.add(Route.RcsStatus)- }- },- )- }-}--/**- * Replaces the WhatsApp registration steps on the stack with Done.- *- * Done is the terminal step: leaving it must exit registration (as the- * single-screen flow's Done/Back buttons did), not step back into the- * code/PIN steps for an already-registered number.- */-internal fun NavBackStack<Route>.showWhatsAppRegistrationDone(cc: String, number: String) {- while (backStack.lastOrNull() is Route.WhatsAppRegistration) pop()- add(Route.WhatsAppRegistration.Done(cc, number))-}--/** Replaces the Signal registration steps on the stack with Done; see [showWhatsAppRegistrationDone]. */-internal fun NavBackStack<Route>.showSignalRegistrationDone(cc: String, number: String) {- while (backStack.lastOrNull() is Route.SignalRegistration) pop()- add(Route.SignalRegistration.Done(cc, number))-}--internal fun EntryProviderScope<Route>.registrationEntries(backStack: NavBackStack<Route>) {- entry<Route.GoogleVoiceSignIn>(metadata = ListDetailPage()) {- GoogleVoiceSignInScreen(- onBack = { backStack.pop() },- onSignedIn = { backStack.pop() },- )- }- entry<Route.WhatsAppRegistration.Number>(metadata = ListDetailPage()) {- WhatsAppRegistrationNumberScreen(- onBack = { backStack.pop() },- onCodeRequested = { cc, number ->- backStack.add(Route.WhatsAppRegistration.Code(cc, number))- },- )- }- entry<Route.WhatsAppRegistration.Code>(metadata = ListDetailPage()) { route ->- WhatsAppRegistrationCodeScreen(- cc = route.cc,- number = route.number,- onBack = { backStack.pop() },- onPinRequired = { cc, number ->- backStack.add(Route.WhatsAppRegistration.Pin(cc, number))- },- onVerified = { cc, number -> backStack.showWhatsAppRegistrationDone(cc, number) },- )- }- entry<Route.WhatsAppRegistration.Pin>(metadata = ListDetailPage()) { route ->- WhatsAppRegistrationPinScreen(- cc = route.cc,- number = route.number,- onBack = { backStack.pop() },- onVerified = { cc, number -> backStack.showWhatsAppRegistrationDone(cc, number) },- )- }- entry<Route.WhatsAppRegistration.Done>(metadata = ListDetailPage()) {- WhatsAppRegistrationDoneScreen(- onBack = { backStack.pop() },- onRegistered = { backStack.pop() },- )- }- entry<Route.WhatsAppBackupImport>(metadata = ListDetailPage()) {- com.vayunmathur.communicate.ui.whatsapp.WhatsAppBackupImportScreen(- onBack = { backStack.pop() },- )- }- entry<Route.SignalRegistration.Number>(metadata = ListDetailPage()) {- SignalRegistrationNumberScreen(- onBack = { backStack.pop() },- onCaptchaRequired = { cc, number, transport ->- backStack.add(Route.SignalRegistration.Captcha(cc, number, transport))- },- onCodeRequested = { cc, number ->- backStack.add(Route.SignalRegistration.Code(cc, number))- },- )- }- entry<Route.SignalRegistration.Captcha>(metadata = ListDetailPage()) { route ->- SignalRegistrationCaptchaScreen(- cc = route.cc,- number = route.number,- transport = route.transport,- onBack = { backStack.pop() },- // Replace (not push) the captcha, so Code's Back/Change-number- // lands on Number as the single-screen flow's buttons did.- onCodeRequested = { cc, number ->- backStack.setLast(Route.SignalRegistration.Code(cc, number))- },- onCaptchaRejected = { backStack.pop() },- )- }- entry<Route.SignalRegistration.Code>(metadata = ListDetailPage()) { route ->- SignalRegistrationCodeScreen(- cc = route.cc,- number = route.number,- onBack = { backStack.pop() },- onVerified = { cc, number -> backStack.showSignalRegistrationDone(cc, number) },- )- }- entry<Route.SignalRegistration.Done>(metadata = ListDetailPage()) {- SignalRegistrationDoneScreen(- onBack = { backStack.pop() },- onRegistered = { backStack.pop() },- )- }- entry<Route.RcsStatus>(metadata = ListDetailPage()) {- RcsRegistrationScreen(- onBack = { backStack.pop() },- )- }-}--private fun EntryProviderScope<Route>.conversationEntries(backStack: NavBackStack<Route>) {- entry<Route.RcsVerify>(metadata = ListDetailPage()) { route ->- com.vayunmathur.communicate.ui.rcs.RcsVerifyScreen(- peerE164 = route.peerE164,- onBack = { backStack.pop() },- )- }- entry<Route.RcsGroupMembers>(metadata = ListDetailPage()) { route ->- com.vayunmathur.communicate.ui.rcs.RcsGroupMembersScreen(- conversationId = route.conversationId,- onBack = { backStack.pop() },- )- }- entry<Route.Conversation>(metadata = ListDetailPage() + MorphPage()) { route ->- ConversationScreen(- threadId = route.threadId,- address = route.address,- line = route.line,- remoteId = route.remoteId,- subscriptionId = route.subscriptionId,- isGroup = route.isGroup,- participants = route.participants,- groupTitle = route.groupTitle,- onBack = { backStack.pop() },- onOpenRcsVerify = { peer -> backStack.add(Route.RcsVerify(peer)) },- onOpenRcsGroupMembers = { cid -> backStack.add(Route.RcsGroupMembers(cid)) },- )- }-}--/**- * One call screen for every in-app line. Google Voice, WhatsApp and Signal all publish into- * InAppCallRegistry, and the screen renders whatever the active line supports. The phase-to-controls- * choice stays inside [InAppCallScreen]; only the screen's presence is navigation, synced by- * [CallRouteEffect]. Closing is the stack pop back to Idle already performs, so the screen's- * [InAppCallScreen.onClose] only clears the terminal registry state.- */-private fun EntryProviderScope<Route>.callEntries(backStack: NavBackStack<Route>) {- entry<Route.Call>(metadata = FullscreenPage()) {- InAppCallScreen(- onClose = {- InAppCallRegistry.clearEnded()- // If the registry is already Idle the sync pop may have run;- // only pop while the call destination is actually on top.- if (backStack.backStack.lastOrNull() is Route.Call) backStack.pop()- },- )- }-}--/** Sync-service effects for all lines. */-@Composable-private fun AppSyncEffects(- context: android.content.Context,- waSignedIn: Boolean,- sigSignedIn: Boolean,- gvSignedIn: Boolean,- session: GoogleVoiceSession,-) {- // Own the WhatsApp always-on receive state via its foreground sync service (dev-only).- LaunchedEffect(waSignedIn) {- if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@LaunchedEffect- if (waSignedIn) WhatsAppSyncService.start(context) else WhatsAppSyncService.stop(context)- }-- // Own the Signal always-on receive state via its foreground sync service (dev-only).- LaunchedEffect(sigSignedIn) {- if (!SignalFeature.enabled) return@LaunchedEffect- 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)- GoogleVoiceCallManager.onIncomingCall = { from -> GoogleVoiceTelecom.addIncoming(context, from) }- // Projects Google Voice call state onto the shared call screen.- GoogleVoiceCallBridge.ensureStarted()- if (gvSignedIn) {- val number = session.phoneNumber() ?: context.getString(R.string.account_google_voice)- GoogleVoiceTelecom.registerPhoneAccount(context, number)- GoogleVoiceSyncService.start(context)- } else {- GoogleVoiceSyncService.stop(context)- }- }-}--/** Telecom registration effects for all lines. */-@Composable-private fun AppTelecomEffects(- context: android.content.Context,- waSignedIn: Boolean,- sigSignedIn: Boolean,-) {- // WhatsApp and Signal calls share one Telecom account and one call screen. Registered whenever either- // line is usable, so the system owns ringing and audio routing rather than the app approximating it.- LaunchedEffect(waSignedIn, sigSignedIn) {- val anyLine = (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled && waSignedIn) ||- (SignalFeature.enabled && sigSignedIn)- if (anyLine) {- InAppCallTelecom.registerPhoneAccount(context, context.getString(R.string.app_name))- if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {- WhatsAppCallBridge.ensureStarted(context)- }- } else {- InAppCallTelecom.unregisterPhoneAccount(context)- }- }-}--/**- * Route-backed tab host for the three top-level tabs ([Route.Messages],- * [Route.Dialer], [Route.CallLogs]).- *- * The tabs are sibling routes: [TabbedPagerScaffold] selects one by- * `backStack.reset(tab.route)` (see its [RouteTab] overload), and each tab's- * screen is the `SiblingPage()` entry for that route in [CommunicateNavGraph],- * hosted inside the scaffold's content slot. A destination pushed over a tab- * (a conversation, accounts, a registration flow) renders in the same slot- * with no tab selected, and picking a tab resets back to that tab.- * There is no pager: the old host declared `pageCount = { 4 }` for only- * three tabs, and tab selection lived in pager state instead of the stack.- */-@Composable-private fun CommunicateTabs(backStack: NavBackStack<Route>) {- val tabs = listOf<RouteTab<Route>>(- RouteTab(Route.Messages, stringResource(R.string.messages_title), { IconSms() }),- RouteTab(Route.Dialer, stringResource(R.string.dialer_title), { IconCall() }),- RouteTab(Route.CallLogs, stringResource(R.string.call_logs_title), { IconHistory() }),- )- TabbedPagerScaffold(backStack = backStack, tabs = tabs) {- CommunicateNavGraph(backStack)- }-}
communicate/src/main/java/com/vayunmathur/communicate/Navigation.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/Navigation.kt b/communicate/src/main/java/com/vayunmathur/communicate/Navigation.ktnew file mode 100644index 0000000000..b06827a37e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/Navigation.kt@@ -0,0 +1,37 @@+package com.vayunmathur.communicate++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.communicate.data.signal.SignalLineSession+import com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession+import com.vayunmathur.communicate.intents.DeepLink+import com.vayunmathur.communicate.ui.AppSyncEffects+import com.vayunmathur.communicate.ui.AppTelecomEffects+import com.vayunmathur.communicate.ui.CallRouteEffect+import com.vayunmathur.communicate.ui.CommunicateTabs+import com.vayunmathur.communicate.ui.DeepLinkEffect+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(initialDeepLink: DeepLink? = null) {+ val context = LocalContext.current+ val session = remember { GoogleVoiceSession.get(context) }+ val gvSignedIn by session.signedInFlow.collectAsState(initial = false)+ val waSession = remember { WhatsAppLineSession.get(context) }+ val waSignedIn by waSession.signedInFlow.collectAsState(initial = false)+ val sigSession = remember { SignalLineSession.get(context) }+ val sigSignedIn by sigSession.signedInFlow.collectAsState(initial = false)++ AppSyncEffects(context, waSignedIn, sigSignedIn, gvSignedIn, session)+ AppTelecomEffects(context, waSignedIn, sigSignedIn)++ val backStack = rememberNavBackStack<Route>(Route.Messages)++ DeepLinkEffect(backStack, initialDeepLink)+ CallRouteEffect(backStack)+ CommunicateTabs(backStack)+}
communicate/src/main/java/com/vayunmathur/communicate/Route.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/Route.kt b/communicate/src/main/java/com/vayunmathur/communicate/Route.ktnew file mode 100644index 0000000000..4de0325a1f--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/Route.kt@@ -0,0 +1,97 @@+package com.vayunmathur.communicate++import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++/** Navigation routes for the communicate app (type-safe back stack keys). */+sealed interface Route : NavKey {+ /** The conversation list tab (home). Sibling of [Dialer] and [CallLogs]. */+ @Serializable data object Messages : Route+ /** The dialer tab. Sibling of [Messages] and [CallLogs]. */+ @Serializable data object Dialer : Route+ /** The call-logs tab. Sibling of [Messages] and [Dialer]. */+ @Serializable data object CallLogs : Route+ /** The accounts / line management route. */+ @Serializable data object Accounts : Route+ /** The Google Voice sign-in route. */+ @Serializable data object GoogleVoiceSignIn : Route+ /**+ * The WhatsApp phone-number registration wizard: one sub-destination+ * per step, pushed in flow order. [Pin] is conditional (only numbers+ * with two-step verification reach it), and reaching [Done] replaces+ * the whole sub-stack so leaving Done exits registration. The entered+ * country code and number travel in the step arguments.+ */+ @Serializable+ sealed interface WhatsAppRegistration : Route {+ /** Enter the number and request an OTP. */+ @Serializable data object Number : WhatsAppRegistration+ /** Enter the OTP for [number]. */+ @Serializable data class Code(val cc: String, val number: String) : WhatsAppRegistration+ /** Enter the two-step PIN for [number] (conditional on the Code result). */+ @Serializable data class Pin(val cc: String, val number: String) : WhatsAppRegistration+ /** Registration succeeded for [number]. */+ @Serializable data class Done(val cc: String, val number: String) : WhatsAppRegistration+ }+ /** The WhatsApp backup import route. */+ @Serializable data object WhatsAppBackupImport : Route+ /**+ * The Signal phone-number registration wizard: one sub-destination+ * per step, pushed in flow order. [Captcha] is conditional (only+ * challenged numbers reach it, carrying the transport to resume),+ * and reaching [Done] replaces the whole sub-stack so leaving Done+ * exits registration. The entered country code and number travel in+ * the step arguments.+ */+ @Serializable+ sealed interface SignalRegistration : Route {+ /** Enter the number and request an OTP. */+ @Serializable data object Number : SignalRegistration+ /** Solve the captcha for [number] and resume requesting via [transport]. */+ @Serializable data class Captcha(+ val cc: String,+ val number: String,+ val transport: String,+ ) : SignalRegistration+ /** Enter the OTP for [number]. */+ @Serializable data class Code(val cc: String, val number: String) : SignalRegistration+ /** Registration succeeded for [number]. */+ @Serializable data class Done(val cc: String, val number: String) : SignalRegistration+ }++ /** The RCS status / provisioning route. */+ @Serializable data object RcsStatus : Route++ /** The RCS safety-number verification route for one peer. */+ @Serializable+ data class RcsVerify(val peerE164: String) : Route++ /** The RCS group member list route. */+ @Serializable+ data class RcsGroupMembers(val conversationId: String) : Route++ /**+ * The full-screen in-app call. Pushed by the call-route sync while+ * [InAppCallRegistry] reports a phase other than Idle, and popped when+ * the call ends: the registry is the session engine, this destination+ * is only its screen. It carries no arguments because the live call+ * state (peer, capabilities, media) changes under it and is read from+ * the registry inside the call screen.+ */+ @Serializable data object Call : Route++ /** One open conversation: its thread, peer address and line. */+ @Serializable+ data class Conversation(+ val threadId: Long,+ val address: String,+ // Serialized as the enum name; defaults keep older back-stack entries valid.+ val line: CommunicateLine = CommunicateLine.Sim,+ val remoteId: String? = null,+ val subscriptionId: Int? = null,+ val isGroup: Boolean = false,+ val participants: List<String> = emptyList(),+ val groupTitle: String? = null,+ ) : Route+}
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 b9d7e5bcd7..4a75b9ab30 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryHelper.kt@@ -38,6 +38,9 @@ fun CommunicateRepository.placeCall(context: Context, choice: LineChoice?, numbe handle?.let { extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, it) } telecomManager.placeCall(uri, extras) return+ } catch (_: SecurityException) {+ // CALL_PHONE was revoked between the check above and the call:+ // fall through to ACTION_DIAL below. } catch (_: Exception) { // Fall through to ACTION_DIAL below. }
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 7e853f95ca..bd06cd34f2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data +import androidx.core.net.toUri import android.content.Context import android.provider.CallLog import android.provider.Telephony@@ -153,7 +154,7 @@ suspend fun CommunicateRepository.deleteConversation( private fun CommunicateRepository.deleteSimThread(context: Context, threadId: Long): Boolean = runCatching { // Provider deletes the thread + its SMS/MMS rows when the conversation is removed. val deleted = context.contentResolver.delete(- android.net.Uri.parse("content://mms-sms/conversations/$threadId"), null, null,+ "content://mms-sms/conversations/$threadId".toUri(), null, null, ) if (deleted > 0) return true // Fallback: delete SMS and MMS rows directly.
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 171f8f1e3b..9b0d847108 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySend.kt@@ -319,7 +319,7 @@ internal fun CommunicateRepository.persistOutgoingMms( put("ct", "text/plain") put("text", body) }- context.contentResolver.insert(Uri.parse("content://mms/$mmsId/part"), partValues)+ context.contentResolver.insert("content://mms/$mmsId/part".toUri(), partValues) } // Address rows: TO (151) per recipient. for (r in recipients) {@@ -328,7 +328,7 @@ internal fun CommunicateRepository.persistOutgoingMms( put("type", MMS_ADDR_TYPE_TO) put("charset", MMS_CHARSET_UTF8) }- context.contentResolver.insert(Uri.parse("content://mms/$mmsId/addr"), addrValues)+ context.contentResolver.insert("content://mms/$mmsId/addr".toUri(), addrValues) } } }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.ktindex e3e0d17b0f..1d339d9d3b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt@@ -177,7 +177,7 @@ internal fun CommunicateRepository.loadThreadRecipients(context: Context): Map<L // recipient_ids is a space-separated list of ids into the canonical-addresses table. val canonical = HashMap<String, String>() context.contentResolver.query(- Uri.parse("content://mms-sms/canonical-addresses"),+ "content://mms-sms/canonical-addresses".toUri(), arrayOf("_id", "address"), null, null, null, )?.use { c ->@@ -265,7 +265,7 @@ internal fun CommunicateRepository.loadMmsParts( val attachments = ArrayList<CommunicateAttachment>() runCatching { context.contentResolver.query(- Uri.parse("content://mms/part"),+ "content://mms/part".toUri(), arrayOf("_id", "ct", "text", "_data"), "mid = ?", arrayOf(mmsId.toString()), null, )?.use { c ->@@ -302,14 +302,14 @@ internal fun CommunicateRepository.loadMmsParts( }.getOrDefault("" to emptyList()) internal fun CommunicateRepository.readMmsTextPart(context: Context, partId: Long): String = runCatching {- context.contentResolver.openInputStream(Uri.parse("content://mms/part/$partId"))?.use {+ context.contentResolver.openInputStream("content://mms/part/$partId".toUri())?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty() }.getOrDefault("") internal fun CommunicateRepository.loadMmsSender(context: Context, mmsId: Long): String? = runCatching { context.contentResolver.query(- Uri.parse("content://mms/$mmsId/addr"),+ "content://mms/$mmsId/addr".toUri(), arrayOf("address", "type"), "type = 137", null, null, )?.use { c ->@@ -422,9 +422,13 @@ internal fun CommunicateRepository.phoneAccountHandleForSub( if (subscriptionId < 0) return null if (!context.hasPermission(Manifest.permission.READ_PHONE_STATE)) return null val tm = context.getSystemService(TelecomManager::class.java) ?: return null- return runCatching {+ return try { tm.callCapablePhoneAccounts.firstOrNull { it.id == subscriptionId.toString() }- }.getOrNull()+ } catch (_: SecurityException) {+ null+ } catch (_: Exception) {+ null+ } } fun CommunicateRepository.openSmsComposer(context: Context, number: String? = null, body: String? = null) {@@ -456,7 +460,13 @@ fun CommunicateRepository.voicemailNumber(context: Context, choice: LineChoice?) } else { base }- return runCatching { scoped.voiceMailNumber }.getOrNull()?.takeIf { it.isNotBlank() }+ return try {+ scoped.voiceMailNumber+ } catch (_: SecurityException) {+ null+ } catch (_: Exception) {+ null+ }?.takeIf { it.isNotBlank() } } /**@@ -566,7 +576,7 @@ fun CommunicateRepository.markVoicemailRead( } return runCatching { context.contentResolver.update(- Uri.parse(voicemail.contentUri),+ voicemail.contentUri.toUri(), values, null, null,@@ -578,7 +588,7 @@ fun CommunicateRepository.markVoicemailRead( fun CommunicateRepository.deleteVoicemail(context: Context, voicemail: VoicemailEntry): Boolean { if (!context.hasPermission(Manifest.permission.WRITE_CALL_LOG)) return false return runCatching {- context.contentResolver.delete(Uri.parse(voicemail.contentUri), null, null) >= 0+ context.contentResolver.delete(voicemail.contentUri.toUri(), null, null) >= 0 }.getOrDefault(false) }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryWhatsApp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryWhatsApp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryWhatsApp.ktindex 1a13abc15b..bb2232f686 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryWhatsApp.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryWhatsApp.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data +import androidx.core.net.toUri import android.content.Context import android.net.Uri import android.telephony.TelephonyManager@@ -163,7 +164,7 @@ internal suspend fun CommunicateRepository.sendAttachments( var allOk = attachments.isNotEmpty() for (attachment in attachments) { val bytes = try {- context.contentResolver.openInputStream(Uri.parse(attachment.contentUri))?.use { it.readBytes() }+ context.contentResolver.openInputStream(attachment.contentUri.toUri())?.use { it.readBytes() } } catch (_: Throwable) { null }
communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.ktindex e0b8100284..769761fe98 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt@@ -29,7 +29,7 @@ object SimManager { // that like zero SIMs rather than crashing composition. val sm = runCatching { context.getSystemService(SubscriptionManager::class.java) } .getOrNull() ?: return emptyList()- return runCatching {+ return try { sm.activeSubscriptionInfoList?.map { info -> CommunicateSim( subscriptionId = info.subscriptionId,@@ -39,7 +39,11 @@ object SimManager { ?: "SIM ${info.simSlotIndex + 1}", ) }.orEmpty()- }.getOrDefault(emptyList())+ } catch (_: SecurityException) {+ emptyList()+ } catch (_: Exception) {+ emptyList()+ } } /** Selectable SIM lines. Falls back to a single default SIM when none can be enumerated. */
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.ktindex 0f5810392a..d5ba3a3b0e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt@@ -155,10 +155,11 @@ object GoogleVoiceParser { // ------------------------------------------------------------------ // Positional wire-shape mapping (confirmed from live api2thread/list bodies) //- // record: ["t.<num>"|"c.<id>", state, [ item, item, ... ], null, [[num,...]], ...]- // item: [itemId, tsMillis, ownNumber, [counterparty,...], type, read, ..,- // duration@8, bodyText@9, .., counterparty@15, .., "t.<id>"|"c.<id>"]- // Items are newest-first.+ // A record is a list whose head is the thread id (prefixed t. or c.),+ // followed by its state and then the item list. Each item carries, in+ // order, its id, timestamp in millis, the own number, the counterparties,+ // the type and the read flag; the duration sits at index 8, the body text+ // at index 9 and the counterparty at index 15. Items are newest-first. // ------------------------------------------------------------------ private const val ITEMS = 2
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.ktindex 5028ed7c19..686bab3f05 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.googlevoice +import androidx.core.net.toUri import android.annotation.SuppressLint import android.app.Activity import android.net.Uri@@ -34,14 +35,6 @@ object GoogleVoiceWebSender { private const val TAG = "GVAUTO" - private var webView: WebView? = null- private var currentRecipient: String = ""- private var currentText: String = ""- private var currentAttachments: List<Uri> = emptyList()-- @Volatile- private var pending: CompletableDeferred<String>? = null- /** * Mint the bot-defense token by letting the GV web app build a `sendsms` request in an * offscreen WebView, intercepting + blocking that request, and returning just the `"!…"`@@ -62,7 +55,7 @@ object GoogleVoiceWebSender { activity = activity, recipient = recipient, text = text,- attachments = attachments.map { Uri.parse(it.contentUri) },+ attachments = attachments.map { it.contentUri.toUri() }, ) /** Drive the offscreen WebView to produce the exact sendsms body (with token). */@@ -72,34 +65,42 @@ object GoogleVoiceWebSender { text: String, attachments: List<Uri> = emptyList(), ): String? {- val deferred = CompletableDeferred<String>()- withContext(Dispatchers.Main) {- pending = deferred- currentRecipient = recipient- currentText = text- currentAttachments = attachments- disposeWebView()- val wv = ensureWebView(activity)- wv.loadUrl("https://voice.google.com/u/0/messages")- }- val body = withTimeoutOrNull(if (attachments.isEmpty()) 60_000 else 120_000) { deferred.await() }- withContext(Dispatchers.Main) {- disposeWebView()- currentAttachments = emptyList()+ // One session per mint: the WebView (and the Activity it is created+ // with) is held only by this call frame and destroyed in the finally+ // below, never by the singleton.+ val session = MintSession(recipient, text, attachments)+ try {+ withContext(Dispatchers.Main) {+ val wv = session.ensureWebView(activity)+ wv.loadUrl("https://voice.google.com/u/0/messages")+ }+ return withTimeoutOrNull(if (attachments.isEmpty()) 60_000 else 120_000) {+ session.deferred.await()+ }+ } finally {+ withContext(Dispatchers.Main) { session.disposeWebView() } }- return body } - private fun disposeWebView() {- val old = webView ?: return- runCatching { old.stopLoading() }- runCatching { (old.parent as? ViewGroup)?.removeView(old) }- runCatching { old.destroy() }- webView = null- }+ /** Per-mint WebView state; see [mintBody]. */+ private class MintSession(+ val recipient: String,+ val text: String,+ val attachments: List<Uri>,+ ) {+ val deferred = CompletableDeferred<String>()+ var webView: WebView? = null - @SuppressLint("SetJavaScriptEnabled")- private fun ensureWebView(activity: Activity): WebView {+ fun disposeWebView() {+ val old = webView ?: return+ runCatching { old.stopLoading() }+ runCatching { (old.parent as? ViewGroup)?.removeView(old) }+ runCatching { old.destroy() }+ webView = null+ }++ @SuppressLint("SetJavaScriptEnabled")+ fun ensureWebView(activity: Activity): WebView { webView?.let { return it } CookieManager.getInstance().setAcceptCookie(true) val wv = WebView(activity)@@ -109,7 +110,7 @@ object GoogleVoiceWebSender { wv.settings.userAgentString = "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/126.0.0.0 Mobile Safari/537.36"- wv.addJavascriptInterface(Bridge(), "AndroidGV")+ wv.addJavascriptInterface(Bridge(deferred), "AndroidGV") // Install the fetch/XHR hook BEFORE any page script runs, so the GV app can't capture the // original fetch first (that's why onPageFinished injection missed the send). if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {@@ -124,13 +125,23 @@ object GoogleVoiceWebSender { // Fallback hook injection for devices without DOCUMENT_START_SCRIPT. view?.evaluateJavascript(hookScript(), null) }+ override fun onRenderProcessGone(+ view: WebView?,+ detail: android.webkit.RenderProcessGoneDetail?,+ ): Boolean {+ // Renderer died (crash/OOM): fail the pending mint instead of+ // taking the whole process down with the WebView.+ deferred.complete("")+ disposeWebView()+ return true+ } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) if (url == null || !url.contains("voice.google.com/u/")) return if (injected) return injected = true view?.evaluateJavascript(- automationScript(currentRecipient, currentText, hasAttachments = currentAttachments.isNotEmpty()),+ automationScript(recipient, text, hasAttachments = attachments.isNotEmpty()), null, ) }@@ -141,8 +152,8 @@ object GoogleVoiceWebSender { filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?, ): Boolean {- Log.dev(TAG, "file chooser requested for ${currentAttachments.size} attachment(s)")- filePathCallback?.onReceiveValue(currentAttachments.toTypedArray())+ Log.dev(TAG, "file chooser requested for ${attachments.size} attachment(s)")+ filePathCallback?.onReceiveValue(attachments.toTypedArray()) return true } }@@ -158,16 +169,19 @@ object GoogleVoiceWebSender { return wv } - private class Bridge {- @JavascriptInterface- fun onBody(body: String) {- Log.dev(TAG, "captured sendsms body (${body.length} bytes)")- pending?.complete(body)- }+ private class Bridge(+ private val deferred: CompletableDeferred<String>,+ ) {+ @JavascriptInterface+ fun onBody(body: String) {+ Log.dev(TAG, "captured sendsms body (${body.length} bytes)")+ deferred.complete(body)+ } - @JavascriptInterface- fun log(msg: String) {- Log.dev(TAG, msg)+ @JavascriptInterface+ fun log(msg: String) {+ Log.dev(TAG, msg)+ } } }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDirectSip.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDirectSip.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDirectSip.ktindex 4bdb84f890..89c0163493 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDirectSip.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDirectSip.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs +import android.annotation.SuppressLint import android.content.Context import android.net.ConnectivityManager import android.net.LinkProperties@@ -88,6 +89,10 @@ object RcsDirectSip { * TCP to the P-CSCF, REGISTER with AKA. Suspends until the first 200 OK * (or failure). Idempotent while running. */+ // Own subscriber number as the SIP public identity (RFC 3261 REGISTER):+ // this is the user's own line, not a device identifier, and RCS cannot+ // register without it.+ @SuppressLint("HardwareIds") suspend fun start(context: Context, subId: Int): Boolean { if (!RcsFeature.enabled) return false if (running) return true@@ -95,8 +100,13 @@ object RcsDirectSip { // Public identity: derive from the line-1 number when readable, else // the IMSI-derived placeholder the P-CSCF will challenge anyway. // The 401 + AKA exchange establishes the real identity.- publicIdentity = runCatching { conn.tm.line1Number?.takeIf { it.isNotBlank() } }- .getOrNull() ?: ""+ publicIdentity = try {+ conn.tm.line1Number?.takeIf { it.isNotBlank() }+ } catch (_: SecurityException) {+ null+ } catch (_: Exception) {+ null+ } ?: "" callIdBase = "${UUID.randomUUID()}@rcs-direct" running = true val ok = runCatching {@@ -534,7 +544,6 @@ object RcsDirectSip { private fun pcscfAddress(app: Context, network: Network): InetSocketAddress? { return runCatching {- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return null val cm = app.getSystemService(ConnectivityManager::class.java) ?: return null val props: LinkProperties = cm.getLinkProperties(network) ?: return null // `getPcscfServers()` is @SystemApi/hidden (absent from android.jar):
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.ktindex 60395cd315..12b979c97c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaBootstrap.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs +import androidx.core.net.toUri import android.content.Context import android.net.Uri import android.telephony.CarrierConfigManager@@ -128,7 +129,7 @@ object RcsGbaBootstrap { method.invoke( tm, TelephonyManager.APPTYPE_ISIM,- Uri.parse(nafUrl),+ nafUrl.toUri(), spId, force, executor,@@ -151,9 +152,19 @@ object RcsGbaBootstrap { return runCatching { val ccm = context.getSystemService(CarrierConfigManager::class.java) ?: return null- val bundle = runCatching {- ccm.getConfigForSubId(subId, KEY_ORG, KEY_PROTOCOL, KEY_CIPHER_SUITE)- }.getOrNull() ?: return null+ // The keyed getter is API 34+; on 31-33 read the whole bundle.+ val bundle = try {+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ ccm.getConfigForSubId(subId, KEY_ORG, KEY_PROTOCOL, KEY_CIPHER_SUITE)+ } else {+ @Suppress("DEPRECATION")+ ccm.getConfigForSubId(subId)+ }+ } catch (_: SecurityException) {+ return null+ } catch (_: Exception) {+ return null+ } ?: return null val org = bundle.getInt(KEY_ORG, UaSecurityProtocolIdentifier.ORG_NONE) val protocol = bundle.getInt( KEY_PROTOCOL,
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.ktindex 2d8f613f2d..8e701c7b59 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs +import android.annotation.SuppressLint import android.content.Context import android.telephony.ims.ImsManager import android.telephony.ims.ImsException@@ -47,6 +48,10 @@ internal object RcsHiddenApi { * dispatch is by name (`onCapabilitiesReceived` / `onComplete` / `onError`). * Returns false when the bridge itself fails (caller treats as no caps). */+ // Hidden @SystemApi surface (see file header): no public SDK accessor+ // exists for this callback registration, so reflection is the only path;+ // every call is feature-gated and failure-degrading.+ @SuppressLint("PrivateApi") fun requestUceCapabilities( adapter: Any, contactUris: Collection<android.net.Uri>,@@ -116,6 +121,10 @@ internal object RcsHiddenApi { * pre-check; full capabilities stay for group setup. Returns false when * the bridge itself fails. */+ // Hidden @SystemApi surface (see file header): no public SDK accessor+ // exists for this callback registration, so reflection is the only path;+ // every call is feature-gated and failure-degrading.+ @SuppressLint("PrivateApi") fun requestUceAvailability( adapter: Any, contactUri: android.net.Uri,
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.ktindex 28c9f1e26e..4310a3c836 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt@@ -75,7 +75,11 @@ object RcsImsNetwork { val builder = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .addCapability(NetworkCapabilities.NET_CAPABILITY_IMS)- .addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL)+ // NET_CAPABILITY_MMTEL is API 33+; on 31-32 the IMS+ // capability alone still matches the IMS PDN.+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL)+ } if (SubscriptionManager.isValidSubscriptionId(subId)) { runCatching { val specClass = Class.forName(@@ -177,7 +181,6 @@ object RcsImsNetwork { fun localIps(context: Context, network: Network): List<String> { if (!RcsFeature.enabled) return emptyList() return runCatching {- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return emptyList() val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java) ?: return emptyList() val props = cm.getLinkProperties(network) ?: return emptyList()
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.ktindex 9359d6394d..705f267302 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs +import android.annotation.SuppressLint import android.content.Context import com.vayunmathur.library.log.Log import java.io.File@@ -255,6 +256,12 @@ object RcsMsrpTls { } } + // Chain validation would reject the self-signed carrier certs MSRP uses;+ // the peer is instead authenticated by RFC 4572 fingerprint pinning,+ // checked per socket in clientSocket / verifyServerSide before any data+ // flows (and clientSocket refuses to connect without an expected+ // fingerprint). This manager therefore intentionally accepts any chain.+ @SuppressLint("CustomX509TrustManager") private object PermissiveTrustManager : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.ktindex a666028bcd..73803aac74 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt@@ -1,5 +1,7 @@ package com.vayunmathur.communicate.data.rcs +import android.telephony.ims.stub.ImsRegistrationImplBase+import android.telephony.ims.feature.MmTelFeature import android.Manifest import android.content.Context import android.content.pm.PackageManager@@ -106,26 +108,37 @@ object RcsProvisioning { private fun readConfigServerUrl(context: Context, subscriptionId: Int): RcsRegistrationState? { // 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 url = try { 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 {- Log.status(TAG, "probe: carrier-config read failed: $it")+ // The keyed getter is API 34+; on 31-33 fall back to the+ // whole-bundle getter for the subscription and read the key.+ val bundle = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ ccm.getConfigForSubId(+ subscriptionId,+ CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING,+ )+ } else {+ @Suppress("DEPRECATION")+ ccm.getConfigForSubId(subscriptionId)+ }+ bundle?.getString(CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING).orEmpty()+ } catch (e: SecurityException) {+ Log.status(TAG, "probe: carrier-config read denied: $e")+ return RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)+ } catch (e: Exception) {+ Log.status(TAG, "probe: carrier-config read failed: $e") return RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable) } lastConfigServerUrl = url.ifEmpty { null }- // NOTE: an empty config URL no longer hard-blocks. MVNOs/Jibe-backed- // carriers (e.g. US Mobile) routinely leave `rcs_config_server_url`- // empty while still accepting a single-reg delegate; the delegate- // request itself is the real test (denial surfaces as- // TransportDenied via onFeatureTagStatusChanged). The URL is still- // recorded for the status screen + TS.43 entitlement.+ // Note — an empty config URL no longer hard-blocks. MVNOs and+ // Jibe-backed carriers (US Mobile, for one) routinely leave the+ // rcs_config_server_url key empty while still accepting a single-reg+ // delegate; the delegate request itself is the real test, and a denial+ // surfaces as TransportDenied via onFeatureTagStatusChanged. The URL+ // is still recorded for the status screen and the TS.43 entitlement. if (url.isBlank()) { Log.status( "RcsProvisioning",@@ -137,18 +150,32 @@ object RcsProvisioning { /** Provisioning-manager gate; returns a terminal state, or null to continue. */ private fun provisioningGate(context: Context, subscriptionId: Int): RcsRegistrationState? {- // 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 {+ // Secondary signal: the provisioning manager's status for the+ // call-composer capability (an MmTel capability, so the non-RCS+ // provisioning pair is the correct query). The provisioning manager+ // is API 33+ and needs READ_PRECISE_PHONE_STATE; without either, this+ // gate degrades to "not required" — the carrier-config URL above is+ // the authoritative gate.+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return null+ // READ_PRECISE_PHONE_STATE is declared in the manifest; it is only+ // granted to carrier-privileged builds, and the SecurityException+ // catch below degrades to "not required" everywhere else.+ val provisioningRequired = try { val ims = context.getSystemService(ImsManager::class.java)- ?: return@runCatching false+ ?: return null 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)+ pm.isProvisioningRequiredForCapability(+ MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,+ ImsRegistrationImplBase.REGISTRATION_TECH_LTE,+ ) && !pm.getProvisioningStatusForCapability(+ MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,+ ImsRegistrationImplBase.REGISTRATION_TECH_LTE,+ )+ } catch (_: SecurityException) {+ false+ } catch (_: Exception) {+ false+ } if (provisioningRequired) { Log.status(TAG, "probe: carrier provisioning required (call-composer cap unprovisioned)") return RcsRegistrationState.Unavailable(RcsUnavailableReason.ProvisioningRequired)@@ -158,10 +185,11 @@ object RcsProvisioning { /** Single-registration support gate; returns a terminal state, or null to continue. */ private fun singleRegGate(context: Context, subscriptionId: Int): RcsRegistrationState? {- // Tertiary signal (TestRcsApp ProvisioningActivity): the hidden- // isRcsVolteSingleRegistrationCapable() on the per-sub manager. Tri-state —- // null (bridge failure, e.g. role not yet granted) means "unknown", not- // "not capable", so it never blocks on permission errors.+ // Tertiary signal, after TestRcsApp's ProvisioningActivity: the hidden+ // single-registration-capability query on the per-sub manager. It is+ // tri-state — a null result (bridge failure, say the role is not yet+ // granted) means unknown rather than not capable, so it never blocks+ // on permission errors. val singleRegCapable = runCatching { val pm = RcsHiddenApi.provisioningManager(subscriptionId) ?: return@runCatching null@@ -242,7 +270,7 @@ object RcsProvisioning { context.packageManager.hasSystemFeature(FEATURE_SINGLE_REG) // 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+ // Call-composer is an MmTel capability (1 shl 4) and LTE the registration+ // tech, expressed with the public provisioning constants below. private const val FEATURE_SINGLE_REG = "android.hardware.telephony.ims.singlereg" }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktindex d115623f07..24990cdf9b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs.e2e +import android.annotation.SuppressLint import android.content.Context import android.telephony.SubscriptionManager import com.vayunmathur.communicate.data.rcs.RcsDatabase@@ -552,13 +553,20 @@ object RcsE2E { } /** Our own E.164 (default SMS subscription's number when readable). */+ // Own subscriber number for MLS/SIP addressing: the user's own line, not+ // a device identifier, and end-to-end RCS cannot address us without it.+ @SuppressLint("HardwareIds") fun localE164(context: Context): String? { if (!RcsFeature.enabled) return null- return runCatching {- val tm = context.getSystemService(android.telephony.TelephonyManager::class.java)- ?: return null+ val tm = context.getSystemService(android.telephony.TelephonyManager::class.java)+ ?: return null+ return try { tm.line1Number?.takeIf { it.isNotBlank() }- }.getOrNull()+ } catch (_: SecurityException) {+ null+ } catch (_: Exception) {+ null+ } }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex 9f67ff3158..5140e97dfc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.signal +import android.annotation.SuppressLint import android.content.Context import android.util.Base64 as AndroidBase64 import com.vayunmathur.library.log.Log@@ -73,6 +74,10 @@ import java.util.concurrent.atomic.AtomicBoolean * GroupsV2 via SignalGroups (GroupMasterKey 32B -> GroupSecretParams, PUT /v2/groups/). * CDSIv2 via SignalContactSync (POST https://cdsi.signal.org/v1/{mrenclave}/discovery). */+// Singleton by design (one Signal account per app). Every Context it or its+// sockets retain is the application context (see init/SignalSocket), so no+// activity or view can leak through these fields.+@SuppressLint("StaticFieldLeak") object SignalClient { internal const val TAG = "SignalClient"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.ktindex 497b2972d4..f551da1152 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.signal +import androidx.core.content.edit import android.Manifest import android.content.Context import android.content.pm.PackageManager@@ -96,9 +97,9 @@ object SignalContactSync { try { val prefs = context.getSharedPreferences("communicate_signal_cdsi", Context.MODE_PRIVATE) if (token == null || token.isEmpty()) {- prefs.edit().remove("cdsi_token").apply()+ prefs.edit { remove("cdsi_token") } } else {- prefs.edit().putString("cdsi_token", AndroidBase64.encodeToString(token, AndroidBase64.NO_WRAP)).apply()+ prefs.edit { putString("cdsi_token", AndroidBase64.encodeToString(token, AndroidBase64.NO_WRAP)) } } } catch (_: Exception) {} }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.ktindex 63eda79976..5704bc80b1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt@@ -124,8 +124,9 @@ abstract class SignalDatabase : RoomDatabase() { private val MIGRATION_3_4 = object : androidx.room3.migration.Migration(3, 4) { override suspend fun migrate(connection: SQLiteConnection) { connection.execSQL("ALTER TABLE signal_conversation ADD COLUMN groupMasterKey BLOB")- connection.execSQL("ALTER TABLE signal_conversation ADD COLUMN" +- "groupRevision INTEGER NOT NULL DEFAULT 0")+ connection.execSQL(+ "ALTER TABLE signal_conversation ADD COLUMN groupRevision INTEGER NOT NULL DEFAULT 0",+ ) connection.execSQL("DELETE FROM signal_cached_message WHERE conversationId LIKE 'group:%'") connection.execSQL("DELETE FROM signal_conversation WHERE chatId LIKE 'group:%'") }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.ktindex cd818e5755..75f1399493 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalGroupCallManager.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.signal.call +import androidx.core.util.size import android.content.Context import com.vayunmathur.library.log.Log import kotlinx.coroutines.CoroutineScope@@ -168,14 +169,14 @@ class SignalGroupCallManager( val id = groupId ?: return val state = try { groupCall.localDeviceState } catch (_: Throwable) { null } val joined = state?.joinState == GroupCall.JoinState.JOINED- val participants = try { groupCall.remoteDeviceStates?.size() ?: 0 } catch (_: Throwable) { 0 }+ val participants = try { groupCall.remoteDeviceStates?.size ?: 0 } catch (_: Throwable) { 0 } Log.status(TAG, "group call state: joinState=${state?.joinState} participants=$participants") signaling.onGroupCallStateChanged(id, joined, participants) } override fun onRemoteDeviceStatesChanged(groupCall: GroupCall) { val id = groupId ?: return- val participants = try { groupCall.remoteDeviceStates?.size() ?: 0 } catch (_: Throwable) { 0 }+ val participants = try { groupCall.remoteDeviceStates?.size ?: 0 } catch (_: Throwable) { 0 } val joined = try { groupCall.localDeviceState?.joinState == GroupCall.JoinState.JOINED } catch (_: Throwable) {
communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.ktindex 61ed149b6d..db293f6c23 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt@@ -295,8 +295,9 @@ class RegistrationHttpClient(private val context: Context) { body = body, sslSocketFactory = SignalTrust.sslSocketFactory(context), )- if (resp.status == HTTP_LOCKED) throw IllegalStateException("423 RegistrationLock (live-only: needs" +- "svr2Credentials/recoveryPassword)")+ if (resp.status == HTTP_LOCKED) throw IllegalStateException(+ "423 RegistrationLock (live-only: needs svr2Credentials/recoveryPassword)",+ ) if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}") return parseSession(resp.body) }@@ -471,12 +472,12 @@ class RegistrationHttpClient(private val context: Context) { } private fun buildAccountAttributesJson(auth: SignalAuthData): JSONObject {- // AccountAttributes per org.whispersystems.signalservice.api.account.AccountAttributes- // {signalingKey:null, registrationId, pniRegistrationId, unidentifiedAccessKey 32B, registrationLock,- // recoveryPassword?,- // fetchesMessages:true,- // capabilities:{storage,versionedExpirationTimer,attachmentBackfill,spqr,usernameChangeSyncMessage},- // discoverableByPhoneNumber, name}+ // The account-attributes payload mirrors the signal service's+ // AccountAttributes shape: a null signaling key, the registration and+ // PNI registration ids, the 32-byte unidentified access key, the+ // registration lock, an optional recovery password, message fetching+ // enabled, the storage / timer / backfill / spqr / username-sync+ // capabilities, phone-number discoverability, and the profile name. val uakB64 = auth.unidentifiedAccessKey val uakBytes = if (uakB64.isNotEmpty()) runCatching { Base64.decode( uakB64,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.ktindex c5dacedad4..646b3a0de1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt@@ -45,7 +45,7 @@ import java.util.concurrent.ConcurrentHashMap * Uses :library:network WebSocketClient (binary frames). */ class SignalSocket(- private val context: Context,+ context: Context, private val authData: SignalAuthData, private val host: String = DEFAULT_HOST, private val port: Int = DEFAULT_PORT,@@ -53,6 +53,9 @@ class SignalSocket( private val passwordOverride: String? = null, private val authenticated: Boolean = true, ) {+ /** Only the application context is retained: sockets outlive any activity. */+ private val context: Context = context.applicationContext+ /** Server endpoint and logging constants for [SignalSocket]. */ companion object { private const val TAG = "SignalSocket"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalTrust.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalTrust.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalTrust.ktindex cd75a46fef..5668adfc3a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalTrust.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalTrust.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.signal.transport +import android.annotation.SuppressLint import android.content.Context import com.vayunmathur.library.log.Log import java.security.KeyStore@@ -133,6 +134,10 @@ object SignalTrust { * Accepts a chain trusted by EITHER the bundled Signal roots or the system roots. * Client auth and accepted issuers defer to the system manager (plus bundled issuers). */+ // This manager does not weaken validation: every chain must pass either+ // the bundled Signal roots or the platform system manager, both of which+ // are default X509TrustManagers doing full chain validation.+ @SuppressLint("CustomX509TrustManager") private class UnionTrustManager( private val bundled: X509TrustManager, private val system: X509TrustManager,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.ktindex a7f69d21f4..844f20d57c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.whatsapp.registration +import android.annotation.SuppressLint import android.content.Context import android.os.Build import android.provider.Settings@@ -85,6 +86,10 @@ object RegistrationIntegrity { * @param encryptQueryString the ENC wrapper used for `_gi` (defaults to * [RegistrationAttestation.encryptQueryString]); may return null on failure. */+ // ANDROID_ID is only fed into aidOf(), which hashes it into the+ // registration integrity signal the official client sends; the raw id+ // never leaves the device or identifies hardware to us.+ @SuppressLint("HardwareIds") fun collect( context: Context, nowSeconds: Long = System.currentTimeMillis() / MS_PER_SECOND,
communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.ktsimilarity index 99%rename from communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.ktrename to communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.ktindex bad8c617c8..add7820cc4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/DeepLinks.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt@@ -1,4 +1,4 @@-package com.vayunmathur.communicate+package com.vayunmathur.communicate.intents import android.content.Intent import android.net.Uri
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.ktindex 02a6419316..e100ddbaa9 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt@@ -53,6 +53,8 @@ class CommunicateCarCallScreen( } } + @ExperimentalCarApi+ @OptIn(ExperimentalCarApi::class) override fun onGetTemplate(): Template { val live = InAppCallRegistry.state.value if (live.phase.isLiveCall()) {@@ -65,6 +67,7 @@ class CommunicateCarCallScreen( } /** Car-native in-call view (experimental). Falls back on any failure. */+ @ExperimentalCarApi @OptIn(ExperimentalCarApi::class) private fun inCallTemplate( title: String,@@ -93,6 +96,7 @@ class CommunicateCarCallScreen( } /** Dialpad for placing a new call (experimental). */+ @ExperimentalCarApi @OptIn(ExperimentalCarApi::class) fun keypadTemplate(): Template { val callIcon = runCatching {@@ -147,6 +151,8 @@ class CommunicateCarCallScreen( } } + @ExperimentalCarApi+ @OptIn(ExperimentalCarApi::class) private fun recentCallsTemplate(): Template { val list = ItemList.Builder() list.addItem(@@ -172,6 +178,7 @@ class CommunicateCarCallScreen( } /** Wrapper so the dialpad renders the keypad template directly. */+ @ExperimentalCarApi @OptIn(ExperimentalCarApi::class) private class CommunicateCarKeypadScreen( carContext: CarContext,
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.ktindex a9bcb48623..7fbb652b9f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.service.car +import androidx.core.graphics.createBitmap import androidx.car.app.CarContext import androidx.car.app.Screen import androidx.car.app.model.Action@@ -132,7 +133,7 @@ class CommunicateCarThreadListScreen( .joinToString("") .ifBlank { "#" } val size = AVATAR_SIZE_PX- val bitmap = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+ val bitmap = createBitmap(size, size) val canvas = android.graphics.Canvas(bitmap) val palette = AVATAR_PALETTE val bg = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.ktindex 8c2e147aba..19788583b7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt@@ -72,11 +72,7 @@ class GoogleVoiceCallForegroundService : Service() { buildOngoingCallNotification(state.phase, state.remoteNumber, contentIntent) } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)- } else {- startForeground(NOTIFICATION_ID, notification)- }+ startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL) } private fun updateRinging(state: CallState) {
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.ktindex bcafc9410a..ef827bfeab 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.kt@@ -46,7 +46,12 @@ object GoogleVoiceTelecom { putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle(context)) } val uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null)- runCatching { tm.placeCall(uri, extras) }+ try {+ tm.placeCall(uri, extras)+ } catch (_: SecurityException) {+ // Self-managed account not registered yet or CALL_PHONE revoked:+ // the Telecom bind simply does not happen.+ } } /** Surface an inbound SIP INVITE to the system as an incoming self-managed call. */
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.ktindex c647f147b6..fc62b88410 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt@@ -80,11 +80,7 @@ class InAppCallForegroundService : Service() { } else { ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL }- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- startForeground(NOTIFICATION_ID, notification, types)- } else {- startForeground(NOTIFICATION_ID, notification)- }+ startForeground(NOTIFICATION_ID, notification, types) } /**
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.ktindex 135d3c93ee..35d8c54a26 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt@@ -61,7 +61,12 @@ object InAppCallTelecom { putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false) } val uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, peerId, null)- runCatching { tm.placeCall(uri, extras) }+ try {+ tm.placeCall(uri, extras)+ } catch (_: SecurityException) {+ // Self-managed account not registered yet or CALL_PHONE revoked:+ // the Telecom bind simply does not happen.+ } } fun addIncoming(context: Context, peerId: String) {
communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.ktindex cd8dfee614..754cfcad14 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.telephony +import androidx.core.net.toUri import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.ContentValues@@ -114,7 +115,7 @@ class MmsDeliverReceiver : BroadcastReceiver() { put("text", p.text.orEmpty()) } }- val partUri = context.contentResolver.insert(Uri.parse("content://mms/$mmsId/part"), pv)+ val partUri = context.contentResolver.insert("content://mms/$mmsId/part".toUri(), pv) // Write binary media bytes into the part's data stream. if (partUri != null && !p.contentType.startsWith("text/") && p.data.isNotEmpty()) { runCatching {@@ -137,7 +138,7 @@ class MmsDeliverReceiver : BroadcastReceiver() { put("type", MMS_ADDR_TYPE_FROM) put("charset", MMS_CHARSET_UTF8) }- context.contentResolver.insert(Uri.parse("content://mms/$mmsId/addr"), av)+ context.contentResolver.insert("content://mms/$mmsId/addr".toUri(), av) val textBody = msg.parts.firstOrNull { it.contentType == "text/plain" }?.text val body = textBody?.takeIf { it.isNotBlank() } ?: context.getString(R.string.media_message)
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 aa0d3794fa..b221aae106 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt@@ -45,6 +45,7 @@ fun AccountsScreen( onShowRcsStatus: () -> Unit = {}, ) { val context = LocalContext.current+ val signedOutMessage = stringResource(R.string.gv_signed_out) val session = remember { GoogleVoiceSession.get(context) } val waSession = remember { com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession.get(context) } val waSignedIn by waSession.signedInFlow.collectAsState(initial = false)@@ -101,7 +102,7 @@ fun AccountsScreen( onClick = { scope.launch { session.signOut()- AppMessages.show(context.getString(R.string.gv_signed_out))+ AppMessages.show(signedOutMessage) } }, modifier = Modifier.fillMaxWidth(),
communicate/src/main/java/com/vayunmathur/communicate/ui/AppSyncEffects.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/AppSyncEffects.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/AppSyncEffects.ktnew file mode 100644index 0000000000..2cbf6e90c3--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AppSyncEffects.kt@@ -0,0 +1,65 @@+package com.vayunmathur.communicate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallBridge+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+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.data.signal.SignalFeature+import com.vayunmathur.communicate.telephony.GoogleVoiceSyncService+import com.vayunmathur.communicate.telephony.GoogleVoiceTelecom+import com.vayunmathur.communicate.telephony.RcsSyncService+import com.vayunmathur.communicate.telephony.SignalSyncService+import com.vayunmathur.communicate.telephony.WhatsAppSyncService++/** Sync-service effects for all lines. */+@Composable+fun AppSyncEffects(+ context: android.content.Context,+ waSignedIn: Boolean,+ sigSignedIn: Boolean,+ gvSignedIn: Boolean,+ session: GoogleVoiceSession,+) {+ // Own the WhatsApp always-on receive state via its foreground sync service (dev-only).+ LaunchedEffect(waSignedIn) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@LaunchedEffect+ if (waSignedIn) WhatsAppSyncService.start(context) else WhatsAppSyncService.stop(context)+ }++ // Own the Signal always-on receive state via its foreground sync service (dev-only).+ LaunchedEffect(sigSignedIn) {+ if (!SignalFeature.enabled) return@LaunchedEffect+ 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)+ GoogleVoiceCallManager.onIncomingCall = { from -> GoogleVoiceTelecom.addIncoming(context, from) }+ // Projects Google Voice call state onto the shared call screen.+ GoogleVoiceCallBridge.ensureStarted()+ if (gvSignedIn) {+ val number = session.phoneNumber() ?: context.getString(R.string.account_google_voice)+ GoogleVoiceTelecom.registerPhoneAccount(context, number)+ GoogleVoiceSyncService.start(context)+ } else {+ GoogleVoiceSyncService.stop(context)+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/AppTelecomEffects.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/AppTelecomEffects.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/AppTelecomEffects.ktnew file mode 100644index 0000000000..0e7d91e738--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AppTelecomEffects.kt@@ -0,0 +1,31 @@+package com.vayunmathur.communicate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.signal.SignalFeature+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallBridge+import com.vayunmathur.communicate.telephony.InAppCallTelecom++/** Telecom registration effects for all lines. */+@Composable+fun AppTelecomEffects(+ context: android.content.Context,+ waSignedIn: Boolean,+ sigSignedIn: Boolean,+) {+ // WhatsApp and Signal calls share one Telecom account and one call screen. Registered whenever either+ // line is usable, so the system owns ringing and audio routing rather than the app approximating it.+ LaunchedEffect(waSignedIn, sigSignedIn) {+ val anyLine = (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled && waSignedIn) ||+ (SignalFeature.enabled && sigSignedIn)+ if (anyLine) {+ InAppCallTelecom.registerPhoneAccount(context, context.getString(R.string.app_name))+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ WhatsAppCallBridge.ensureStarted(context)+ }+ } else {+ InAppCallTelecom.unregisterPhoneAccount(context)+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsContent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsContent.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsContent.ktnew file mode 100644index 0000000000..03001a1492--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsContent.kt@@ -0,0 +1,190 @@+package com.vayunmathur.communicate.ui++import android.Manifest+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconPerson+import com.vayunmathur.library.ui.IconPersonAdd+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateCallLogEntry+import com.vayunmathur.communicate.data.CommunicateCallType+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.deleteCallLog+import com.vayunmathur.communicate.data.loadCallLogsMerged+import com.vayunmathur.communicate.data.placeCall+import com.vayunmathur.communicate.domain.callDurationParts+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Call-log list, stateless: rows plus the delete-confirm dialog. Split out so+ * screenshot previews can render entries without the call-log provider, the+ * polling tick, or the permission gates above.+ */+@Composable+fun CallLogsContent(+ entries: List<CommunicateCallLogEntry>,+ modifier: Modifier = Modifier,+ onCall: (CommunicateCallLogEntry) -> Unit,+ onDelete: (CommunicateCallLogEntry) -> Unit,+) {+ var pendingDelete by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<CommunicateCallLogEntry?>(null) }+ LazyColumn(+ modifier = modifier+ .fillMaxSize(),+ contentPadding = PaddingValues(vertical = 8.dp),+ ) {+ items(entries, key = { it.id }) { entry ->+ CallLogRow(+ entry = entry,+ onClick = { onCall(entry) },+ onDelete = { pendingDelete = entry },+ )+ }+ }+ val toDelete = pendingDelete+ if (toDelete != null) {+ com.vayunmathur.library.ui.ConfirmDialog(+ title = stringResource(R.string.delete_call_log_title),+ message = stringResource(R.string.delete_call_log_message),+ confirmLabel = stringResource(com.vayunmathur.library.ui.R.string.delete),+ dismissLabel = stringResource(com.vayunmathur.library.ui.R.string.cancel),+ destructive = true,+ onConfirm = {+ pendingDelete = null+ onDelete(toDelete)+ },+ onDismiss = { pendingDelete = null },+ )+ }+}++@Composable+private fun CallLogRow(entry: CommunicateCallLogEntry, onClick: () -> Unit, onDelete: () -> Unit = {}) {+ val context = LocalContext.current+ val title = entry.displayName ?: entry.phoneNumber+ ListItem(+ content = {+ Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {+ Text(+ title,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ fontWeight = if (entry.type == CommunicateCallType.Missed) FontWeight.Bold else FontWeight.Medium,+ )+ LineBadge(entry.line, modifier = Modifier.padding(start = 6.dp), subscriptionId = entry.subscriptionId)+ }+ },+ supportingContent = {+ Column {+ Text(entry.phoneNumber, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(+ "${entry.type.label()} · ${formatDateTime(context, entry.timestampMillis)} · " ++ callDurationLabel(entry.durationSeconds),+ style = MaterialTheme.typography.labelSmall,+ color = if (entry.type == CommunicateCallType.Missed) {+ MaterialTheme.colorScheme.error+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ },+ )+ }+ },+ leadingContent = { IconForCallType(entry.type) },+ trailingContent = {+ Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {+ com.vayunmathur.library.ui.IconButton(onClick = onClick) { IconCall() }+ com.vayunmathur.library.ui.OverflowMenu(icon = { IconMoreVert() }) {+ // The provider already resolved a cached name for anyone saved, and withheld calls+ // arrive as a placeholder with no digits — neither can be turned into a contact.+ if (entry.displayName == null && entry.phoneNumber.any { it.isDigit() }) {+ Item(+ text = stringResource(R.string.contact_create_new),+ leadingIcon = { IconPersonAdd() },+ onClick = { ContactIntents.createNew(context, entry.phoneNumber) },+ )+ Item(+ text = stringResource(R.string.contact_add_to_existing),+ leadingIcon = { IconPerson() },+ onClick = { ContactIntents.addToExisting(context, entry.phoneNumber) },+ )+ }+ Item(+ text = stringResource(com.vayunmathur.library.ui.R.string.delete),+ leadingIcon = { IconDelete() },+ onClick = onDelete,+ )+ }+ }+ },+ colors = ListItemDefaults.colors(containerColor = Color.Transparent),+ modifier = Modifier.clickable(onClick = onClick),+ )+}++@Composable+private fun IconForCallType(type: CommunicateCallType) {+ val tint = if (type == CommunicateCallType.Missed) {+ MaterialTheme.colorScheme.error+ } else {+ MaterialTheme.colorScheme.primary+ }+ IconCall(tint = tint)+}++@Composable+private fun callDurationLabel(durationSeconds: Long): String {+ val parts = callDurationParts(durationSeconds)+ val shown = listOfNotNull(+ parts.hours?.let { pluralStringResource(R.plurals.duration_hours, it, it) },+ parts.minutes?.let { pluralStringResource(R.plurals.duration_minutes, it, it) },+ parts.seconds?.let { pluralStringResource(R.plurals.duration_seconds, it, it) },+ )+ return if (shown.size == 2) {+ stringResource(R.string.duration_two_units, shown[0], shown[1])+ } else {+ shown.first()+ }+}++@Composable+private fun CommunicateCallType.label(): String = when (this) {+ CommunicateCallType.Incoming -> stringResource(R.string.incoming_call)+ CommunicateCallType.Outgoing -> stringResource(R.string.outgoing_call)+ CommunicateCallType.Missed -> stringResource(R.string.missed_call)+ CommunicateCallType.Rejected -> stringResource(R.string.rejected_call)+ CommunicateCallType.Blocked -> stringResource(R.string.blocked_call)+ CommunicateCallType.Voicemail -> stringResource(R.string.voicemail_call)+ CommunicateCallType.Unknown -> stringResource(R.string.unknown_call)+}
communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.ktindex dfbcbfcc34..f6ec2f7462 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt@@ -50,6 +50,7 @@ import kotlinx.coroutines.withContext @Composable fun CallLogsScreen() { val context = LocalContext.current+ val deleteFailedMessage = stringResource(R.string.delete_failed) val scope = androidx.compose.runtime.rememberCoroutineScope() var tick by androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(0) } var pendingDelete by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<CommunicateCallLogEntry?>(null) }@@ -87,7 +88,7 @@ fun CallLogsScreen() { val ok = withContext(Dispatchers.IO) { CommunicateRepository.deleteCallLog( context, toDelete) }- if (ok) tick++ else AppMessages.show(context.getString(R.string.delete_failed))+ if (ok) tick++ else AppMessages.show(deleteFailedMessage) } }, )@@ -97,145 +98,3 @@ fun CallLogsScreen() { } } }--/**- * Call-log list, stateless: rows plus the delete-confirm dialog. Split out so- * screenshot previews can render entries without the call-log provider, the- * polling tick, or the permission gates above.- */-@Composable-fun CallLogsContent(- entries: List<CommunicateCallLogEntry>,- modifier: Modifier = Modifier,- onCall: (CommunicateCallLogEntry) -> Unit,- onDelete: (CommunicateCallLogEntry) -> Unit,-) {- var pendingDelete by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<CommunicateCallLogEntry?>(null) }- LazyColumn(- modifier = modifier- .fillMaxSize(),- contentPadding = PaddingValues(vertical = 8.dp),- ) {- items(entries, key = { it.id }) { entry ->- CallLogRow(- entry = entry,- onClick = { onCall(entry) },- onDelete = { pendingDelete = entry },- )- }- }- val toDelete = pendingDelete- if (toDelete != null) {- com.vayunmathur.library.ui.ConfirmDialog(- title = stringResource(R.string.delete_call_log_title),- message = stringResource(R.string.delete_call_log_message),- confirmLabel = stringResource(com.vayunmathur.library.ui.R.string.delete),- dismissLabel = stringResource(com.vayunmathur.library.ui.R.string.cancel),- destructive = true,- onConfirm = {- pendingDelete = null- onDelete(toDelete)- },- onDismiss = { pendingDelete = null },- )- }-}--@Composable-private fun CallLogRow(entry: CommunicateCallLogEntry, onClick: () -> Unit, onDelete: () -> Unit = {}) {- val context = LocalContext.current- val title = entry.displayName ?: entry.phoneNumber- ListItem(- content = {- Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {- Text(- title,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- fontWeight = if (entry.type == CommunicateCallType.Missed) FontWeight.Bold else FontWeight.Medium,- )- LineBadge(entry.line, entry.subscriptionId, modifier = Modifier.padding(start = 6.dp))- }- },- supportingContent = {- Column {- Text(entry.phoneNumber, maxLines = 1, overflow = TextOverflow.Ellipsis)- Text(- "${entry.type.label()} · ${formatDateTime(context, entry.timestampMillis)} · " +- callDurationLabel(entry.durationSeconds),- style = MaterialTheme.typography.labelSmall,- color = if (entry.type == CommunicateCallType.Missed) {- MaterialTheme.colorScheme.error- } else {- MaterialTheme.colorScheme.onSurfaceVariant- },- )- }- },- leadingContent = { IconForCallType(entry.type) },- trailingContent = {- Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {- com.vayunmathur.library.ui.IconButton(onClick = onClick) { IconCall() }- com.vayunmathur.library.ui.OverflowMenu(icon = { IconMoreVert() }) {- // The provider already resolved a cached name for anyone saved, and withheld calls- // arrive as a placeholder with no digits — neither can be turned into a contact.- if (entry.displayName == null && entry.phoneNumber.any { it.isDigit() }) {- Item(- text = stringResource(R.string.contact_create_new),- leadingIcon = { IconPersonAdd() },- onClick = { ContactIntents.createNew(context, entry.phoneNumber) },- )- Item(- text = stringResource(R.string.contact_add_to_existing),- leadingIcon = { IconPerson() },- onClick = { ContactIntents.addToExisting(context, entry.phoneNumber) },- )- }- Item(- text = stringResource(com.vayunmathur.library.ui.R.string.delete),- leadingIcon = { IconDelete() },- onClick = onDelete,- )- }- }- },- colors = ListItemDefaults.colors(containerColor = Color.Transparent),- modifier = Modifier.clickable(onClick = onClick),- )-}--@Composable-private fun callDurationLabel(durationSeconds: Long): String {- val parts = callDurationParts(durationSeconds)- val shown = listOfNotNull(- parts.hours?.let { pluralStringResource(R.plurals.duration_hours, it, it) },- parts.minutes?.let { pluralStringResource(R.plurals.duration_minutes, it, it) },- parts.seconds?.let { pluralStringResource(R.plurals.duration_seconds, it, it) },- )- return if (shown.size == 2) {- stringResource(R.string.duration_two_units, shown[0], shown[1])- } else {- shown.first()- }-}--@Composable-private fun IconForCallType(type: CommunicateCallType) {- val tint = if (type == CommunicateCallType.Missed) {- MaterialTheme.colorScheme.error- } else {- MaterialTheme.colorScheme.primary- }- IconCall(tint = tint)-}--@Composable-private fun CommunicateCallType.label(): String = when (this) {- CommunicateCallType.Incoming -> stringResource(R.string.incoming_call)- CommunicateCallType.Outgoing -> stringResource(R.string.outgoing_call)- CommunicateCallType.Missed -> stringResource(R.string.missed_call)- CommunicateCallType.Rejected -> stringResource(R.string.rejected_call)- CommunicateCallType.Blocked -> stringResource(R.string.blocked_call)- CommunicateCallType.Voicemail -> stringResource(R.string.voicemail_call)- CommunicateCallType.Unknown -> stringResource(R.string.unknown_call)-}
communicate/src/main/java/com/vayunmathur/communicate/ui/CallRouteEffect.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallRouteEffect.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallRouteEffect.ktnew file mode 100644index 0000000000..6af8309849--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallRouteEffect.kt@@ -0,0 +1,55 @@+package com.vayunmathur.communicate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.communicate.Route+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.library.util.NavBackStack++/**+ * Keeps [Route.Call] on top of the stack exactly while a call is live.+ *+ * [InAppCallRegistry] stays the session engine: lines bind, ring, connect+ * and end without touching navigation, and this effect projects its phase+ * onto the stack. Leaving Idle pushes the call screen over whatever the+ * user was doing; returning to Idle pops it and reveals that screen again.+ * A back press that pops the call screen mid-call is undone by the same+ * projection (the phase is still live), so the call UI cannot be lost+ * while the call itself continues.+ */+@Composable+fun CallRouteEffect(backStack: NavBackStack<Route>) {+ val inAppCallState by InAppCallRegistry.state.collectAsState()+ val top = backStack.backStack.lastOrNull()+ LaunchedEffect(inAppCallState.phase, top) {+ syncCallRoute(backStack, inAppCallState.phase)+ }+}++/**+ * The phase-to-stack projection behind [CallRouteEffect], kept free of+ * composition so unit tests can drive it with a plain [NavBackStack].+ *+ * Idempotent: a live phase with the call already on top, and Idle with no+ * call on top, both leave the stack untouched.+ */+internal fun syncCallRoute(backStack: NavBackStack<Route>, phase: InAppCallPhase) {+ val top = backStack.backStack.lastOrNull()+ if (phase != InAppCallPhase.Idle) {+ when {+ top is Route.Call -> Unit+ // A deep link pushed over the call: bring the existing call+ // destination back on top instead of stacking a second one.+ backStack.backStack.any { it is Route.Call } -> backStack.reset(+ *backStack.backStack.filterNot { it is Route.Call }.toTypedArray(),+ Route.Call,+ )+ else -> backStack.add(Route.Call)+ }+ } else if (top is Route.Call) {+ backStack.pop()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.ktnew file mode 100644index 0000000000..97c0349bc0--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt@@ -0,0 +1,251 @@+package com.vayunmathur.communicate.ui++import androidx.compose.runtime.Composable+import com.vayunmathur.communicate.Route+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.signal.SignalFeature+import com.vayunmathur.communicate.ui.call.InAppCallScreen+import com.vayunmathur.communicate.ui.googlevoice.GoogleVoiceSignInScreen+import com.vayunmathur.communicate.ui.rcs.RcsRegistrationScreen+import com.vayunmathur.communicate.ui.signal.SignalRegistrationCaptchaScreen+import com.vayunmathur.communicate.ui.signal.SignalRegistrationCodeScreen+import com.vayunmathur.communicate.ui.signal.SignalRegistrationDoneScreen+import com.vayunmathur.communicate.ui.signal.SignalRegistrationNumberScreen+import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationCodeScreen+import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationDoneScreen+import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationNumberScreen+import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationPinScreen+import com.vayunmathur.library.util.EntryProviderScope+import com.vayunmathur.library.util.FullscreenPage+import com.vayunmathur.library.util.ListDetailPage+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.MorphPage+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.SiblingPage++@Composable+fun CommunicateNavGraph(backStack: NavBackStack<Route>) {+ MainNavigation(backStack) {+ coreEntries(backStack)+ registrationEntries(backStack)+ conversationEntries(backStack)+ callEntries(backStack)+ }+}++fun EntryProviderScope<Route>.coreEntries(backStack: NavBackStack<Route>) {+ entry<Route.Messages>(metadata = ListPage() + SiblingPage()) {+ MessagesScreen(+ onOpenThread = { thread ->+ val route = Route.Conversation(+ threadId = thread.threadId,+ address = thread.address,+ line = thread.line,+ remoteId = thread.remoteId,+ subscriptionId = thread.subscriptionId,+ isGroup = thread.isGroup,+ participants = thread.participants,+ groupTitle = thread.groupTitle,+ )+ // Re-tapping another thread replaces the detail instead of stacking+ // Conversation on Conversation.+ if (backStack.last() is Route.Conversation) backStack.setLast(route)+ else backStack.add(route)+ },+ onOpenAccounts = { backStack.add(Route.Accounts) },+ )+ }+ entry<Route.Dialer>(metadata = SiblingPage()) {+ DialerScreen()+ }+ entry<Route.CallLogs>(metadata = SiblingPage()) {+ CallLogsScreen()+ }+ entry<Route.Accounts>(metadata = ListDetailPage()) {+ AccountsScreen(+ onBack = { backStack.pop() },+ onSignIn = { backStack.add(Route.GoogleVoiceSignIn) },+ onRegisterWhatsApp = {+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ backStack.add(Route.WhatsAppRegistration.Number)+ }+ },+ onImportBackup = {+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ backStack.add(Route.WhatsAppBackupImport)+ }+ },+ onRegisterSignal = {+ if (SignalFeature.enabled) {+ backStack.add(Route.SignalRegistration.Number)+ }+ },+ onShowRcsStatus = {+ if (RcsFeature.enabled) {+ backStack.add(Route.RcsStatus)+ }+ },+ )+ }+}++/**+ * Replaces the WhatsApp registration steps on the stack with Done.+ *+ * Done is the terminal step: leaving it must exit registration (as the+ * single-screen flow's Done/Back buttons did), not step back into the+ * code/PIN steps for an already-registered number.+ */+internal fun NavBackStack<Route>.showWhatsAppRegistrationDone(cc: String, number: String) {+ while (backStack.lastOrNull() is Route.WhatsAppRegistration) pop()+ add(Route.WhatsAppRegistration.Done(cc, number))+}++/** Replaces the Signal registration steps on the stack with Done; see [showWhatsAppRegistrationDone]. */+internal fun NavBackStack<Route>.showSignalRegistrationDone(cc: String, number: String) {+ while (backStack.lastOrNull() is Route.SignalRegistration) pop()+ add(Route.SignalRegistration.Done(cc, number))+}++fun EntryProviderScope<Route>.registrationEntries(backStack: NavBackStack<Route>) {+ entry<Route.GoogleVoiceSignIn>(metadata = ListDetailPage()) {+ GoogleVoiceSignInScreen(+ onBack = { backStack.pop() },+ onSignedIn = { backStack.pop() },+ )+ }+ entry<Route.WhatsAppRegistration.Number>(metadata = ListDetailPage()) {+ WhatsAppRegistrationNumberScreen(+ onBack = { backStack.pop() },+ onCodeRequested = { cc, number ->+ backStack.add(Route.WhatsAppRegistration.Code(cc, number))+ },+ )+ }+ entry<Route.WhatsAppRegistration.Code>(metadata = ListDetailPage()) { route ->+ WhatsAppRegistrationCodeScreen(+ cc = route.cc,+ number = route.number,+ onBack = { backStack.pop() },+ onPinRequired = { cc, number ->+ backStack.add(Route.WhatsAppRegistration.Pin(cc, number))+ },+ onVerified = { cc, number -> backStack.showWhatsAppRegistrationDone(cc, number) },+ )+ }+ entry<Route.WhatsAppRegistration.Pin>(metadata = ListDetailPage()) { route ->+ WhatsAppRegistrationPinScreen(+ cc = route.cc,+ number = route.number,+ onBack = { backStack.pop() },+ onVerified = { cc, number -> backStack.showWhatsAppRegistrationDone(cc, number) },+ )+ }+ entry<Route.WhatsAppRegistration.Done>(metadata = ListDetailPage()) {+ WhatsAppRegistrationDoneScreen(+ onBack = { backStack.pop() },+ onRegistered = { backStack.pop() },+ )+ }+ entry<Route.WhatsAppBackupImport>(metadata = ListDetailPage()) {+ com.vayunmathur.communicate.ui.whatsapp.WhatsAppBackupImportScreen(+ onBack = { backStack.pop() },+ )+ }+ entry<Route.SignalRegistration.Number>(metadata = ListDetailPage()) {+ SignalRegistrationNumberScreen(+ onBack = { backStack.pop() },+ onCaptchaRequired = {
Diff truncated.