communicate: add Google Voice as a second line (merged inbox, SMS, VoIP calls)
- Commit
48b7e3b0a7a21c754c7025fd16cf4fce6622bf45- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 18:11 UTC (3 months ago)
- Parents
b166593
Diff
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 852c15e6b2..7d5f8b3c03 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -12,6 +12,18 @@ <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> + <!-- Google Voice virtual line: network for protojson RPCs + SIP/WSS, mic + audio+ routing for VoIP, self-managed calls, and the ongoing-call foreground service. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.RECORD_AUDIO" />+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />+ <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-feature android:name="android.hardware.telephony" android:required="false" />@@ -116,6 +128,22 @@ <action android:name="android.telecom.InCallService" /> </intent-filter> </service>++ <!-- Google Voice virtual line: self-managed ConnectionService (the "GV SIM") + the+ foreground service that hosts the active VoIP call. -->+ <service+ android:name=".telephony.GoogleVoiceConnectionService"+ android:exported="true"+ android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">+ <intent-filter>+ <action android:name="android.telecom.ConnectionService" />+ </intent-filter>+ </service>++ <service+ android:name=".telephony.GoogleVoiceCallForegroundService"+ android:exported="false"+ android:foregroundServiceType="phoneCall" /> </application> </manifest>
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 1ecc61a626..94ed06d73c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -5,6 +5,10 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconCall@@ -15,17 +19,36 @@ import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.MainNavigation 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.GoogleVoiceCallManager+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.call.CallScreen+import com.vayunmathur.communicate.ui.googlevoice.GoogleVoiceSignInScreen+import androidx.compose.ui.platform.LocalContext import kotlinx.serialization.Serializable sealed interface Route : NavKey { @Serializable data object Messages : Route @Serializable data object Dialer : Route @Serializable data object CallLogs : Route- @Serializable data class Conversation(val threadId: Long, val address: String) : Route+ @Serializable data object Accounts : Route+ @Serializable data object GoogleVoiceSignIn : Route++ @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,+ ) : Route } class MainActivity : ComponentActivity() {@@ -43,10 +66,26 @@ class MainActivity : ComponentActivity() { @Composable private fun CommunicateApp() {+ val context = LocalContext.current+ val session = remember { GoogleVoiceSession.get(context) }+ val gvSignedIn by session.signedInFlow.collectAsState(initial = false)+ val callState by GoogleVoiceCallManager.state.collectAsState()++ // Make Google Voice a selectable line and route inbound SIP INVITEs to the system.+ LaunchedEffect(gvSignedIn) {+ GoogleVoiceCallManager.init(context)+ GoogleVoiceCallManager.onIncomingCall = { from -> GoogleVoiceTelecom.addIncoming(context, from) }+ if (gvSignedIn) {+ val number = session.phoneNumber() ?: context.getString(R.string.account_google_voice)+ GoogleVoiceTelecom.registerPhoneAccount(context, number)+ }+ }+ val backStack = rememberNavBackStack<Route>(Route.Messages) val currentPage = backStack.last() val currentRoot = when (currentPage) { is Route.Conversation -> Route.Messages+ is Route.Accounts, is Route.GoogleVoiceSignIn -> Route.Messages else -> currentPage } val pages = listOf(@@ -55,10 +94,14 @@ private fun CommunicateApp() { BottomBarItem(stringResource(R.string.nav_call_logs), Route.CallLogs) { IconHistory() }, ) + val showBottomBar = currentPage is Route.Messages ||+ currentPage is Route.Dialer ||+ currentPage is Route.CallLogs+ MainNavigation( backStack = backStack, bottomBar = {- if (currentPage !is Route.Conversation) {+ if (showBottomBar) { BottomNavBar(backStack, pages, currentRoot) } },@@ -66,18 +109,45 @@ private fun CommunicateApp() { entry<Route.Messages> { MessagesScreen( onOpenThread = { thread ->- backStack.add(Route.Conversation(thread.threadId, thread.address))+ backStack.add(+ Route.Conversation(+ threadId = thread.threadId,+ address = thread.address,+ line = thread.line,+ remoteId = thread.remoteId,+ ),+ ) },+ onOpenAccounts = { backStack.add(Route.Accounts) }, ) } entry<Route.Dialer> { DialerScreen() } entry<Route.CallLogs> { CallLogsScreen() }+ entry<Route.Accounts> {+ AccountsScreen(+ onBack = { backStack.pop() },+ onSignIn = { backStack.add(Route.GoogleVoiceSignIn) },+ )+ }+ entry<Route.GoogleVoiceSignIn> {+ GoogleVoiceSignInScreen(+ onBack = { backStack.pop() },+ onSignedIn = { backStack.pop() },+ )+ } entry<Route.Conversation> { route -> ConversationScreen( threadId = route.threadId, address = route.address,+ line = route.line,+ remoteId = route.remoteId, onBack = { backStack.pop() }, ) } }++ // In-app call UI overlays everything while a Google Voice VoIP call is in progress.+ if (callState.phase != CallPhase.Idle) {+ CallScreen(onClose = { GoogleVoiceCallManager.clearEnded() })+ } }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex ea35874cab..85bfbc909f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -1,5 +1,15 @@ package com.vayunmathur.communicate.data +/**+ * Which line a conversation, message, or call belongs to. The physical SIM is the+ * default so every existing construction site (system-provider reads) stays valid;+ * Google Voice rows are tagged explicitly when merged in by the repository.+ */+enum class CommunicateLine {+ Sim,+ GoogleVoice,+}+ data class CommunicateContact( val id: Long, val name: String,@@ -24,6 +34,17 @@ data class CommunicateCallLogEntry( val type: CommunicateCallType, val timestampMillis: Long, val durationSeconds: Long,+ val line: CommunicateLine = CommunicateLine.Sim,+)++/**+ * A media item attached to a message. SIM MMS parts arrive as local `content://`+ * URIs; Google Voice media arrive as remote https URLs. [contentUri] holds whichever+ * form applies so the UI can load it uniformly.+ */+data class CommunicateAttachment(+ val contentUri: String,+ val mimeType: String, ) data class SmsThread(@@ -33,6 +54,13 @@ data class SmsThread( val snippet: String, val timestampMillis: Long, val unreadCount: Int,+ val line: CommunicateLine = CommunicateLine.Sim,+ /**+ * Google Voice thread id (e.g. `t.<...>`). Null for SIM threads, which are keyed by+ * the Long [threadId] from the system provider. GV rows synthesize a stable Long+ * [threadId] (hash of [remoteId]) so list keys and navigation still work.+ */+ val remoteId: String? = null, ) data class SmsMessage(@@ -43,4 +71,7 @@ data class SmsMessage( val timestampMillis: Long, val outgoing: Boolean, val read: Boolean,+ val line: CommunicateLine = CommunicateLine.Sim,+ val remoteId: String? = null,+ val attachments: List<CommunicateAttachment> = emptyList(), )
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 6a681cc1ff..90c5450d6f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -13,6 +13,13 @@ import android.telecom.PhoneAccount import android.telecom.TelecomManager import androidx.core.content.ContextCompat import androidx.core.net.toUri+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceWebSender+import com.vayunmathur.communicate.data.googlevoice.GvCall+import com.vayunmathur.communicate.data.googlevoice.GvCallType+import com.vayunmathur.communicate.data.googlevoice.GvMessage+import com.vayunmathur.communicate.data.googlevoice.GvThread import com.vayunmathur.library.ui.ExternalIntents object CommunicateRepository {@@ -225,6 +232,140 @@ object CommunicateRepository { } ExternalIntents.launch(context, intent) }++ // ------------------------------------------------------------------+ // Google Voice merge (second line)+ //+ // These suspend variants return SIM data (tagged CommunicateLine.Sim) merged with Google+ // Voice data (tagged CommunicateLine.GoogleVoice) when a GV session is present. All GV+ // network work is done here off the main thread; callers already invoke us from+ // Dispatchers.IO in produceState. GV failures are swallowed so the SIM inbox still loads.+ // ------------------------------------------------------------------++ /** Merged thread list: SIM threads + Google Voice threads, newest first. */+ suspend fun loadSmsThreadsMerged(context: Context): List<SmsThread> {+ val sim = loadSmsThreads(context)+ val gv = loadGoogleVoiceThreads(context)+ return (sim + gv).sortedByDescending { it.timestampMillis }+ }++ /** Route by line: SIM threads read the provider; GV threads hit `api2thread/get`. */+ suspend fun loadSmsMessagesMerged(context: Context, thread: SmsThread): List<SmsMessage> =+ when (thread.line) {+ CommunicateLine.Sim -> loadSmsMessages(context, thread.threadId)+ CommunicateLine.GoogleVoice -> {+ val remoteId = thread.remoteId ?: return emptyList()+ runCatching {+ GoogleVoiceClient.get(context).getThread(remoteId)+ .map { it.toSmsMessage(thread.threadId, context) }+ }.getOrDefault(emptyList())+ }+ }++ /** Merged call history: device call log + Google Voice calls, newest first. */+ suspend fun loadCallLogsMerged(context: Context): List<CommunicateCallLogEntry> {+ val device = loadCallLogs(context)+ val gv = loadGoogleVoiceCalls(context)+ return (device + gv).sortedByDescending { it.timestampMillis }+ }++ /**+ * Dispatch an outgoing message to the right line. SIM uses the existing composer path;+ * Google Voice posts through `api2thread/sendsms`. Returns true on success.+ */+ suspend fun sendMessage(+ context: Context,+ line: CommunicateLine,+ address: String,+ body: String,+ threadRemoteId: String? = null,+ ): Boolean = when (line) {+ CommunicateLine.Sim -> {+ openSmsComposer(context, address, body)+ true+ }+ CommunicateLine.GoogleVoice -> runCatching {+ // The bot-defense token is minted invisibly in an offscreen WebView; the app then+ // builds and sends the sendsms API call itself using that token.+ val activity = context as? android.app.Activity ?: return@runCatching false+ val token = GoogleVoiceWebSender.mintToken(activity, address, body) ?: return@runCatching false+ val sendBody = com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+ .buildSendSmsBody(address, body, threadRemoteId, botToken = token)+ GoogleVoiceClient.get(context).sendPreparedSms(sendBody)+ true+ }.getOrDefault(false)+ }++ /** Toggle a Google Voice thread attribute (read/archive/spam) via batchupdateattributes. */+ suspend fun updateGoogleVoiceThread(+ context: Context,+ remoteId: String,+ action: com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser.ThreadAction,+ ): Boolean = runCatching {+ GoogleVoiceClient.get(context).updateThreadAttributes(remoteId, action)+ true+ }.getOrDefault(false)++ private suspend fun loadGoogleVoiceThreads(context: Context): List<SmsThread> {+ val session = GoogleVoiceSession.get(context)+ if (!session.hasUsableCredentials()) return emptyList()+ return runCatching {+ GoogleVoiceClient.get(context).listThreads().map { it.toSmsThread(context) }+ }.getOrDefault(emptyList())+ }++ private suspend fun loadGoogleVoiceCalls(context: Context): List<CommunicateCallLogEntry> {+ val session = GoogleVoiceSession.get(context)+ if (!session.hasUsableCredentials()) return emptyList()+ return runCatching {+ GoogleVoiceClient.get(context).listCalls().map { it.toCallLogEntry(context) }+ }.getOrDefault(emptyList())+ }++ /** Stable positive Long key for a GV remote id, kept clear of provider thread ids. */+ fun stableThreadId(remoteId: String): Long = (remoteId.hashCode().toLong() and 0xFFFFFFFFL) or 0x1_0000_0000L++ private fun GvThread.toSmsThread(context: Context): SmsThread = SmsThread(+ threadId = stableThreadId(id),+ address = phoneNumber,+ displayName = displayName ?: findContactName(context, phoneNumber),+ snippet = snippet,+ timestampMillis = timestampMillis,+ unreadCount = unreadCount,+ line = CommunicateLine.GoogleVoice,+ remoteId = id,+ )++ private fun GvMessage.toSmsMessage(threadId: Long, context: Context): SmsMessage = SmsMessage(+ id = ("$threadId#$id").hashCode().toLong(),+ threadId = threadId,+ address = phoneNumber,+ body = text,+ timestampMillis = timestampMillis,+ outgoing = outgoing,+ read = read,+ line = CommunicateLine.GoogleVoice,+ remoteId = id,+ attachments = mediaUrls.map { CommunicateAttachment(it, "image/*") },+ )++ private fun GvCall.toCallLogEntry(context: Context): CommunicateCallLogEntry = CommunicateCallLogEntry(+ id = stableThreadId(id),+ displayName = displayName ?: findContactName(context, phoneNumber),+ phoneNumber = phoneNumber,+ type = type.toCommunicateCallType(),+ timestampMillis = timestampMillis,+ durationSeconds = durationSeconds,+ line = CommunicateLine.GoogleVoice,+ )++ private fun GvCallType.toCommunicateCallType(): CommunicateCallType = when (this) {+ GvCallType.Incoming -> CommunicateCallType.Incoming+ GvCallType.Outgoing -> CommunicateCallType.Outgoing+ GvCallType.Missed -> CommunicateCallType.Missed+ GvCallType.Voicemail -> CommunicateCallType.Voicemail+ GvCallType.Unknown -> CommunicateCallType.Unknown+ } } private fun Context.hasPermission(permission: String): Boolean =
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceAuth.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceAuth.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceAuth.ktnew file mode 100644index 0000000000..ff943a02e8--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceAuth.kt@@ -0,0 +1,66 @@+package com.vayunmathur.communicate.data.googlevoice++import java.security.MessageDigest++/**+ * Builds the authentication material for Google Voice web RPCs.+ *+ * Google's browser RPCs authenticate with cookies plus a `SAPISIDHASH` Authorization+ * header (the same scheme used across Google web properties):+ *+ * ```+ * Authorization: SAPISIDHASH <ts>_<sha1hex(ts + " " + SAPISID + " " + origin)>+ * ```+ *+ * where `ts` is the current unix time in seconds and `origin` is `https://voice.google.com`.+ * See `voice-documentation.md` — the exact hash was not preserved in the HAR, but this is+ * the well-known, stable construction Google uses for these endpoints.+ *+ * The functions here are pure so they can be unit-tested without a device/session.+ */+object GoogleVoiceAuth {++ const val ORIGIN = "https://voice.google.com"+ const val REFERER = "https://voice.google.com/"+ const val CONTENT_TYPE = "application/json+protobuf"++ /** `<ts>_<sha1hex>` per the SAPISIDHASH scheme. */+ fun sapisidHash(timestampSeconds: Long, sapisid: String, origin: String = ORIGIN): String {+ val digestInput = "$timestampSeconds $sapisid $origin"+ val sha1 = sha1Hex(digestInput)+ return "${timestampSeconds}_$sha1"+ }++ /** Full `Authorization` header value. */+ fun authorization(timestampSeconds: Long, sapisid: String, origin: String = ORIGIN): String =+ "SAPISIDHASH ${sapisidHash(timestampSeconds, sapisid, origin)}"++ /**+ * Assemble the header set observed on Voice RPCs. [nowSeconds] is injectable for tests.+ */+ fun headers(+ cookieHeader: String,+ sapisid: String,+ authUser: String,+ nowSeconds: Long = System.currentTimeMillis() / 1000,+ ): Map<String, String> = buildMap {+ put("Authorization", authorization(nowSeconds, sapisid))+ put("Cookie", cookieHeader)+ put("Content-Type", CONTENT_TYPE)+ put("Origin", ORIGIN)+ put("Referer", REFERER)+ put("X-Goog-AuthUser", authUser)+ put("X-Requested-With", "XMLHttpRequest")+ // Voice web sends a recent Chrome UA; keep it stable so the endpoints behave.+ put(+ "User-Agent",+ "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) " ++ "Chrome/126.0.0.0 Mobile Safari/537.36",+ )+ }++ fun sha1Hex(input: String): String {+ val bytes = MessageDigest.getInstance("SHA-1").digest(input.toByteArray(Charsets.UTF_8))+ return bytes.joinToString("") { "%02x".format(it) }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.ktnew file mode 100644index 0000000000..f398c44ea6--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt@@ -0,0 +1,126 @@+package com.vayunmathur.communicate.data.googlevoice++import android.content.Context+import com.vayunmathur.library.network.NetworkClient+import java.io.IOException++/** Raised when the Google Voice session is missing or rejected (401/403) so callers re-auth. */+class GoogleVoiceAuthException(message: String) : IOException(message)++/**+ * Thin client over the documented Google Voice web RPCs (`voice-documentation.md`,+ * Reverse-Slice Summary + Second Capture). All requests are+ * `POST https://clients6.google.com/voice/v1/voiceclient/<path>?alt=protojson&key=<apiKey>`+ * with `application/json+protobuf` positional-array bodies and cookie + SAPISIDHASH auth.+ *+ * Networking goes through the repo's [NetworkClient] (HttpURLConnection, no OkHttp); parsing+ * is delegated to [GoogleVoiceParser].+ */+class GoogleVoiceClient(private val session: GoogleVoiceSession) {++ suspend fun getAccount(): GvAccount {+ val body = post("account/get", GoogleVoiceParser.buildAccountBody())+ val account = GoogleVoiceParser.parseAccount(body)+ account.phoneNumber?.let { session.setPhoneNumber(it) }+ return account+ }++ suspend fun listThreads(folder: GvFolder = GvFolder.Inbox): List<GvThread> {+ val body = post("api2thread/list", GoogleVoiceParser.buildListBody(folder))+ return GoogleVoiceParser.parseThreads(body, session.phoneNumber())+ }++ /**+ * Messages for a single thread. `api2thread/get` returned only an empty stub for our request+ * shape, but `api2thread/list` embeds every message per thread, so we read them from there+ * (checking the Inbox then the All folder).+ */+ suspend fun getThread(remoteId: String): List<GvMessage> {+ val self = session.phoneNumber()+ for (folder in listOf(GvFolder.Inbox, GvFolder.All)) {+ val body = post("api2thread/list", GoogleVoiceParser.buildListBody(folder, pageSize = 100, window = 50))+ val messages = GoogleVoiceParser.parseThreadMessages(body, remoteId, self)+ if (messages.isNotEmpty()) return messages+ if (GoogleVoiceParser.parseThreads(body, self).any { it.id == remoteId }) return messages+ }+ return emptyList()+ }++ suspend fun search(query: String): List<GvThread> {+ val body = post("api2thread/search", GoogleVoiceParser.buildSearchBody(query))+ return GoogleVoiceParser.parseThreads(body, session.phoneNumber())+ }++ suspend fun listCalls(): List<GvCall> {+ val body = post("api2thread/list", GoogleVoiceParser.buildListBody(GvFolder.Calls))+ return GoogleVoiceParser.parseCalls(body, session.phoneNumber())+ }++ suspend fun sendSms(recipient: String, text: String, threadRemoteId: String? = null) {+ post("api2thread/sendsms", GoogleVoiceParser.buildSendSmsBody(recipient, text, threadRemoteId))+ }++ /** Replay an exact, already-token-bearing sendsms body captured from the web app. */+ suspend fun sendPreparedSms(body: String) {+ post("api2thread/sendsms", body)+ }++ suspend fun updateThreadAttributes(remoteId: String, action: GoogleVoiceParser.ThreadAction) {+ post("thread/batchupdateattributes", GoogleVoiceParser.buildBatchUpdateBody(remoteId, action))+ }++ suspend fun markAllRead() {+ // Real web body: [1] (folder id), not {}.+ post("thread/markallread", "[1]")+ }++ suspend fun getSipRegisterInfo(): GvSipRegisterInfo {+ // Real web body: [3, "<12-char client token>"]; [{},{}] returns HTTP 400.+ val token = (1..12).map { TOKEN_CHARS[kotlin.random.Random.nextInt(TOKEN_CHARS.length)] }.joinToString("")+ val body = post("sipregisterinfo/get", "[3,${'"'}$token${'"'}]")+ return GoogleVoiceParser.parseSipRegisterInfo(body)+ }++ // ------------------------------------------------------------------++ private suspend fun post(path: String, jsonBody: String): String {+ val cookie = session.cookieHeader()+ val sapisid = session.sapisid()+ val apiKey = session.apiKey()+ val authUser = session.authUser()+ if (cookie.isNullOrBlank() || sapisid.isNullOrBlank() || apiKey.isNullOrBlank()) {+ throw GoogleVoiceAuthException("Missing Google Voice session")+ }++ val url = "$BASE$path?alt=protojson&key=$apiKey"+ val headers = GoogleVoiceAuth.headers(cookie, sapisid, authUser)+ val response = NetworkClient.performRequest(+ url = url,+ method = "POST",+ headers = headers,+ body = jsonBody,+ )+ if (response.status == 401 || response.status == 403) {+ throw GoogleVoiceAuthException("Google Voice auth rejected (${response.status})")+ }+ if (!response.isSuccess) {+ android.util.Log.e(TAG, "$path failed HTTP ${response.status}: ${response.body.take(500)}")+ throw IOException("Google Voice ${path} failed: HTTP ${response.status}")+ }+ // TEMP diagnostic logging of raw protojson so the positional parser can be pinned to the+ // real wire shapes. Chunked because logcat truncates long lines.+ val body = response.body+ android.util.Log.d(TAG, "$path <= ${body.length} bytes")+ body.chunked(3500).forEachIndexed { i, chunk -> android.util.Log.d(TAG, "$path[$i] $chunk") }+ return body+ }++ companion object {+ private const val TAG = "GoogleVoiceRaw"+ private const val TOKEN_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+ private const val BASE = "https://clients6.google.com/voice/v1/voiceclient/"++ fun get(context: Context): GoogleVoiceClient =+ GoogleVoiceClient(GoogleVoiceSession.get(context))+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.ktnew file mode 100644index 0000000000..3fefa5d82a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt@@ -0,0 +1,63 @@+package com.vayunmathur.communicate.data.googlevoice++/**+ * Internal DTOs for the Google Voice data layer, produced by [GoogleVoiceParser] from the+ * reverse-engineered protojson responses and mapped by the repository onto the shared+ * `Communicate*` models. Keeping them separate isolates the (fragile, positional) wire+ * shapes from the rest of the app.+ */++data class GvAccount(+ /** The account's primary Google Voice number, in whatever form the wire returned. */+ val phoneNumber: String?,+)++/** Folder/tab enum for `api2thread/list` (slot 0). Values observed 1–5 in capture 2. */+enum class GvFolder(val id: Int) {+ All(1),+ Inbox(2),+ // 3/4/5 map to calls/voicemail/spam-style folders; exact mapping is unproven from the+ // wire (see voice-documentation.md "Folder Navigation Shape").+ Calls(3),+ Voicemail(4),+ Spam(5),+}++data class GvMessage(+ val id: String,+ val threadId: String,+ val phoneNumber: String,+ val text: String,+ val timestampMillis: Long,+ val outgoing: Boolean,+ val read: Boolean,+ val mediaUrls: List<String> = emptyList(),+)++data class GvThread(+ val id: String,+ val phoneNumber: String,+ val displayName: String?,+ val snippet: String,+ val timestampMillis: Long,+ val unreadCount: Int,+ val messages: List<GvMessage> = emptyList(),+)++enum class GvCallType { Incoming, Outgoing, Missed, Voicemail, Unknown }++data class GvCall(+ val id: String,+ val phoneNumber: String,+ val displayName: String?,+ val type: GvCallType,+ val timestampMillis: Long,+ val durationSeconds: Long,+)++/** SIP registration material from `sipregisterinfo/get`, consumed by the calling layer. */+data class GvSipRegisterInfo(+ val phoneNumber: String?,+ /** Opaque registration credential/token strings observed in the response tail. */+ val credentials: List<String>,+)
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.ktnew file mode 100644index 0000000000..6f3527c614--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt@@ -0,0 +1,342 @@+package com.vayunmathur.communicate.data.googlevoice++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.add+import kotlinx.serialization.json.addJsonArray++/**+ * Converts Google Voice protojson (`alt=protojson`, `application/json+protobuf`) bodies to+ * and from [GoogleVoiceModels]. Google's RPCs use *positional* JSON arrays with no field+ * names, so **every** array index / wire assumption is deliberately quarantined in this+ * one file. If Google shifts a slot, this is the only place that needs to change.+ *+ * The shapes here are reverse-engineered from `voice-documentation.md` (two HAR captures)+ * and are intentionally tolerant: parsing walks the tree heuristically (find the id-prefixed+ * records, then the phone / timestamp / text inside them) rather than hard-coding brittle+ * deep indices, because the captures preserved shape but not exact offsets. They must be+ * validated against live responses; see the plan's "Key Risks".+ */+object GoogleVoiceParser {++ val json = Json {+ ignoreUnknownKeys = true+ isLenient = true+ }++ // ------------------------------------------------------------------+ // Request body builders (documented shapes)+ // ------------------------------------------------------------------++ /** `api2thread/list`: `[folder,pageSize,window,null,null,[null,1,1,1]]`. */+ fun buildListBody(folder: GvFolder, pageSize: Int = 20, window: Int = 15): String =+ buildJsonArray {+ add(JsonPrimitive(folder.id))+ add(JsonPrimitive(pageSize))+ add(JsonPrimitive(window))+ add(JsonNull)+ add(JsonNull)+ addJsonArray {+ add(JsonNull); add(JsonPrimitive(1)); add(JsonPrimitive(1)); add(JsonPrimitive(1))+ }+ }.toString()++ /** `api2thread/search`: `["<query>",200,null,null,null,[null,1,1,1]]`. */+ fun buildSearchBody(query: String, limit: Int = 200): String =+ buildJsonArray {+ add(JsonPrimitive(query))+ add(JsonPrimitive(limit))+ add(JsonNull)+ add(JsonNull)+ add(JsonNull)+ addJsonArray {+ add(JsonNull); add(JsonPrimitive(1)); add(JsonPrimitive(1)); add(JsonPrimitive(1))+ }+ }.toString()++ /** `account/get`: `[null,{}]`. */+ fun buildAccountBody(): String =+ buildJsonArray {+ add(JsonNull)+ add(JsonObject(emptyMap()))+ }.toString()++ /**+ * `api2thread/sendsms`, real positional shape recovered from the HAR:+ * `[null,null,null,null, <text>, <threadId|null>, <[recipient]|null>, null, [<clientTxnId>], <media|null>, ["!<botToken>"...]]`+ *+ * ⚠️ The trailing `"!…"` entry is a Google bot-defense (WAA/botguard) token minted by the+ * site's obfuscated JS; it cannot be produced natively, and the server rejects sends without+ * it (HTTP 400 INVALID_ARGUMENT). We build the correct prefix; [botToken] must be supplied by+ * a WebView that ran Google's JS for the send to actually succeed.+ */+ fun buildSendSmsBody(+ recipient: String,+ text: String,+ threadRemoteId: String?,+ clientTxnId: Long = kotlin.random.Random.nextLong(1, Long.MAX_VALUE),+ botToken: String? = null,+ ): String = buildJsonArray {+ add(JsonNull); add(JsonNull); add(JsonNull); add(JsonNull)+ add(JsonPrimitive(text))+ add(threadRemoteId?.let { JsonPrimitive(it) } ?: JsonNull)+ if (threadRemoteId == null) {+ addJsonArray { add(JsonPrimitive(recipient)) }+ } else {+ add(JsonNull)+ }+ add(JsonNull)+ addJsonArray { add(JsonPrimitive(clientTxnId)) }+ add(JsonNull)+ if (botToken != null) {+ addJsonArray { add(JsonPrimitive(botToken)) }+ }+ }.toString()++ /** Attribute mutations funnelled through `thread/batchupdateattributes`. */+ enum class ThreadAction { MarkRead, MarkUnread, Archive, Unarchive }++ /**+ * `thread/batchupdateattributes`, matching the exact web shapes recovered from the HARs:+ * - read/unread toggles the flag at key index 3: `[[[["<id>",null,null,<v>],[null,null,null,1],1]]]`+ * - archive/unarchive toggles the flag at key index 2: `[[[["<id>",null,<v>],[null,null,1],1]]]`+ * (Getting these slots wrong archives a thread when you meant to mark it read.)+ */+ fun buildBatchUpdateBody(remoteId: String, action: ThreadAction): String {+ val id = quote(remoteId)+ return when (action) {+ ThreadAction.MarkRead -> "[[[[$id,null,null,1],[null,null,null,1],1]]]"+ ThreadAction.MarkUnread -> "[[[[$id,null,null,0],[null,null,null,1],1]]]"+ ThreadAction.Archive -> "[[[[$id,null,1],[null,null,1],1]]]"+ ThreadAction.Unarchive -> "[[[[$id,null,0],[null,null,1],1]]]"+ }+ }++ private fun quote(s: String): String = JsonPrimitive(s).toString()++ /** Pull the `"!…"` WAA/botguard token out of a captured web `sendsms` body. */+ fun extractBotToken(capturedBody: String): String? {+ val root = parseOrNull(capturedBody) as? JsonArray ?: return null+ // The token is a string element (usually the last non-null) starting with '!'.+ fun search(el: JsonElement): String? {+ when (el) {+ is JsonArray -> for (c in el) search(c)?.let { return it }+ is JsonPrimitive -> if (el.isString && el.content.startsWith("!")) return el.content+ else -> {}+ }+ return null+ }+ return search(root)+ }++ // ------------------------------------------------------------------+ // Response parsing+ // ------------------------------------------------------------------++ fun parseAccount(body: String): GvAccount {+ val root = parseOrNull(body) ?: return GvAccount(null)+ // The primary number is the first phone-shaped string in the (large) account array.+ val phone = firstPhone(root)+ return GvAccount(phoneNumber = phone)+ }++ fun parseThreads(body: String, selfNumber: String? = null): List<GvThread> {+ val root = parseOrNull(body) ?: return emptyList()+ return findRecords(root, prefixes = listOf("t.")).mapNotNull { it.toThread() }+ .filter { it.phoneNumber.isNotBlank() || it.snippet.isNotBlank() || it.messages.isNotEmpty() }+ .distinctBy { it.id }+ }++ /**+ * Messages of a single thread. `api2thread/get` returned an empty stub for our request shape,+ * but every message is already embedded in the `api2thread/list` record ([2]); the repository+ * therefore feeds a list-record body here.+ */+ fun parseThreadMessages(body: String, threadId: String, selfNumber: String? = null): List<GvMessage> {+ val root = parseOrNull(body) ?: return emptyList()+ val record = findRecords(root, prefixes = listOf("t.", "c."))+ .firstOrNull { recordId(it) == threadId }+ ?: return emptyList()+ return record.toThread()?.messages ?: emptyList()+ }++ fun parseCalls(body: String, selfNumber: String? = null): List<GvCall> {+ val root = parseOrNull(body) ?: return emptyList()+ return findRecords(root, prefixes = listOf("c.")).mapNotNull { record ->+ val id = recordId(record) ?: return@mapNotNull null+ val items = record.arrAt(ITEMS)?.mapNotNull { it as? JsonArray }.orEmpty()+ val newest = items.firstOrNull()+ val counterparty = counterpartyOf(record, newest) ?: return@mapNotNull null+ val duration = newest?.longAt(ITEM_DURATION) ?: 0L+ val outgoing = newest != null &&+ normalizePhone(newest.strAt(ITEM_OWN).orEmpty()) == normalizePhone(counterparty)+ GvCall(+ id = id,+ phoneNumber = counterparty,+ displayName = null,+ type = when {+ outgoing -> GvCallType.Outgoing+ duration <= 0 -> GvCallType.Missed+ else -> GvCallType.Incoming+ },+ timestampMillis = newest?.longAt(ITEM_TS)?.let { normalizeTimestampMillis(it) } ?: 0L,+ durationSeconds = duration,+ )+ }.distinctBy { it.id }+ }++ fun parseSipRegisterInfo(body: String): GvSipRegisterInfo {+ val root = parseOrNull(body) ?: return GvSipRegisterInfo(null, emptyList())+ val phone = firstPhone(root)+ // The tail carries long opaque credential strings (~56/24 chars in the capture).+ val creds = allStrings(root).filter { it.length in 20..512 && !looksLikePhone(it) }+ return GvSipRegisterInfo(phoneNumber = phone, credentials = creds)+ }++ // ------------------------------------------------------------------+ // 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.+ // ------------------------------------------------------------------++ private const val ITEMS = 2+ private const val ITEM_ID = 0+ private const val ITEM_TS = 1+ private const val ITEM_OWN = 2+ private const val ITEM_PARTICIPANTS = 3+ private const val ITEM_TYPE = 4+ private const val ITEM_DURATION = 8+ private const val ITEM_BODY = 9++ private fun parseOrNull(body: String): JsonElement? =+ runCatching { json.parseToJsonElement(body.ifBlank { "null" }) }.getOrNull()+ ?.takeIf { it !is JsonNull }++ /**+ * Depth-first collect the outermost arrays whose first primitive element is a string with one+ * of [prefixes]. Google keys threads by `t.<number>` and calls by `c.<opaque>`. Records are+ * not recursed into once matched.+ */+ private fun findRecords(root: JsonElement, prefixes: List<String>): List<JsonArray> {+ val out = mutableListOf<JsonArray>()+ fun visit(el: JsonElement) {+ if (el is JsonArray) {+ val id = (el.firstOrNull() as? JsonPrimitive)?.takeIf { it.isString }?.content+ if (id != null && prefixes.any { id.startsWith(it) }) {+ out.add(el)+ return+ }+ el.forEach { visit(it) }+ } else if (el is JsonObject) {+ el.values.forEach { visit(it) }+ }+ }+ visit(root)+ return out+ }++ private fun JsonArray.toThread(): GvThread? {+ val id = recordId(this) ?: return null+ val itemArrays = arrAt(ITEMS)?.mapNotNull { it as? JsonArray }.orEmpty()+ // SMS thread ids embed the counterparty ("t.+1415..."/"t.37407"); calls don't.+ val idNumber = id.removePrefix("t.").takeIf { it != id && (looksLikePhone(it) || it.all { c -> c.isDigit() }) }+ val newest = itemArrays.firstOrNull()+ val counterparty = idNumber ?: counterpartyOf(this, newest) ?: ""+ val messages = itemArrays.mapIndexedNotNull { index, item ->+ item.toMessage(id, counterparty, index)+ }.sortedBy { it.timestampMillis }+ val newestMsg = messages.maxByOrNull { it.timestampMillis }+ return GvThread(+ id = id,+ phoneNumber = counterparty,+ displayName = null,+ snippet = newestMsg?.text.orEmpty(),+ timestampMillis = newestMsg?.timestampMillis ?: (newest?.longAt(ITEM_TS)?.let { normalizeTimestampMillis(it) } ?: 0L),+ unreadCount = 0,+ messages = messages,+ )+ }++ private fun JsonArray.toMessage(threadId: String, threadCounterparty: String, index: Int): GvMessage? {+ val ts = longAt(ITEM_TS)?.let { normalizeTimestampMillis(it) } ?: return null+ val counterparty = (arrAt(ITEM_PARTICIPANTS)?.strAt(0))+ ?.takeIf { it.isNotBlank() }+ ?: threadCounterparty+ // Direction is the type field: 10 = inbound SMS, 11 = outbound SMS (confirmed from the wire).+ val type = longAt(ITEM_TYPE)+ val outgoing = type == 11L+ return GvMessage(+ id = strAt(ITEM_ID) ?: "$threadId#$index",+ threadId = threadId,+ phoneNumber = counterparty,+ text = strAt(ITEM_BODY).orEmpty(),+ timestampMillis = ts,+ outgoing = outgoing,+ read = true,+ )+ }++ /** Counterparty from a record: newest item participants, then record-level participant slots. */+ private fun counterpartyOf(record: JsonArray, newest: JsonArray?): String? {+ (newest?.arrAt(ITEM_PARTICIPANTS)?.strAt(0))?.takeIf { it.isNotBlank() }?.let { return it }+ (record.arrAt(4)?.arrAt(0)?.strAt(0))?.takeIf { it.isNotBlank() }?.let { return it }+ (record.arrAt(7)?.strAt(0))?.takeIf { it.isNotBlank() }?.let { return it }+ val fromId = recordId(record)?.removePrefix("t.")+ if (fromId != null && (looksLikePhone(fromId) || fromId.all { it.isDigit() })) return fromId+ return null+ }++ private fun recordId(record: JsonArray): String? =+ (record.firstOrNull() as? JsonPrimitive)?.takeIf { it.isString }?.content++ private fun JsonArray.strAt(i: Int): String? =+ (getOrNull(i) as? JsonPrimitive)?.takeIf { it.isString }?.content++ private fun JsonArray.longAt(i: Int): Long? =+ (getOrNull(i) as? JsonPrimitive)?.takeIf { !it.isString }?.content?.toLongOrNull()++ private fun JsonArray.arrAt(i: Int): JsonArray? = getOrNull(i) as? JsonArray++ private val PHONE = Regex("^\\+?[0-9]{7,15}$")+ fun looksLikePhone(raw: String): Boolean = PHONE.matches(raw.replace(" ", "").replace("-", ""))++ /** First phone-shaped string, optionally skipping the account's own number. */+ private fun firstPhone(el: JsonElement, exclude: String? = null): String? {+ val normalizedExclude = exclude?.let { normalizePhone(it) }+ return allStrings(el).firstOrNull {+ looksLikePhone(it) && (normalizedExclude == null || normalizePhone(it) != normalizedExclude)+ }+ }++ private fun normalizePhone(raw: String): String = raw.filter { it.isDigit() }.takeLast(10)++ /** GV timestamps appear as µs (16 digits), ms (13), or s (10); normalize to millis. */+ fun normalizeTimestampMillis(raw: Long): Long = when {+ raw <= 0 -> 0+ raw >= 1_000_000_000_000_000L -> raw / 1000+ raw >= 1_000_000_000_000L -> raw+ raw >= 1_000_000_000L -> raw * 1000+ else -> 0+ }++ private fun allStrings(el: JsonElement): List<String> {+ val out = mutableListOf<String>()+ fun visit(e: JsonElement) {+ when (e) {+ is JsonArray -> e.forEach { visit(it) }+ is JsonObject -> e.values.forEach { visit(it) }+ is JsonPrimitive -> if (e.isString) out.add(e.content)+ }+ }+ visit(el)+ return out+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.ktnew file mode 100644index 0000000000..1afb004429--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt@@ -0,0 +1,108 @@+package com.vayunmathur.communicate.data.googlevoice++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++/**+ * DataStore-backed store for the Google Voice web session captured by the WebView+ * sign-in flow. Google Voice has no public API, so every authenticated RPC replays+ * the browser's cookies plus the sniffed web `apiKey`; this persists that material+ * (see `voice-documentation.md` "Authentication, Headers, And Request Conventions").+ *+ * Cookies and the API key are sensitive; they live in the app's private,+ * credential-encrypted DataStore file like any other secret in this repo.+ */+class GoogleVoiceSession private constructor(private val store: DataStoreUtils) {++ /** Raw `Cookie:` header value captured from the signed-in voice.google.com session. */+ suspend fun cookieHeader(): String? = store.getStringAwait(KEY_COOKIE)++ /** SAPISID cookie value, extracted from [cookieHeader] for SAPISIDHASH auth. */+ suspend fun sapisid(): String? = store.getStringAwait(KEY_SAPISID)++ /** Web `key=` API key sniffed from a voiceclient RPC URL. */+ suspend fun apiKey(): String? = store.getStringAwait(KEY_API_KEY)++ /** `x-goog-authuser` index (the `/u/<n>/` account slot). Defaults to "0". */+ suspend fun authUser(): String = store.getStringAwait(KEY_AUTHUSER) ?: "0"++ /** The account's Google Voice phone number (from `account/get`), for display + line label. */+ suspend fun phoneNumber(): String? = store.getStringAwait(KEY_PHONE_NUMBER)++ suspend fun isSignedIn(): Boolean = store.getBooleanAwait(KEY_SIGNED_IN, default = false)++ /** Reactive sign-in state for UI (Accounts screen, line pickers). */+ val signedInFlow: Flow<Boolean>+ get() = store.booleanFlow(KEY_SIGNED_IN)++ /** True only when we have the minimum needed to make an authenticated RPC. */+ suspend fun hasUsableCredentials(): Boolean =+ !cookieHeader().isNullOrBlank() && !apiKey().isNullOrBlank() && !sapisid().isNullOrBlank()++ /**+ * Persist the material captured by the WebView. [cookieHeader] is the full cookie+ * string; [sapisid] is extracted from it here if not supplied.+ */+ suspend fun save(+ cookieHeader: String,+ apiKey: String,+ authUser: String,+ sapisid: String? = null,+ ) {+ store.setString(KEY_COOKIE, cookieHeader)+ store.setString(KEY_API_KEY, apiKey)+ store.setString(KEY_AUTHUSER, authUser)+ val resolvedSapisid = sapisid ?: extractSapisid(cookieHeader)+ if (resolvedSapisid != null) store.setString(KEY_SAPISID, resolvedSapisid)+ store.setBoolean(KEY_SIGNED_IN, true)+ }++ /** Refresh just the cookie string (e.g. after a WebView revisit), keeping other fields. */+ suspend fun updateCookies(cookieHeader: String) {+ store.setString(KEY_COOKIE, cookieHeader)+ extractSapisid(cookieHeader)?.let { store.setString(KEY_SAPISID, it) }+ }++ suspend fun setPhoneNumber(number: String) {+ store.setString(KEY_PHONE_NUMBER, number)+ }++ suspend fun signOut() {+ store.removeKeys(+ listOf(KEY_COOKIE, KEY_SAPISID, KEY_API_KEY, KEY_AUTHUSER, KEY_PHONE_NUMBER),+ )+ store.setBoolean(KEY_SIGNED_IN, false)+ }++ val phoneNumberFlow: Flow<String?>+ get() = store.stringFlow(KEY_PHONE_NUMBER).map { it }++ companion object {+ private const val KEY_COOKIE = "gv_cookie"+ private const val KEY_SAPISID = "gv_sapisid"+ private const val KEY_API_KEY = "gv_api_key"+ private const val KEY_AUTHUSER = "gv_authuser"+ private const val KEY_PHONE_NUMBER = "gv_phone_number"+ private const val KEY_SIGNED_IN = "gv_signed_in"++ fun get(context: Context): GoogleVoiceSession =+ GoogleVoiceSession(DataStoreUtils.getInstance(context.applicationContext))++ /**+ * Pull the SAPISID (or __Secure-3PAPISID as a fallback) value out of a raw cookie+ * header. Google's SAPISIDHASH scheme signs requests with this value.+ */+ fun extractSapisid(cookieHeader: String): String? {+ val cookies = cookieHeader.split(';').map { it.trim() }+ fun value(name: String): String? = cookies+ .firstOrNull { it.startsWith("$name=") }+ ?.substringAfter('=')+ ?.takeIf { it.isNotBlank() }+ return value("SAPISID")+ ?: value("__Secure-3PAPISID")+ ?: value("__Secure-1PAPISID")+ }+ }+}
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.ktnew file mode 100644index 0000000000..a7dcaa80aa--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt@@ -0,0 +1,239 @@+package com.vayunmathur.communicate.data.googlevoice++import android.annotation.SuppressLint+import android.app.Activity+import android.util.Log+import android.view.ViewGroup+import android.webkit.CookieManager+import android.webkit.JavascriptInterface+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull++/**+ * Sends a Google Voice SMS by borrowing Google's own bot-defense token, invisibly.+ *+ * `api2thread/sendsms` requires a `"!…"` WAA/botguard token that only Google's obfuscated JS can+ * mint. We therefore run the real web app in a **1×1, fully transparent, offscreen** WebView, let+ * its JS build the send request (which mints the token), **intercept and block** that request so+ * the WebView never actually sends, capture the full token-bearing body, and **replay it from the+ * app's native HTTP path** ([GoogleVoiceClient.sendPreparedSms]). Nothing is shown to the user.+ *+ * The composer DOM is obfuscated, so the injected automation logs each step to Logcat (`GVAUTO`).+ */+object GoogleVoiceWebSender {++ private const val TAG = "GVAUTO"++ private var webView: WebView? = null++ @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 `"!…"`+ * token. The actual send is then performed natively by the app (see [CommunicateRepository]).+ */+ suspend fun mintToken(activity: Activity, recipient: String, text: String): String? {+ val body = mintBody(activity, recipient, text) ?: return null+ return GoogleVoiceParser.extractBotToken(body)+ }++ /** Drive the offscreen WebView to produce the exact sendsms body (with token). */+ private suspend fun mintBody(activity: Activity, recipient: String, text: String): String? {+ val deferred = CompletableDeferred<String>()+ withContext(Dispatchers.Main) {+ pending = deferred+ val wv = ensureWebView(activity, recipient, text)+ wv.loadUrl("https://voice.google.com/u/0/messages")+ }+ val body = withTimeoutOrNull(60_000) { deferred.await() }+ withContext(Dispatchers.Main) { runCatching { webView?.stopLoading() } }+ return body+ }++ @SuppressLint("SetJavaScriptEnabled")+ private fun ensureWebView(activity: Activity, recipient: String, text: String): WebView {+ webView?.let { return it }+ CookieManager.getInstance().setAcceptCookie(true)+ val wv = WebView(activity)+ CookieManager.getInstance().setAcceptThirdPartyCookies(wv, true)+ wv.settings.javaScriptEnabled = true+ wv.settings.domStorageEnabled = true+ 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")+ // 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)) {+ runCatching {+ WebViewCompat.addDocumentStartJavaScript(wv, hookScript(), setOf("https://voice.google.com"))+ }+ }+ wv.webViewClient = object : WebViewClient() {+ private var injected = false+ override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {+ super.onPageStarted(view, url, favicon)+ // Fallback hook injection for devices without DOCUMENT_START_SCRIPT.+ view?.evaluateJavascript(hookScript(), null)+ }+ override fun onPageFinished(view: WebView?, url: String?) {+ super.onPageFinished(view, url)+ if (injected || url == null || !url.contains("voice.google.com/u/")) return+ injected = true+ view?.evaluateJavascript(automationScript(recipient, text), null)+ }+ }+ // Place the WebView BEHIND the app's opaque UI: it must lay out on-screen for GV's CDK+ // autocomplete/overlay (recipient chip) to work, but the opaque Compose content covers it+ // (invisible) and receives all touches, so it stays hidden and non-interactive.+ val decor = activity.window.decorView as ViewGroup+ decor.addView(wv, 0, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))+ webView = wv+ return wv+ }++ private class Bridge {+ @JavascriptInterface+ fun onBody(body: String) {+ Log.d(TAG, "captured sendsms body (${body.length} bytes)")+ pending?.complete(body)+ }++ @JavascriptInterface+ fun log(msg: String) {+ Log.d(TAG, msg)+ }+ }++ /** Installed at document-start: hook fetch + XHR to capture & block the sendsms request. */+ private fun hookScript(): String = """+ (function(){+ if(window.__gvHook) return; window.__gvHook=1;+ function log(m){ try{ AndroidGV.log(""+m);}catch(e){} }+ var of = window.fetch;+ window.fetch = function(input, init){+ try{+ var url = (typeof input==='string')?input:(input&&input.url);+ if(url && url.indexOf('api2thread/sendsms')>=0){+ var b = init && init.body;+ if(typeof b==='string'){ AndroidGV.onBody(b); log('blocked fetch sendsms');+ return Promise.resolve(new Response('[]',{status:200,headers:{'Content-Type':'application/json+protobuf'}}));+ }+ }+ }catch(e){ log('fetch hook err '+e); }+ return of.apply(this, arguments);+ };+ var ou = XMLHttpRequest.prototype.open, os = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.open=function(m,u){ this.__u=u; return ou.apply(this,arguments); };+ XMLHttpRequest.prototype.send=function(b){+ try{+ if(this.__u && this.__u.indexOf('api2thread/sendsms')>=0 && typeof b==='string'){+ AndroidGV.onBody(b); log('blocked xhr sendsms');+ var self=this;+ Object.defineProperty(self,'readyState',{value:4,configurable:true});+ Object.defineProperty(self,'status',{value:200,configurable:true});+ Object.defineProperty(self,'responseText',{value:'[]',configurable:true});+ if(self.onreadystatechange) self.onreadystatechange();+ if(self.onload) self.onload();+ return;+ }+ }catch(e){ log('xhr hook err '+e); }+ return os.apply(this, arguments);+ };+ log('hooks installed (doc-start)');+ })();+ """.trimIndent()++ /**+ * Runs after load: automate the composer to make the page build (and thus mint the token for)+ * the sendsms request. Sequence: open composer → fill recipient → fill message → click the real+ * "Send message" button (NOT the "Send new message" FAB). Dumps DOM to Logcat for tuning.+ */+ private fun automationScript(recipient: String, text: String): String {+ val num = recipient.replace("\"", "")+ val body = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n")+ return """+ (function(){+ function log(m){ try{ AndroidGV.log(""+m);}catch(e){} }+ var NUM="$num", TEXT="$body";+ function qa(s){ return Array.prototype.slice.call(document.querySelectorAll(s)); }+ function q(s){ return document.querySelector(s); }+ function lbl(e){ return (e.getAttribute('aria-label')||'').toLowerCase(); }+ function ph(e){ return (e.getAttribute('placeholder')||'').toLowerCase(); }+ function vis(e){ return !!(e && e.offsetParent!==null); }+ function fld(e){ return e.tagName+'|al='+lbl(e)+'|ph='+ph(e)+'|vis='+vis(e)+'|t='+((e.type||'').toLowerCase()); }+ function dumpFields(tag){ log(tag+' '+JSON.stringify(qa('input,textarea,[contenteditable="true"]').map(fld)).slice(0,1500)); }+ function byLabel(p){ p=p.toLowerCase(); return qa('[aria-label]').filter(function(e){return lbl(e).indexOf(p)>=0;}); }+ function labels(){ return qa('[aria-label]').map(function(e){return e.tagName+'#'+(e.getAttribute('aria-label')||'')+(e.getAttribute('aria-disabled')?('/dis='+e.getAttribute('aria-disabled')):'');}); }+ function setNative(el,val){ try{ var proto=el.tagName==='TEXTAREA'?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(proto,'value').set.call(el,val);}catch(e){ el.value=val; } el.dispatchEvent(new Event('input',{bubbles:true})); el.dispatchEvent(new Event('change',{bubbles:true})); }+ function type(el,val){ el.focus(); var ok=false; try{ ok=document.execCommand('insertText',false,val);}catch(e){} if(!ok){ if(el.tagName==='TEXTAREA'||el.tagName==='INPUT'){ setNative(el,val);} else { el.textContent=val; el.dispatchEvent(new InputEvent('input',{bubbles:true,data:val,inputType:'insertText'})); } } }+ function typeReal(el,val){ el.focus(); try{ el.value=''; }catch(e){} for(var i=0;i<val.length;i++){ var ch=val.charAt(i); el.dispatchEvent(new KeyboardEvent('keydown',{bubbles:true,key:ch})); try{ el.value=(el.value||'')+ch; }catch(e){} el.dispatchEvent(new InputEvent('input',{bubbles:true,data:ch,inputType:'insertText'})); el.dispatchEvent(new KeyboardEvent('keyup',{bubbles:true,key:ch})); } el.dispatchEvent(new Event('change',{bubbles:true})); }+ function enter(el){ ['keydown','keypress','keyup'].forEach(function(t){ el.dispatchEvent(new KeyboardEvent(t,{bubbles:true,key:'Enter',code:'Enter',keyCode:13,which:13})); }); }+ var B=document.body;+ var step=0;+ var timer=setInterval(function(){+ step++; if(step>70){ clearInterval(timer); log('giveup'); return; }+ try{+ if(step===1){ log('DUMP ta='+qa('textarea').length+' ce='+qa('[contenteditable="true"]').length+' in='+qa('input').length); log('DUMP '+JSON.stringify(labels()).slice(0,1600)); }++ // 1) Open the composer first. A label-less textarea on the inbox page is NOT the+ // message box, so gate everything on having clicked "Send new message".+ if(!B.dataset.gvOpen){+ var fab=byLabel('send new message')[0]||byLabel('new conversation')[0]||byLabel('start a conversation')[0];+ if(fab){ B.dataset.gvOpen='1'; B.dataset.gvOpenStep=String(step); log('open composer'); fab.click(); }+ else log('await fab '+step);+ return;+ }+ // Dump the composer DOM once shortly after opening.+ if(!B.dataset.gvDump2 && (step-(parseInt(B.dataset.gvOpenStep)||0))>=2){ B.dataset.gvDump2='1'; log('DUMP2 '+JSON.stringify(labels()).slice(0,1200)); dumpFields('FIELDS'); }++ // 2) Recipient input: prefer placeholder/label mentioning name/phone; exclude Search.+ function findRecip(){ var ins=qa('input,textarea').filter(vis); for(var i=0;i<ins.length;i++){ var s=lbl(ins[i])+' '+ph(ins[i]); if(s.indexOf('search')<0 && (s.indexOf('name')>=0||s.indexOf('phone')>=0||s.indexOf('recipient')>=0)) return ins[i]; } for(var j=0;j<ins.length;j++){ var t=(ins[j].type||'text').toLowerCase(); if((t==='text'||t==='tel') && (lbl(ins[j])+ph(ins[j])).indexOf('search')<0) return ins[j]; } return null; }+ // 3) Message box: a visible textarea/contenteditable, preferring message/text hints.+ function findMsg(){ var cs=qa('textarea,div[contenteditable="true"]').filter(vis); for(var i=0;i<cs.length;i++){ var s=lbl(cs[i])+' '+ph(cs[i]); if(s.indexOf('message')>=0||s.indexOf('text')>=0) return cs[i]; } return cs.length?cs[cs.length-1]:null; }+ var recip=findRecip();+ var msg=findMsg();+ // 4) Real send button: a BUTTON labelled exactly "Send message" (NOT the mat-label+ // "Select recipients to send a message to", and not "Send new message").+ function findSend(){ var bs=qa('button[aria-label]'); var best=null; for(var i=0;i<bs.length;i++){ var l=lbl(bs[i]); if(l.indexOf('new')>=0||l.indexOf('select')>=0) continue; if(l==='send message'||l==='send sms'||l==='send') return bs[i]; if(l.indexOf('send')>=0&&l.indexOf('message')>=0&&!best) best=bs[i]; } return best; }+ var send=findSend();++ if(recip && !B.dataset.gvRecip){ B.dataset.gvRecip='1'; log('fill recipient ['+fld(recip)+']');+ recip.focus(); var ok=false; try{ ok=document.execCommand('insertText',false,NUM);}catch(e){} if(!ok){ typeReal(recip,NUM); }+ var digits=NUM.replace(/[^0-9]/g,'');+ var tries=0; var st=setInterval(function(){ tries++;+ var opts=qa('[role="option"],mat-option,.mat-mdc-option,[role="listbox"] li,ul[role="listbox"] *');+ var textMatches=qa('div,span,li,button,a,[jsaction]').filter(function(e){ return e.children.length===0 && (e.textContent||'').replace(/[^0-9]/g,'').indexOf(digits)>=0; });+ if(tries%3===1){ log('SUG '+tries+' opt='+opts.length+' txt='+textMatches.length); }+ if(tries===2){ log('SUGDUMP '+JSON.stringify(opts.slice(0,6).map(function(e){return e.tagName+':'+(e.textContent||'').slice(0,24);})).slice(0,500)); log('TXTDUMP '+JSON.stringify(textMatches.slice(0,6).map(function(e){return e.tagName+':'+(e.textContent||'').slice(0,24);})).slice(0,500)); }+ var pick=opts[0]||textMatches[0];+ if(pick){ log('pick ['+pick.tagName+':'+(pick.textContent||'').slice(0,24)+']'); pick.click(); B.dataset.gvRecipDone='1'; clearInterval(st); }+ else if(tries>=18){ clearInterval(st); log('commit fallback (enter/comma/blur)'); recip.focus(); enter(recip);+ recip.dispatchEvent(new KeyboardEvent('keydown',{bubbles:true,key:',',keyCode:188,which:188}));+ recip.dispatchEvent(new KeyboardEvent('keyup',{bubbles:true,key:',',keyCode:188,which:188}));+ try{ recip.blur(); }catch(e){}+ B.dataset.gvRecipDone='1'; }+ }, 500);+ return;+ }+ if(!B.dataset.gvRecip){ log('await recip '+step); return; }+ if(!B.dataset.gvRecipDone){ log('await recip commit '+step); return; }+ // Fill the message once the recipient chip is committed.+ if(msg && !B.dataset.gvMsg){ B.dataset.gvMsg='1'; log('fill message ['+fld(msg)+']'); type(msg,TEXT); return; }+ if(!B.dataset.gvMsg){ if(step%4===0) dumpFields('FIELDS@'+step); log('await msg '+step); return; }+ if(send){ var dis=(send.getAttribute('aria-disabled')==='true'||send.disabled); if(!dis){ log('click SEND ['+lbl(send)+']'); send.click(); clearInterval(timer); log('sent-clicked'); return; } else { log('send disabled '+step+' recipVal='+((recip&&(recip.value||recip.textContent))||'')); return; } }+ log('await send '+step+' recip='+!!recip+' msg='+!!msg);+ }catch(e){ log('auto err '+e); }+ }, 800);+ })();+ """.trimIndent()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.ktnew file mode 100644index 0000000000..3f4fda5e14--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt@@ -0,0 +1,235 @@+package com.vayunmathur.communicate.data.googlevoice.call++import android.content.Context+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/** Coarse call lifecycle exposed to the UI + Telecom bridge. */+enum class CallPhase { Idle, Dialing, Ringing, Active, Incoming, Ended }++data class CallState(+ val phase: CallPhase = CallPhase.Idle,+ val remoteNumber: String = "",+ val muted: Boolean = false,+ val speaker: Boolean = false,+)++/** Implemented by the Telecom [android.telecom.Connection] so the manager can drive system UI. */+interface CallConnection {+ fun onCallActive()+ fun onCallEnded()+}++/**+ * Orchestrates a single Google Voice VoIP call: wires [SipClient] signaling to the+ * [WebRtcAudioSession] media leg and publishes a [CallState] flow. Also the entry point the+ * Telecom bridge and in-app call UI both talk to. Singleton because a call outlives any one+ * screen and the self-managed [android.telecom.Connection].+ *+ * See `voice-documentation.md` → "Voice Calling (SIP over WebSocket)". Phase 5 is expected to+ * need on-device iteration (SDP/codec/ICE + SIP auth specifics).+ */+object GoogleVoiceCallManager {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ private val _state = MutableStateFlow(CallState())+ val state: StateFlow<CallState> = _state.asStateFlow()++ private var appContext: Context? = null+ private var audio: WebRtcAudioSession? = null+ private var sip: SipClient? = null+ private var gvNumber: String = ""+ private var remoteNumber: String = ""+ private var registered = false+ private var remoteApplied = false+ private var pendingInviteTarget: String? = null+ private var pendingInviteSdp: String? = null++ /** Set by the Telecom bridge so SIP-driven transitions reflect into system call UI. */+ var connection: CallConnection? = null++ /** Set by the registration service to surface inbound INVITEs to Telecom. */+ var onIncomingCall: ((from: String) -> Unit)? = null++ fun init(context: Context) {+ if (appContext == null) appContext = context.applicationContext+ }++ fun placeCall(number: String) {+ val ctx = appContext ?: return+ remoteNumber = number+ _state.value = CallState(phase = CallPhase.Dialing, remoteNumber = number)+ scope.launch {+ runCatching {+ val session = GoogleVoiceSession.get(ctx)+ val info = GoogleVoiceClient.get(ctx).getSipRegisterInfo()+ gvNumber = session.phoneNumber() ?: info.phoneNumber.orEmpty()+ val a = WebRtcAudioSession(ctx).also { it.initialize() }+ audio = a+ val offer = a.createOffer()+ pendingInviteTarget = number+ pendingInviteSdp = offer+ val s = SipClient(info, gvNumber, scope, sipListener())+ sip = s+ s.connect()+ s.register()+ }.onFailure {+ android.util.Log.e("GoogleVoiceCall", "placeCall setup failed", it)+ fail(it.message ?: "call setup failed")+ }+ }+ }++ /** Connect + register without placing a call, so inbound INVITEs can arrive. */+ fun startRegistration() {+ val ctx = appContext ?: return+ if (sip != null) return+ scope.launch {+ runCatching {+ val session = GoogleVoiceSession.get(ctx)+ val info = GoogleVoiceClient.get(ctx).getSipRegisterInfo()+ gvNumber = session.phoneNumber() ?: info.phoneNumber.orEmpty()+ val s = SipClient(info, gvNumber, scope, sipListener())+ sip = s+ s.connect()+ s.register()+ }.onFailure { fail(it.message ?: "registration failed") }+ }+ }++ fun answer() {+ val ctx = appContext ?: return+ scope.launch {+ runCatching {+ val a = audio ?: WebRtcAudioSession(ctx).also { it.initialize(); audio = it }+ val offer = pendingInviteSdp ?: return@launch+ val answerSdp = a.createAnswer(offer)+ sip?.answerInbound(answerSdp)+ setActive()+ }.onFailure { fail(it.message ?: "answer failed") }+ }+ }++ fun reject() {+ scope.launch {+ runCatching { sip?.declineInbound() }+ endCall()+ }+ }++ fun hangup() {+ scope.launch {+ runCatching { sip?.bye(remoteNumber) }+ endCall()+ }+ }++ fun sendDtmf(digit: String) {+ audio?.sendDtmf(digit)+ }++ fun setMuted(muted: Boolean) {+ audio?.setMuted(muted)+ _state.value = _state.value.copy(muted = muted)+ }++ fun setSpeaker(on: Boolean) {+ audio?.setSpeaker(on)+ _state.value = _state.value.copy(speaker = on)+ }++ // ------------------------------------------------------------------++ private fun sipListener() = object : SipClient.Listener {+ override fun onRegistered() {+ registered = true+ val target = pendingInviteTarget+ val sdp = pendingInviteSdp+ if (target != null && sdp != null) {+ scope.launch { runCatching { sip?.invite(target, sdp) } }+ }+ }++ override fun onProvisional(code: Int) {+ if (code == 180 || code == 183) {+ _state.value = _state.value.copy(phase = CallPhase.Ringing)+ }+ }++ override fun onEarlyMedia(remoteSdp: String) {+ // Apply the answer as soon as it arrives (183) so ICE/DTLS + audio can start during+ // ringback; the final 200 just confirms + ACKs.+ scope.launch { runCatching { applyRemote(remoteSdp) } }+ }++ override fun onAnswered(remoteSdp: String) {+ scope.launch {+ runCatching {+ applyRemote(remoteSdp)+ sip?.ack(remoteNumber)+ setActive()+ }.onFailure { fail(it.message ?: "media negotiation failed") }+ }+ }++ override fun onEnded() = endCall()++ override fun onFailed(reason: String) = fail(reason)++ override fun onIncomingInvite(remoteSdp: String, from: String) {+ remoteNumber = from+ pendingInviteSdp = remoteSdp+ _state.value = CallState(phase = CallPhase.Incoming, remoteNumber = from)+ onIncomingCall?.invoke(from)+ }+ }++ private fun setActive() {+ _state.value = _state.value.copy(phase = CallPhase.Active)+ connection?.onCallActive()+ }++ /** Apply the remote SDP answer to the WebRTC session exactly once (183 or 200). */+ private suspend fun applyRemote(sdp: String) {+ if (remoteApplied) return+ remoteApplied = true+ audio?.setRemoteAnswer(sdp)+ }++ private fun endCall() {+ cleanup()+ _state.value = CallState(phase = CallPhase.Ended, remoteNumber = remoteNumber)+ connection?.onCallEnded()+ }++ private fun fail(reason: String) {+ android.util.Log.e("GoogleVoiceCall", "call failed: $reason")+ cleanup()+ _state.value = CallState(phase = CallPhase.Ended, remoteNumber = remoteNumber)+ connection?.onCallEnded()+ }++ private fun cleanup() {+ runCatching { sip?.close() }+ runCatching { audio?.close() }+ sip = null+ audio = null+ registered = false+ remoteApplied = false+ pendingInviteTarget = null+ pendingInviteSdp = null+ }++ /** Reset to Idle once the UI has consumed a terminal state. */+ fun clearEnded() {+ if (_state.value.phase == CallPhase.Ended) _state.value = CallState()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.ktnew file mode 100644index 0000000000..5a6cc88527--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt@@ -0,0 +1,356 @@+package com.vayunmathur.communicate.data.googlevoice.call++import android.util.Log+import com.vayunmathur.communicate.data.googlevoice.GvSipRegisterInfo+import com.vayunmathur.library.network.WebSocketClient+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import java.util.UUID+import kotlin.random.Random++/**+ * Minimal SIP-over-WebSocket client for Google Voice web calling.+ *+ * Google Voice web calls run SIP over `wss://web.voice.telephony.goog/websocket` with+ * DTLS-SRTP WebRTC media (see `voice-documentation.md` → "Voice Calling (SIP over WebSocket)").+ * Outbound frames are readable SIP text; the registrar is `*.pbx.voice.sip.google.com`.+ *+ * This implements the observed lifecycle:+ * ```+ * REGISTER -> 200+ * Outbound: INVITE(SDP offer) -> 100/180/183 -> PRACK -> 200 OK(SDP) -> ACK -> media -> BYE+ * Inbound: INVITE(recv) -> 180 Ringing -> 200 OK(answer) / 603 Decline / 487+ * ```+ *+ * ⚠️ The exact SIP auth (digest realm/credentials mapping) and some header specifics were not+ * recoverable from the HAR (inbound frames were binary/compressed). This is a structurally+ * complete best-effort that will need on-device iteration — the plan flags Phase 5 as the most+ * likely to need tuning. Transport uses the repo's [WebSocketClient] (no OkHttp).+ */+class SipClient(+ private val registerInfo: GvSipRegisterInfo,+ private val gvNumber: String,+ private val scope: CoroutineScope,+ private val listener: Listener,+) {+ interface Listener {+ fun onRegistered()+ fun onProvisional(code: Int)+ /** Remote answer SDP for our outbound INVITE. */+ fun onAnswered(remoteSdp: String)+ /** Early-media SDP delivered in a reliable provisional (183) before the final 200. */+ fun onEarlyMedia(remoteSdp: String)+ fun onEnded()+ fun onFailed(reason: String)+ /** Inbound INVITE: remote offer SDP + caller number. */+ fun onIncomingInvite(remoteSdp: String, from: String)+ }++ private var socket: WebSocketClient? = null+ private var readJob: Job? = null++ private val localHost = "${randomToken(12)}.invalid"+ private val callId = UUID.randomUUID().toString()+ private val fromTag = randomToken(8)+ private var toTag: String? = null+ private var cseq = 1+ private var lastInviteSdp: String? = null+ private var inviteTarget: String? = null+ private var inviteCseq = 0+ private var remoteContact: String? = null+ private var routeSet: List<String> = emptyList()+ private var lastExpires = 3600+ private var registerRetried = false+ private var authRetried = false++ // The SIP AOR/username is credential[0]; the digest password is credential[1] (from+ // sipregisterinfo/get). The AOR user is credential[0] URL-encoded ("=" -> "%3D").+ private val authUsername = registerInfo.credentials.getOrNull(0) ?: gvNumber+ private val authPassword = registerInfo.credentials.getOrNull(1) ?: ""+ private val aorUser = authUsername.replace("=", "%3D")+ private val contactUser = randomToken(8)++ suspend fun connect() {+ socket = WebSocketClient.connect(+ urlStr = WS_URL,+ headers = mapOf(+ "Sec-WebSocket-Protocol" to "sip",+ "Origin" to "https://voice.google.com",+ ),+ )+ readJob = scope.launch(Dispatchers.IO) {+ val s = socket ?: return@launch+ s.incomingFlow().collect { frame ->+ val text = when (frame) {+ is WebSocketClient.WsFrame.Text -> frame.text+ // Inbound frames were binary/compressed in the HAR; try a UTF-8 view.+ is WebSocketClient.WsFrame.Binary -> runCatching { frame.bytes.toString(Charsets.UTF_8) }.getOrNull()+ is WebSocketClient.WsFrame.Close -> { listener.onEnded(); null }+ else -> null+ }+ if (!text.isNullOrBlank()) handleIncoming(text)+ }+ }+ }++ suspend fun register(expires: Int = 3600, authHeader: String? = null) {+ lastExpires = expires+ val msg = buildRequest(+ method = "REGISTER",+ requestUri = "sip:$SIP_DOMAIN",+ to = fromUri(),+ extraHeaders = listOfNotNull(+ "Expires: $expires",+ authHeader?.let { "Authorization: $it" },+ ),+ )+ send(msg)+ }++ /** Place an outbound call with the given ICE-complete SDP offer. */+ suspend fun invite(target: String, sdpOffer: String) {+ lastInviteSdp = sdpOffer+ inviteTarget = target+ val msg = buildRequest(+ method = "INVITE",+ requestUri = "sip:$target@$SIP_DOMAIN",+ to = "<sip:$target@$SIP_DOMAIN>",+ body = sdpOffer,+ contentType = "application/sdp",+ )+ inviteCseq = cseq+ send(msg)+ }++ /** Acknowledge a reliable provisional response (100rel) so the call can proceed. */+ private suspend fun prack(target: String, rseq: Int) {+ val msg = buildRequest(+ method = "PRACK",+ requestUri = "sip:$target@$SIP_DOMAIN",+ to = "<sip:$target@$SIP_DOMAIN>${toTag?.let { ";tag=$it" } ?: ""}",+ extraHeaders = listOf("RAck: $rseq $inviteCseq INVITE"),+ )+ send(msg)+ }++ suspend fun ack(target: String) {+ // In-dialog: send to the remote Contact with the route set, reusing the INVITE CSeq.+ val uri = remoteContact ?: "sip:$target@$SIP_DOMAIN"+ val msg = buildRequest(+ method = "ACK",+ requestUri = uri,+ to = "<sip:$target@$SIP_DOMAIN>${toTag?.let { ";tag=$it" } ?: ""}",+ extraHeaders = routeSet.map { "Route: $it" },+ cseqOverride = inviteCseq,+ )+ send(msg)+ }++ suspend fun bye(target: String) {+ // Must target the remote Contact URI and carry the dialog route set, or Google can't+ // match the dialog and the far leg never hangs up.+ val uri = remoteContact ?: "sip:$target@$SIP_DOMAIN"+ val msg = buildRequest(+ method = "BYE",+ requestUri = uri,+ to = "<sip:$target@$SIP_DOMAIN>${toTag?.let { ";tag=$it" } ?: ""}",+ extraHeaders = routeSet.map { "Route: $it" },+ )+ send(msg)+ }++ /** Answer an inbound INVITE with our answer SDP (200 OK). */+ suspend fun answerInbound(answerSdp: String) {+ // Best-effort: echo a 200 OK for the pending inbound INVITE.+ val response = buildString {+ append("SIP/2.0 200 OK\r\n")+ append("Content-Type: application/sdp\r\n")+ append("Content-Length: ${answerSdp.toByteArray().size}\r\n")+ append("\r\n")+ append(answerSdp)+ }+ send(response)+ }++ /** Decline an inbound INVITE (603). */+ suspend fun declineInbound() {+ send("SIP/2.0 603 Decline\r\nContent-Length: 0\r\n\r\n")+ }++ fun close() {+ readJob?.cancel()+ scope.launch { runCatching { socket?.close() } }+ }++ // ------------------------------------------------------------------++ private suspend fun send(message: String) {+ Log.d(TAG, "SIP >>\n$message")+ socket?.send(message)+ }++ private fun handleIncoming(message: String) {+ Log.d(TAG, "SIP <<\n$message")+ val firstLine = message.lineSequence().firstOrNull()?.trim().orEmpty()+ val headers = parseHeaders(message)+ headers["to"]?.let { extractTag(it)?.let { t -> toTag = t } }+ val body = message.substringAfter("\r\n\r\n", "").ifBlank { message.substringAfter("\n\n", "") }++ // Capture the dialog remote target + route set from INVITE responses (183/200), needed+ // so in-dialog ACK/BYE route correctly and actually tear the call down.+ val cseqHeaderTop = headers["cseq"].orEmpty()+ val codeTop = if (firstLine.startsWith("SIP/2.0")) firstLine.split(' ').getOrNull(1)?.toIntOrNull() ?: 0 else -1+ if (cseqHeaderTop.contains("INVITE", true) && codeTop in 180..299) {+ if (remoteContact == null) extractContact(message)?.let { remoteContact = it }+ if (routeSet.isEmpty()) {+ val rr = extractRecordRoutes(message)+ if (rr.isNotEmpty()) routeSet = rr.reversed()+ }+ }++ when {+ firstLine.startsWith("SIP/2.0") -> {+ val code = firstLine.split(' ').getOrNull(1)?.toIntOrNull() ?: 0+ val cseqHeader = headers["cseq"].orEmpty()+ when {+ // Registrar wants a longer registration interval; retry once at Min-Expires.+ code == 423 && cseqHeader.contains("REGISTER", true) && !registerRetried -> {+ registerRetried = true+ val min = headers["min-expires"]?.toIntOrNull() ?: (lastExpires * 2)+ scope.launch { runCatching { register(min) } }+ }+ // Digest challenge: compute the response and re-REGISTER with Authorization.+ (code == 401 || code == 407) && cseqHeader.contains("REGISTER", true) && !authRetried -> {+ authRetried = true+ val challenge = headers["www-authenticate"] ?: headers["proxy-authenticate"] ?: ""+ val nonce = extractParam(challenge, "nonce") ?: ""+ val realm = extractParam(challenge, "realm") ?: SIP_DOMAIN+ val auth = digestAuth("REGISTER", "sip:$SIP_DOMAIN", nonce, realm)+ scope.launch { runCatching { register(lastExpires, auth) } }+ }+ code == 200 && cseqHeader.contains("REGISTER", true) -> listener.onRegistered()+ code == 200 && cseqHeader.contains("INVITE", true) -> listener.onAnswered(body)+ code in 100..199 -> {+ listener.onProvisional(code)+ // Reliable provisional (100rel) carries the SDP answer + RSeq; apply the+ // early media and PRACK it, or the registrar drops the call with 504.+ if (body.contains("m=", ignoreCase = true)) listener.onEarlyMedia(body)+ val rseq = headers["rseq"]?.toIntOrNull()+ val tgt = inviteTarget+ if (rseq != null && tgt != null) {+ scope.launch { runCatching { prack(tgt, rseq) } }+ }+ }+ code == 487 || code == 603 || code == 486 -> listener.onEnded()+ code in 400..699 -> listener.onFailed("SIP $firstLine")+ }+ }+ firstLine.startsWith("INVITE", true) -> {+ val from = headers["from"]?.let { extractUserFromHeader(it) } ?: "Unknown"+ listener.onIncomingInvite(body, from)+ }+ firstLine.startsWith("BYE", true) -> listener.onEnded()+ }+ }++ private fun buildRequest(+ method: String,+ requestUri: String,+ to: String,+ body: String? = null,+ contentType: String? = null,+ extraHeaders: List<String> = emptyList(),+ incrementCseq: Boolean = true,+ cseqOverride: Int? = null,+ ): String {+ val seq = cseqOverride ?: if (incrementCseq) ++cseq else cseq+ val branch = "z9hG4bK${randomToken(16)}"+ val bodyBytes = body?.toByteArray()?.size ?: 0+ return buildString {+ append("$method $requestUri SIP/2.0\r\n")+ append("Via: SIP/2.0/wss $localHost;branch=$branch\r\n")+ append("Max-Forwards: 70\r\n")+ append("From: ${fromUri()};tag=$fromTag\r\n")+ append("To: $to\r\n")+ append("Call-ID: $callId\r\n")+ append("CSeq: $seq $method\r\n")+ append("Contact: <sip:$contactUser@$localHost;transport=wss>;+sip.ice;reg-id=1\r\n")+ append("Supported: 100rel,ice,replaces,outbound,timer\r\n")+ append("Allow: INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,PRACK\r\n")+ append("User-Agent: Communicate GoogleVoice\r\n")+ extraHeaders.forEach { append("$it\r\n") }+ if (contentType != null) append("Content-Type: $contentType\r\n")+ append("Content-Length: $bodyBytes\r\n")+ append("\r\n")+ if (body != null) append(body)+ }+ }++ /** The remote target URI from a response's Contact header (used for in-dialog ACK/BYE). */+ private fun extractContact(message: String): String? {+ val line = message.lineSequence().firstOrNull { it.trim().startsWith("Contact:", true) } ?: return null+ return Regex("<([^>]+)>").find(line)?.groupValues?.getOrNull(1)+ ?: line.substringAfter(":").trim().ifBlank { null }+ }++ /** All Record-Route URIs (in order) from a response; the dialog route set is their reverse. */+ private fun extractRecordRoutes(message: String): List<String> =+ message.lineSequence()+ .filter { it.trim().startsWith("Record-Route:", true) }+ .mapNotNull { Regex("<([^>]+)>").find(it)?.groupValues?.getOrNull(1)?.let { u -> "<$u>" } }+ .toList()++ private fun fromUri() = "<sip:$aorUser@$SIP_DOMAIN>"++ private fun parseHeaders(message: String): Map<String, String> {+ val out = mutableMapOf<String, String>()+ for (line in message.lineSequence()) {+ val trimmed = line.trimEnd()+ if (trimmed.isEmpty()) break+ val idx = trimmed.indexOf(':')+ if (idx > 0) {+ out[trimmed.substring(0, idx).trim().lowercase()] = trimmed.substring(idx + 1).trim()+ }+ }+ return out+ }++ private fun extractTag(headerValue: String): String? =+ Regex(";tag=([^;\\s]+)").find(headerValue)?.groupValues?.getOrNull(1)++ /** Extract a quoted or bare param (e.g. nonce, realm) from a WWW-Authenticate header. */+ private fun extractParam(header: String, name: String): String? =+ Regex("$name=\"([^\"]*)\"").find(header)?.groupValues?.getOrNull(1)+ ?: Regex("$name=([^,\\s]+)").find(header)?.groupValues?.getOrNull(1)++ /** RFC 2069-style MD5 SIP digest (no qop), matching Google's registrar challenge. */+ private fun digestAuth(method: String, uri: String, nonce: String, realm: String): String {+ val ha1 = md5("$authUsername:$realm:$authPassword")+ val ha2 = md5("$method:$uri")+ val response = md5("$ha1:$nonce:$ha2")+ return "Digest algorithm=MD5, username=\"$authUsername\", realm=\"$realm\", " ++ "nonce=\"$nonce\", uri=\"$uri\", response=\"$response\""+ }++ private fun md5(input: String): String {+ val bytes = java.security.MessageDigest.getInstance("MD5").digest(input.toByteArray(Charsets.UTF_8))+ return bytes.joinToString("") { "%02x".format(it) }+ }++ private fun extractUserFromHeader(headerValue: String): String? =+ Regex("sip:([^@>;\\s]+)@").find(headerValue)?.groupValues?.getOrNull(1)++ private fun randomToken(len: Int): String {+ val chars = "abcdefghijklmnopqrstuvwxyz0123456789"+ return (1..len).map { chars[Random.nextInt(chars.length)] }.joinToString("")+ }++ companion object {+ private const val TAG = "SipClient"+ private const val WS_URL = "wss://web.voice.telephony.goog/websocket"+ // Registrar/domain observed in capture 2 (User-Agent: GoogleVoice; PBX host).+ private const val SIP_DOMAIN = "web.c.pbx.voice.sip.google.com"+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/WebRtcAudioSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/WebRtcAudioSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/WebRtcAudioSession.ktnew file mode 100644index 0000000000..72ea08e7bc--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/WebRtcAudioSession.kt@@ -0,0 +1,214 @@+package com.vayunmathur.communicate.data.googlevoice.call++import android.content.Context+import android.media.AudioManager+import org.webrtc.AudioSource+import org.webrtc.AudioTrack+import org.webrtc.DefaultVideoDecoderFactory+import org.webrtc.DefaultVideoEncoderFactory+import org.webrtc.DtmfSender+import org.webrtc.EglBase+import org.webrtc.IceCandidate+import org.webrtc.MediaConstraints+import org.webrtc.MediaStream+import org.webrtc.PeerConnection+import org.webrtc.PeerConnectionFactory+import org.webrtc.RtpReceiver+import org.webrtc.RtpSender+import org.webrtc.SdpObserver+import org.webrtc.SessionDescription+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlin.coroutines.suspendCoroutine+import kotlinx.coroutines.CompletableDeferred++/**+ * WebRTC audio leg of a Google Voice call.+ *+ * Wraps a single [PeerConnection] carrying one Opus audio m-line (with PCMU/PCMA/G722/CN and+ * RFC 4733 `telephone-event` offered too, matching the SDP observed in `voice-documentation.md`+ * → "Media (WebRTC / SDP)"). SDP is exchanged as full offers/answers over SIP, so we gather+ * ICE fully before handing the SDP back (non-trickle) to keep the SIP body self-contained.+ *+ * Exposes mute (sender track enabled), speaker routing (AudioManager), and DTMF via the+ * audio [RtpSender]'s [DtmfSender] (`insertDtmf`). Uses the maintained+ * `io.getstream:stream-webrtc-android` prebuilt (`org.webrtc.*`).+ */+class WebRtcAudioSession(private val appContext: Context) {++ private val eglBase: EglBase = EglBase.create()+ private var factory: PeerConnectionFactory? = null+ private var peerConnection: PeerConnection? = null+ private var audioSource: AudioSource? = null+ private var localAudioTrack: AudioTrack? = null+ private var audioSender: RtpSender? = null++ private val iceComplete = CompletableDeferred<Unit>()++ fun initialize() {+ PeerConnectionFactory.initialize(+ PeerConnectionFactory.InitializationOptions.builder(appContext)+ .setEnableInternalTracer(false)+ .createInitializationOptions(),+ )+ val encoder = DefaultVideoEncoderFactory(eglBase.eglBaseContext, true, true)+ val decoder = DefaultVideoDecoderFactory(eglBase.eglBaseContext)+ factory = PeerConnectionFactory.builder()+ .setVideoEncoderFactory(encoder)+ .setVideoDecoderFactory(decoder)+ .createPeerConnectionFactory()+ }++ private fun ensurePeerConnection() {+ if (peerConnection != null) return+ val f = factory ?: error("initialize() not called")+ val iceServers = listOf(+ PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer(),+ )+ val config = PeerConnection.RTCConfiguration(iceServers).apply {+ sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN+ bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE+ rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE+ continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_ONCE+ }+ peerConnection = f.createPeerConnection(config, object : PeerConnection.Observer {+ override fun onIceCandidate(candidate: IceCandidate?) {}+ override fun onIceGatheringChange(state: PeerConnection.IceGatheringState?) {+ if (state == PeerConnection.IceGatheringState.COMPLETE && !iceComplete.isCompleted) {+ iceComplete.complete(Unit)+ }+ }+ override fun onSignalingChange(p0: PeerConnection.SignalingState?) {}+ override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) {}+ override fun onIceConnectionReceivingChange(p0: Boolean) {}+ override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) {}+ override fun onAddStream(p0: MediaStream?) {}+ override fun onRemoveStream(p0: MediaStream?) {}+ override fun onDataChannel(p0: org.webrtc.DataChannel?) {}+ override fun onRenegotiationNeeded() {}+ override fun onAddTrack(p0: RtpReceiver?, p1: Array<out MediaStream>?) {}+ })+ addLocalAudio(f)+ }++ private fun addLocalAudio(f: PeerConnectionFactory) {+ val constraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("googEchoCancellation", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("googAutoGainControl", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("googNoiseSuppression", "true"))+ }+ val source = f.createAudioSource(constraints)+ val track = f.createAudioTrack("gv_audio", source)+ audioSource = source+ localAudioTrack = track+ audioSender = peerConnection?.addTrack(track, listOf("gv_stream"))+ }++ /** Create an SDP offer, set it locally, wait for ICE, and return the final SDP. */+ suspend fun createOffer(): String {+ ensurePeerConnection()+ val pc = peerConnection ?: error("no peer connection")+ val constraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"))+ }+ val offer = pc.createOfferSuspend(constraints)+ pc.setLocalDescriptionSuspend(offer)+ iceComplete.await()+ return pc.localDescription?.description ?: offer.description+ }++ /** Apply the remote answer SDP received in the SIP 200 OK. */+ suspend fun setRemoteAnswer(sdp: String) {+ val pc = peerConnection ?: error("no peer connection")+ pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.ANSWER, sdp))+ }++ /** For an inbound call: apply the remote offer, create + set an answer, return answer SDP. */+ suspend fun createAnswer(remoteOfferSdp: String): String {+ ensurePeerConnection()+ val pc = peerConnection ?: error("no peer connection")+ pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.OFFER, remoteOfferSdp))+ val constraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"))+ }+ val answer = pc.createAnswerSuspend(constraints)+ pc.setLocalDescriptionSuspend(answer)+ iceComplete.await()+ return pc.localDescription?.description ?: answer.description+ }++ fun setMuted(muted: Boolean) {+ localAudioTrack?.setEnabled(!muted)+ }++ fun setSpeaker(on: Boolean) {+ val am = appContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager+ @Suppress("DEPRECATION")+ am.isSpeakerphoneOn = on+ }++ fun sendDtmf(digits: String) {+ val sender = audioSender ?: return+ val dtmf: DtmfSender = sender.dtmf() ?: return+ // 100ms tone, 70ms gap — standard RFC 4733 timing.+ dtmf.insertDtmf(digits, 100, 70)+ }++ fun close() {+ runCatching { peerConnection?.dispose() }+ runCatching { audioSource?.dispose() }+ runCatching { factory?.dispose() }+ runCatching { eglBase.release() }+ peerConnection = null+ audioSource = null+ localAudioTrack = null+ audioSender = null+ }++ // ---- SdpObserver → coroutine adapters ----++ private suspend fun PeerConnection.createOfferSuspend(c: MediaConstraints): SessionDescription =+ suspendCoroutine { cont ->+ createOffer(object : SimpleSdpObserver() {+ override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)+ override fun onCreateFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("createOffer: $error"))+ }, c)+ }++ private suspend fun PeerConnection.createAnswerSuspend(c: MediaConstraints): SessionDescription =+ suspendCoroutine { cont ->+ createAnswer(object : SimpleSdpObserver() {+ override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)+ override fun onCreateFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("createAnswer: $error"))+ }, c)+ }++ private suspend fun PeerConnection.setLocalDescriptionSuspend(desc: SessionDescription) =+ suspendCoroutine<Unit> { cont ->+ setLocalDescription(object : SimpleSdpObserver() {+ override fun onSetSuccess() = cont.resume(Unit)+ override fun onSetFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("setLocal: $error"))+ }, desc)+ }++ private suspend fun PeerConnection.setRemoteDescriptionSuspend(desc: SessionDescription) =+ suspendCoroutine<Unit> { cont ->+ setRemoteDescription(object : SimpleSdpObserver() {+ override fun onSetSuccess() = cont.resume(Unit)+ override fun onSetFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("setRemote: $error"))+ }, desc)+ }+}++private open class SimpleSdpObserver : SdpObserver {+ override fun onCreateSuccess(desc: SessionDescription) {}+ override fun onSetSuccess() {}+ override fun onCreateFailure(error: String?) {}+ override fun onSetFailure(error: String?) {}+}
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.ktnew file mode 100644index 0000000000..48946dce58--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt@@ -0,0 +1,92 @@+package com.vayunmathur.communicate.telephony++import android.app.Notification+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import androidx.core.content.ContextCompat+import com.vayunmathur.communicate.MainActivity+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.googlevoice.call.CallPhase+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Foreground service (type `phoneCall`) that keeps a Google Voice call — its SIP socket, mic+ * capture, and audio focus — alive while off-screen, showing the ongoing-call notification.+ * Started by [GoogleVoiceConnectionService] and self-stops when the call reaches a terminal+ * state.+ */+class GoogleVoiceCallForegroundService : Service() {++ private val scope = CoroutineScope(SupervisorJob())+ private var observeJob: Job? = null++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ startForegroundWithNotification()+ observeJob?.cancel()+ observeJob = scope.launch {+ GoogleVoiceCallManager.state.collect { state ->+ when (state.phase) {+ CallPhase.Idle, CallPhase.Ended -> stopSelfSafely()+ else -> startForegroundWithNotification()+ }+ }+ }+ return START_STICKY+ }++ private fun startForegroundWithNotification() {+ ensureNotificationChannel(CHANNEL_ID, getString(R.string.gv_call_channel_name))+ val contentIntent = PendingIntent.getActivity(+ this, 0, Intent(this, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val notification: Notification = Notification.Builder(this, CHANNEL_ID)+ .setContentTitle(getString(R.string.gv_ongoing_call))+ .setContentText(GoogleVoiceCallManager.state.value.remoteNumber)+ .setSmallIcon(android.R.drawable.sym_action_call)+ .setOngoing(true)+ .setContentIntent(contentIntent)+ .build()++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)+ } else {+ startForeground(NOTIFICATION_ID, notification)+ }+ }++ private fun stopSelfSafely() {+ androidx.core.app.ServiceCompat.stopForeground(+ this, androidx.core.app.ServiceCompat.STOP_FOREGROUND_REMOVE,+ )+ stopSelf()+ }++ override fun onDestroy() {+ observeJob?.cancel()+ super.onDestroy()+ }++ companion object {+ private const val CHANNEL_ID = "gv_calls"+ private const val NOTIFICATION_ID = 4711++ fun start(context: Context) {+ ContextCompat.startForegroundService(+ context, Intent(context, GoogleVoiceCallForegroundService::class.java),+ )+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.ktnew file mode 100644index 0000000000..263319ae8f--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnection.kt@@ -0,0 +1,61 @@+package com.vayunmathur.communicate.telephony++import android.telecom.Connection+import android.telecom.DisconnectCause+import com.vayunmathur.communicate.data.googlevoice.call.CallConnection+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager++/**+ * The Telecom [Connection] representing one Google Voice call. Bridges system call actions+ * (answer/reject/hangup/DTMF) to [GoogleVoiceCallManager], and reflects SIP/WebRTC state back+ * into the system via [CallConnection].+ */+class GoogleVoiceConnection : Connection(), CallConnection {++ init {+ audioModeIsVoip = true+ connectionCapabilities = connectionCapabilities or+ CAPABILITY_MUTE or CAPABILITY_SUPPORT_HOLD+ }++ override fun onAnswer() {+ GoogleVoiceCallManager.answer()+ }++ override fun onReject() {+ GoogleVoiceCallManager.reject()+ setDisconnected(DisconnectCause(DisconnectCause.REJECTED))+ destroy()+ }++ override fun onDisconnect() {+ GoogleVoiceCallManager.hangup()+ setDisconnected(DisconnectCause(DisconnectCause.LOCAL))+ destroy()+ }++ override fun onAbort() {+ GoogleVoiceCallManager.hangup()+ setDisconnected(DisconnectCause(DisconnectCause.CANCELED))+ destroy()+ }++ override fun onPlayDtmfTone(c: Char) {+ GoogleVoiceCallManager.sendDtmf(c.toString())+ }++ override fun onStateChanged(state: Int) {+ super.onStateChanged(state)+ }++ // ---- CallConnection (driven by GoogleVoiceCallManager) ----++ override fun onCallActive() {+ setActive()+ }++ override fun onCallEnded() {+ setDisconnected(DisconnectCause(DisconnectCause.REMOTE))+ destroy()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.ktnew file mode 100644index 0000000000..ed87e0171e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt@@ -0,0 +1,57 @@+package com.vayunmathur.communicate.telephony++import android.net.Uri+import android.telecom.Connection+import android.telecom.ConnectionRequest+import android.telecom.ConnectionService+import android.telecom.PhoneAccountHandle+import android.telecom.TelecomManager+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager++/**+ * Self-managed [ConnectionService] that makes Google Voice behave like a second line. Outgoing+ * calls placed via [GoogleVoiceTelecom.placeOutgoing] and inbound calls surfaced via+ * [GoogleVoiceTelecom.addIncoming] both land here and are wired to [GoogleVoiceCallManager].+ */+class GoogleVoiceConnectionService : ConnectionService() {++ override fun onCreateOutgoingConnection(+ connectionManagerPhoneAccount: PhoneAccountHandle?,+ request: ConnectionRequest?,+ ): Connection {+ GoogleVoiceCallManager.init(applicationContext)+ val number = request?.address?.schemeSpecificPart.orEmpty()+ val connection = GoogleVoiceConnection().apply {+ setAddress(request?.address ?: Uri.fromParts("tel", number, null), TelecomManager.PRESENTATION_ALLOWED)+ setDialing()+ connectionProperties = connectionProperties or Connection.PROPERTY_SELF_MANAGED+ }+ GoogleVoiceCallManager.connection = connection+ GoogleVoiceCallManager.placeCall(number)+ GoogleVoiceCallForegroundService.start(applicationContext)+ return connection+ }++ override fun onCreateIncomingConnection(+ connectionManagerPhoneAccount: PhoneAccountHandle?,+ request: ConnectionRequest?,+ ): Connection {+ GoogleVoiceCallManager.init(applicationContext)+ val address = request?.extras?.getParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS) as? Uri+ val connection = GoogleVoiceConnection().apply {+ if (address != null) setAddress(address, TelecomManager.PRESENTATION_ALLOWED)+ setRinging()+ connectionProperties = connectionProperties or Connection.PROPERTY_SELF_MANAGED+ }+ GoogleVoiceCallManager.connection = connection+ GoogleVoiceCallForegroundService.start(applicationContext)+ return connection+ }++ override fun onCreateOutgoingConnectionFailed(+ connectionManagerPhoneAccount: PhoneAccountHandle?,+ request: ConnectionRequest?,+ ) {+ GoogleVoiceCallManager.hangup()+ }+}
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.ktnew file mode 100644index 0000000000..bcafc9410a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceTelecom.kt@@ -0,0 +1,63 @@+package com.vayunmathur.communicate.telephony++import android.content.ComponentName+import android.content.Context+import android.net.Uri+import android.os.Bundle+import android.telecom.PhoneAccount+import android.telecom.PhoneAccountHandle+import android.telecom.TelecomManager++/**+ * Registers Google Voice as a **self-managed** [PhoneAccount] so the OS treats it like another+ * SIM/line: it becomes selectable for outgoing calls and gets system call-audio focus and,+ * for inbound, the incoming-call surface — all routed to [GoogleVoiceConnectionService].+ */+object GoogleVoiceTelecom {++ private const val ACCOUNT_ID = "google_voice_line"++ fun handle(context: Context): PhoneAccountHandle =+ PhoneAccountHandle(+ ComponentName(context.applicationContext, GoogleVoiceConnectionService::class.java),+ ACCOUNT_ID,+ )++ /** Register (or refresh) the self-managed account, labelled with the GV number. */+ fun registerPhoneAccount(context: Context, label: String) {+ val tm = context.getSystemService(TelecomManager::class.java) ?: return+ val account = PhoneAccount.builder(handle(context), label)+ .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)+ .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)+ .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)+ .build()+ runCatching { tm.registerPhoneAccount(account) }+ }++ fun unregisterPhoneAccount(context: Context) {+ val tm = context.getSystemService(TelecomManager::class.java) ?: return+ runCatching { tm.unregisterPhoneAccount(handle(context)) }+ }++ /** Place an outgoing GV call through Telecom so it routes to our ConnectionService. */+ fun placeOutgoing(context: Context, number: String) {+ val tm = context.getSystemService(TelecomManager::class.java) ?: return+ val extras = Bundle().apply {+ putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle(context))+ }+ val uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null)+ runCatching { tm.placeCall(uri, extras) }+ }++ /** Surface an inbound SIP INVITE to the system as an incoming self-managed call. */+ fun addIncoming(context: Context, from: String) {+ val tm = context.getSystemService(TelecomManager::class.java) ?: return+ val extras = Bundle().apply {+ putParcelable(+ TelecomManager.EXTRA_INCOMING_CALL_ADDRESS,+ Uri.fromParts(PhoneAccount.SCHEME_TEL, from, null),+ )+ }+ runCatching { tm.addNewIncomingCall(handle(context), extras) }+ }+}
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.ktnew file mode 100644index 0000000000..2acafaebf5--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt@@ -0,0 +1,130 @@+package com.vayunmathur.communicate.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconPerson+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.launch++/**+ * Account management for the merged inbox: shows the physical SIM line and the Google Voice+ * line, with sign-in / sign-out and the connected GV number.+ */+@Composable+fun AccountsScreen(onBack: () -> Unit, onSignIn: () -> Unit) {+ val context = LocalContext.current+ val session = remember { GoogleVoiceSession.get(context) }+ val scope = rememberCoroutineScope()+ val signedIn by session.signedInFlow.collectAsState(initial = false)+ val number by session.phoneNumberFlow.collectAsState(initial = null)++ // Fetch the GV number once after sign-in if we don't have it yet.+ androidx.compose.runtime.LaunchedEffect(signedIn, number) {+ if (signedIn && number == null) {+ runCatching { GoogleVoiceClient.get(context).getAccount() }+ }+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(stringResource(R.string.accounts_title)) },+ navigationIcon = { IconNavigation(onBack) },+ )+ },+ ) { padding ->+ Column(+ modifier = Modifier+ .padding(padding)+ .fillMaxSize()+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Card(modifier = Modifier.fillMaxWidth()) {+ ListItem(+ leadingContent = { IconCall() },+ content = { Text(stringResource(R.string.account_sim), fontWeight = FontWeight.SemiBold) },+ supportingContent = { Text(stringResource(R.string.line_sim)) },+ )+ }++ Card(modifier = Modifier.fillMaxWidth()) {+ Column(modifier = Modifier.padding(bottom = 8.dp)) {+ ListItem(+ leadingContent = { IconPerson() },+ content = {+ Text(stringResource(R.string.account_google_voice), fontWeight = FontWeight.SemiBold)+ },+ supportingContent = {+ Text(+ if (signedIn) {+ number ?: stringResource(R.string.gv_number_unknown)+ } else {+ stringResource(R.string.gv_not_signed_in)+ },+ )+ },+ )+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (signedIn) {+ OutlinedButton(+ onClick = {+ scope.launch {+ session.signOut()+ AppMessages.show(context.getString(R.string.gv_signed_out))+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Text(stringResource(R.string.gv_sign_out))+ }+ } else {+ Button(onClick = onSignIn, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.gv_sign_in))+ }+ }+ }+ }+ }++ if (signedIn && number == null) {+ Text(+ stringResource(R.string.gv_number_unknown),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}
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 0cfac61d3a..eca7124cae 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt@@ -4,6 +4,7 @@ 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@@ -46,7 +47,7 @@ fun CallLogsScreen() { modifier = Modifier.padding(padding), ) { permissionRevision -> val callLogs = produceState<List<CommunicateCallLogEntry>?>(initialValue = null, roleRevision, permissionRevision) {- value = withContext(Dispatchers.IO) { CommunicateRepository.loadCallLogs(context) }+ value = withContext(Dispatchers.IO) { CommunicateRepository.loadCallLogsMerged(context) } } when (val rows = callLogs.value) { null -> com.vayunmathur.library.ui.LoadingState(Modifier.padding(padding))@@ -79,12 +80,15 @@ private fun CallLogRow(entry: CommunicateCallLogEntry, onClick: () -> Unit) { val title = entry.displayName ?: entry.phoneNumber ListItem( content = {- Text(- title,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- fontWeight = if (entry.type == CommunicateCallType.Missed) FontWeight.Bold else FontWeight.Medium,- )+ 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))+ } }, supportingContent = { Column {
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.ktindex 85adfa73bf..c54dcd49dc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt@@ -9,6 +9,8 @@ import android.text.format.DateUtils import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -17,12 +19,18 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconSms+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import java.util.Date @@ -150,3 +158,26 @@ fun initialsFor(text: String): String = text .take(2) .joinToString("") { it.first().uppercase() } .ifBlank { "?" }++/**+ * Small pill that tags a row with the line (SIM vs Google Voice) it belongs to, so the+ * merged inbox / call log stays legible. Only Google Voice is badged; SIM is the implicit+ * default and left unbadged to avoid noise.+ */+@Composable+fun LineBadge(line: CommunicateLine, modifier: Modifier = Modifier) {+ if (line != CommunicateLine.GoogleVoice) return+ Surface(+ shape = RoundedCornerShape(50),+ color = MaterialTheme.colorScheme.tertiaryContainer,+ contentColor = MaterialTheme.colorScheme.onTertiaryContainer,+ modifier = modifier,+ ) {+ Text(+ stringResource(R.string.line_gv),+ modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp),+ fontSize = 10.sp,+ fontWeight = FontWeight.Bold,+ )+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex 425bf589b7..e275487f09 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -1,8 +1,8 @@ package com.vayunmathur.communicate.ui import android.Manifest+import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row@@ -18,9 +18,11 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -30,7 +32,11 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import androidx.core.net.toUri import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.IconArchive+import com.vayunmathur.library.ui.IconAttachment import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSend import com.vayunmathur.library.ui.IconSms@@ -42,15 +48,41 @@ import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.SmsMessage+import com.vayunmathur.communicate.data.SmsThread+import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import android.content.Intent @Composable-fun ConversationScreen(threadId: Long, address: String, onBack: () -> Unit) {+fun ConversationScreen(+ threadId: Long,+ address: String,+ line: CommunicateLine,+ remoteId: String?,+ onBack: () -> Unit,+) { val context = LocalContext.current+ val scope = rememberCoroutineScope() var draft by remember(threadId) { mutableStateOf("") }+ // Bumped after a Google Voice send to re-fetch the thread (no realtime channel yet).+ var refresh by remember(threadId) { mutableIntStateOf(0) }+ val thread = remember(threadId) {+ SmsThread(+ threadId = threadId,+ address = address,+ displayName = null,+ snippet = "",+ timestampMillis = 0,+ unreadCount = 0,+ line = line,+ remoteId = remoteId,+ )+ } val title = produceState(initialValue = address.ifBlank { context.getString(R.string.conversation_title) }, address) { value = withContext(Dispatchers.IO) { CommunicateRepository.findContactName(context, address)@@ -58,17 +90,38 @@ fun ConversationScreen(threadId: Long, address: String, onBack: () -> Unit) { } } + // Opening a Google Voice thread marks it read server-side via batchupdateattributes.+ androidx.compose.runtime.LaunchedEffect(remoteId, line) {+ if (line == CommunicateLine.GoogleVoice && remoteId != null) {+ CommunicateRepository.updateGoogleVoiceThread(+ context, remoteId, com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser.ThreadAction.MarkRead,+ )+ }+ }+ // Foreground polling for the open GV thread (no realtime channel yet).+ androidx.compose.runtime.LaunchedEffect(remoteId, line) {+ if (line == CommunicateLine.GoogleVoice && remoteId != null) {+ while (true) {+ kotlinx.coroutines.delay(10_000)+ refresh+++ }+ }+ }+ Scaffold( topBar = {
Diff truncated.