Modern Apps git

← Modern-Apps.git

messages: add Google Voice as a second source

Commit
a9a27b43aa41f655c959f736354762975f9951f2
Author
Vayun Mathur <[email protected]>
When
2026-05-30 18:29 UTC (6 months ago)
Parents
ac0d4be

Diff

messages/src/main/java/com/vayunmathur/messages/MainActivity.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt b/messages/src/main/java/com/vayunmathur/messages/MainActivity.ktindex aa129e7523..72621ba3d5 100644--- a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt+++ b/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt@@ -20,6 +20,7 @@ import com.vayunmathur.messages.ui.ConversationScreen import com.vayunmathur.messages.ui.InboxScreen import com.vayunmathur.messages.ui.SettingsScreen import com.vayunmathur.messages.ui.setup.MessagesPairingScreen+import com.vayunmathur.messages.ui.setup.VoiceLoginScreen import com.vayunmathur.messages.util.MessagesViewModel import kotlinx.serialization.Serializable @@ -61,6 +62,7 @@ sealed interface Route : NavKey {     @Serializable data class Conversation(val conversationId: String) : Route     @Serializable data object Settings : Route     @Serializable data object PairMessages : Route+    @Serializable data object LoginVoice : Route }  @Composable@@ -82,5 +84,8 @@ private fun Navigation(         entry<Route.PairMessages> {             MessagesPairingScreen(backStack, vm)         }+        entry<Route.LoginVoice> {+            VoiceLoginScreen(backStack)+        }     } }
messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.ktnew file mode 100644index 0000000000..a27113201a--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt@@ -0,0 +1,67 @@+package com.vayunmathur.messages.gvoice++/**+ * Endpoints + headers + content types ported from+ * `/Users/vayun/Documents/gvoice/pkg/libgv/constants.go`.+ *+ * Values are copied verbatim. Bumping `Chrome/128.0.0.0` in [UserAgent]+ * and the matching version in [SecChUa] occasionally is recommended to+ * stay current with real Chrome releases.+ */+object VoiceEndpoints {+    const val UserAgent =+        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"+    const val SecChUa =+        "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\""+    const val SecChPlatform = "\"Linux\""+    const val ClientVersion = "665865172"+    const val JavaScriptUserAgent = "google-api-javascript-client/1.1.0"+    const val WaaXUserAgent = "grpc-web-javascript/0.1"++    /** Sent as the X-ClientDetails header. URL-form-encoded blob the+     *  client sends to identify itself to the auth pipeline. */+    val ClientDetails: String = listOf(+        "appVersion" to "5.0 (X11)",+        "platform" to "Linux x86_64",+        "userAgent" to UserAgent,+    ).joinToString("&") { (k, v) ->+        java.net.URLEncoder.encode(k, "UTF-8") + "=" + java.net.URLEncoder.encode(v, "UTF-8")+    }++    const val ApiKey = "AIzaSyDTYc1N4xiODyrQYK0Kl6g_y279LjYkrBg"+    const val WaaApiKey = "AIzaSyBGb5fGAyC-pRcRU6MUHb__b_vKha71HRE"+    const val WaaRequestKey = "/JR8jsAkqotcKsEKhXic"+    const val UploadOpi = "111538494"++    const val Origin = "https://voice.google.com"++    const val ApiDomain = "clients6.google.com"+    const val RealtimeDomain = "signaler-pa.$ApiDomain"+    const val ContactsDomain = "peoplestack-pa.$ApiDomain"+    const val UploadDomain = "docs.google.com"+    const val WaaDomain = "waa-pa.$ApiDomain"++    private const val ApiBaseUrl = "https://$ApiDomain/voice/v1/voiceclient"+    const val EndpointGetAccount = "$ApiBaseUrl/account/get"+    const val EndpointGetThread = "$ApiBaseUrl/api2thread/get"+    const val EndpointListThreads = "$ApiBaseUrl/api2thread/list"+    const val EndpointSendSms = "$ApiBaseUrl/api2thread/sendsms"+    const val EndpointGetThreadingInfo = "$ApiBaseUrl/threadinginfo/get"+    const val EndpointUpdateAttributes = "$ApiBaseUrl/thread/updateattributes"+    const val EndpointMarkAllRead = "$ApiBaseUrl/thread/markallread"+    const val EndpointDeleteThread = "$ApiBaseUrl/thread/delete"++    private const val RealtimeBaseUrl = "https://$RealtimeDomain"+    const val EndpointRealtimeChannel = "$RealtimeBaseUrl/punctual/multi-watch/channel"+    const val EndpointRealtimeChooseServer = "$RealtimeBaseUrl/punctual/v1/chooseServer"++    private const val WaaBaseUrl = "https://$WaaDomain/\$rpc/google.internal.waa.v1.Waa"+    const val EndpointCreateWaa = "$WaaBaseUrl/Create"+    const val EndpointPingWaa = "$WaaBaseUrl/Ping"++    /** Cookie names the user must paste for sign-in to work. */+    val RequiredCookies = listOf("SID", "HSID", "SSID", "APISID", "SAPISID")++    /** Cookies we recognize + persist if present, even if not required. */+    val OptionalCookies = listOf("OSID", "COMPASS", "__Secure-1PSIDTS", "__Secure-3PSIDTS")+}
messages/src/main/java/com/vayunmathur/messages/gvoice/CookieParser.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/CookieParser.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/CookieParser.ktnew file mode 100644index 0000000000..49bbf83e14--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/CookieParser.kt@@ -0,0 +1,141 @@+package com.vayunmathur.messages.gvoice++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull++/**+ * Lenient parser for the cookie blobs users paste at setup time.+ *+ * Accepts three formats:+ *   1. A JSON object: `{"SID":"...","HSID":"..."}` — possibly with extra+ *      whitespace or trailing commas (we don't insist on strict JSON).+ *   2. A cURL command from the browser devtools "Copy as cURL" feature.+ *      We pull cookies out of the `-H 'Cookie: …'` (or `-b '…'`) flag+ *      and ignore everything else.+ *   3. A raw Cookie header value: `SID=…; HSID=…; …`+ *+ * Returns the recognized cookie subset (intersection of what's found+ * and the set of cookies Voice actually uses). Returns null when no+ * cookies could be extracted at all — the UI surfaces a validation+ * error in that case.+ */+object CookieParser {++    private val recognized: Set<String> =+        (VoiceEndpoints.RequiredCookies + VoiceEndpoints.OptionalCookies).toSet()++    fun parse(input: String): Map<String, String>? {+        val trimmed = input.trim()+        if (trimmed.isEmpty()) return null++        return parseJsonObject(trimmed)+            ?: parseNetscapeCookiesTxt(trimmed)+            ?: parseCurl(trimmed)+            ?: parseRawCookieHeader(trimmed)+    }++    /** Validate that all required cookies are present + non-empty. */+    fun missingRequired(cookies: Map<String, String>): List<String> =+        VoiceEndpoints.RequiredCookies.filter { cookies[it].isNullOrBlank() }++    // ----------------------------------------------------------------+    // Format-specific parsers+    // ----------------------------------------------------------------++    private fun parseJsonObject(input: String): Map<String, String>? {+        if (!input.startsWith("{")) return null+        val obj: JsonObject = try {+            Json.decodeFromString(JsonObject.serializer(), input)+        } catch (_: Throwable) {+            // Tolerant JSON: try a one-pass cleanup (strip trailing commas).+            val cleaned = input.replace(Regex(",\\s*([}\\]])"), "$1")+            try {+                Json.decodeFromString(JsonObject.serializer(), cleaned)+            } catch (_: Throwable) {+                return null+            }+        }+        val out = mutableMapOf<String, String>()+        for ((key, value) in obj) {+            if (key !in recognized) continue+            val v = (value as? JsonPrimitive)?.contentOrNull ?: continue+            if (v.isNotBlank()) out[key] = v+        }+        return out.takeIf { it.isNotEmpty() }+    }++    private fun parseCurl(input: String): Map<String, String>? {+        if (!input.contains("curl")) return null+        // Match `-H 'Cookie: ...'` or `-H "Cookie: ..."` (case-insensitive+        // header name; many curl exports use Cookie or cookie) and the+        // `-b '...'` short form.+        val patterns = listOf(+            Regex("""-H\s+['"](?:cookie|Cookie):\s*([^'"]+)['"]"""),+            Regex("""-b\s+['"]([^'"]+)['"]"""),+        )+        for (p in patterns) {+            val match = p.find(input) ?: continue+            return parseRawCookieHeader(match.groupValues[1])+        }+        return null+    }++    private fun parseRawCookieHeader(input: String): Map<String, String>? {+        // Don't match obvious non-cookie text. Required form: at least+        // one `key=value` pair separated by `;`.+        if (!input.contains('=')) return null+        val out = mutableMapOf<String, String>()+        for (part in input.split(';')) {+            val eq = part.indexOf('=')+            if (eq < 0) continue+            val key = part.substring(0, eq).trim()+            val value = part.substring(eq + 1).trim()+            if (key.isEmpty() || value.isEmpty()) continue+            if (key !in recognized) continue+            out[key] = value+        }+        return out.takeIf { it.isNotEmpty() }+    }++    /**+     * Parse Netscape's cookies.txt format (what the popular+     * "cookies.txt" / "cookies.txt LOCALLY" / "Get cookies.txt"+     * extensions all emit). Lines look like:+     *+     *     # Netscape HTTP Cookie File+     *     .google.com\tTRUE\t/\tTRUE\t1780000000\tSID\tabc123...+     *+     * Seven tab-separated fields per cookie line:+     *   1. domain+     *   2. includeSubdomains (TRUE/FALSE)+     *   3. path+     *   4. secure (TRUE/FALSE)+     *   5. expiration (unix seconds)+     *   6. name+     *   7. value+     *+     * Comment lines (starting with `#`) and blank lines are ignored.+     */+    private fun parseNetscapeCookiesTxt(input: String): Map<String, String>? {+        // Heuristic: there must be at least one line with 7 tab-separated+        // fields AND a recognized cookie name in field 6.+        val out = mutableMapOf<String, String>()+        var sawAnyTabLine = false+        for (line in input.lineSequence()) {+            val trimmed = line.trim()+            if (trimmed.isEmpty() || trimmed.startsWith("#")) continue+            val fields = line.split('\t')+            if (fields.size < 7) continue+            sawAnyTabLine = true+            val name = fields[5].trim()+            val value = fields[6].trim()+            if (name.isEmpty() || value.isEmpty()) continue+            if (name !in recognized) continue+            out[name] = value+        }+        if (!sawAnyTabLine) return null+        return out.takeIf { it.isNotEmpty() }+    }+}
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.ktnew file mode 100644index 0000000000..a1f1fca889--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -0,0 +1,316 @@+package com.vayunmathur.messages.gvoice++import android.content.Context+import android.util.Log+import com.vayunmathur.messages.data.MessageSource+import com.vayunmathur.messages.gmessages.GMEvent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import requests.Requests+import responses.Responses+import threads.Threads+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Process-global owner of the Google Voice protocol session.+ *+ * Mirrors the [com.vayunmathur.messages.gmessages.GMessagesClient]+ * pattern: a singleton with a state machine, an event flow, and+ * persistence backed by DataStore. Both this and the gmessages client+ * fan their events into the same [com.vayunmathur.messages.util.MessagesSessionManager]+ * which writes the unified Room DB.+ */+object GVoiceClient {++    private const val TAG = "GVoiceClient"++    sealed interface State {+        data object Idle : State+        /** Awaiting user-pasted cookies — UI shows the paste form. */+        data object NeedsSetup : State+        data object Connecting : State+        data object Connected : State+        data class Disconnected(val reason: String) : State+    }++    val source: MessageSource = MessageSource.VOICE++    private val _state = MutableStateFlow<State>(State.Idle)+    val state: StateFlow<State> = _state.asStateFlow()++    private val _events = MutableSharedFlow<GMEvent>(extraBufferCapacity = 256)+    val events: SharedFlow<GMEvent> = _events.asSharedFlow()++    private val initialized = AtomicBoolean(false)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private lateinit var appContext: Context+    @Volatile private var rpc: GVoiceRpcClient? = null+    private var realtime: RealtimeChannel? = null+    private var backfillJob: Job? = null++    fun init(context: Context) {+        if (!initialized.compareAndSet(false, true)) return+        appContext = context.applicationContext+        Log.i(TAG, "init")+        runBlocking {+            val auth = VoiceAuthData.load(appContext)+            if (auth?.hasRequired() == true) {+                Log.i(TAG, "resuming from persisted cookies")+                bootSession(auth)+            } else {+                _state.value = State.NeedsSetup+            }+        }+    }++    fun start() {+        if (!initialized.get()) return+        if (_state.value is State.Connected) return+        scope.launch {+            val auth = VoiceAuthData.load(appContext)+            if (auth?.hasRequired() == true) bootSession(auth)+            else _state.value = State.NeedsSetup+        }+    }++    fun stop() {+        Log.i(TAG, "stop — clearing Voice session")+        backfillJob?.cancel()+        realtime?.stop()+        realtime = null+        rpc?.close()+        rpc = null+        scope.launch { VoiceAuthData.clear(appContext) }+        _state.value = State.NeedsSetup+    }++    /**+     * Validate the user-supplied cookies via a GetAccount round-trip;+     * on success, persist + start the session. Returns null on success+     * (and transitions state to Connecting → Connected), or a+     * human-readable error message on failure.+     */+    suspend fun submitCookies(cookies: Map<String, String>): String? {+        val missing = CookieParser.missingRequired(cookies)+        if (missing.isNotEmpty()) return "Missing required cookies: ${missing.joinToString(", ")}"+        _state.value = State.Connecting+        val client = GVoiceRpcClient(cookies)+        val accountOk = try {+            val acc = client.postPbLite(+                url = VoiceEndpoints.EndpointGetAccount,+                body = Requests.ReqGetAccount.getDefaultInstance(),+                responseTemplate = Responses.RespGetAccount.getDefaultInstance(),+            )+            Log.i(TAG, "GetAccount OK; primary=${acc.account.primaryDestinationID}")+            true+        } catch (t: Throwable) {+            Log.e(TAG, "GetAccount failed: ${t.message}")+            client.close()+            _state.value = State.NeedsSetup+            return "Sign-in failed: ${t.message?.take(160) ?: "unknown error"}"+        }+        if (!accountOk) return "Sign-in validation failed"+        val authData = VoiceAuthData(cookies)+        authData.save(appContext)+        // Tear down any previous session before booting the new one.+        realtime?.stop()+        rpc?.close()+        rpc = client+        bootSession(authData)+        return null+    }++    /** Trigger a re-list of conversations. */+    fun forceResync() {+        if (_state.value !is State.Connected) return+        kickoffBackfill()+    }++    /** Load (or refresh) messages for a thread. */+    fun fetchMessages(conversationId: String, count: Int = 100) {+        if (_state.value !is State.Connected) return+        scope.launch {+            val client = rpc ?: return@launch+            val webId = conversationId.substringAfter(':', conversationId)+            Log.i(TAG, "fetchMessages threadId=$webId count=$count")+            val req = Requests.ReqGetThread.newBuilder()+                .setThreadID(webId)+                .setMaybeMessageCount(count)+                .build()+            val resp = try {+                client.postPbLite(+                    url = VoiceEndpoints.EndpointGetThread,+                    body = req,+                    responseTemplate = Responses.RespGetThread.getDefaultInstance(),+                )+            } catch (t: Throwable) {+                Log.w(TAG, "GetThread failed: ${t.message}")+                return@launch+            }+            if (!resp.hasThread()) return@launch+            val thread = resp.thread+            for (i in 0 until thread.messagesCount) {+                emitMessage(thread.getID(), thread.getMessages(i))+            }+        }+    }++    // ----------------------------------------------------------------+    // Internals+    // ----------------------------------------------------------------++    private fun bootSession(auth: VoiceAuthData) {+        val client = rpc ?: GVoiceRpcClient(auth.cookies).also { rpc = it }+        client.updateCookies(auth.cookies)+        rpc = client++        _state.value = State.Connected+        realtime?.stop()+        realtime = RealtimeChannel(client) { evt ->+            when (evt) {+                RealtimeEvent.Connected -> Log.i(TAG, "realtime connected")+                is RealtimeEvent.Data -> handleRealtimeData(evt.event)+            }+        }.also { it.start(scope) }+        kickoffBackfill()+    }++    private fun kickoffBackfill() {+        backfillJob?.cancel()+        backfillJob = scope.launch {+            val client = rpc ?: return@launch+            Log.i(TAG, "ListThreads (TEXT_THREADS)")+            val req = Requests.ReqListThreads.newBuilder()+                .setFolder(Threads.ThreadFolder.TEXT_THREADS)+                // libgv hard-codes these "unknown" fields — 20 on the+                // first call (10 on subsequent), 15 for the second.+                // Without them the server returns 0 threads even though+                // the account has real conversations.+                .setUnknownInt2(20)+                .setUnknownInt3(15)+                .build()+            val resp = try {+                client.postPbLite(+                    url = VoiceEndpoints.EndpointListThreads,+                    body = req,+                    responseTemplate = Responses.RespListThreads.getDefaultInstance(),+                )+            } catch (t: Throwable) {+                Log.w(TAG, "ListThreads failed: ${t.message}")+                _state.value = State.Disconnected(t.message ?: "ListThreads failed")+                return@launch+            }+            Log.i(TAG, "ListThreads: ${resp.threadsCount} threads")+            for (i in 0 until resp.threadsCount) {+                emitConversation(resp.getThreads(i))+            }+        }+    }++    private suspend fun handleRealtimeData(evt: webchannel.Webchannel.WebChannelEvent) {+        // Each realtime event can carry thread updates / new message+        // notifications. The shape is deeply nested; for v1 just+        // re-trigger the backfill on any event — it's cheap and+        // guarantees consistency until we wire per-event decoding.+        Log.d(TAG, "realtime event arrayID=${evt.arrayID} wrappers=${evt.dataWrapperCount}")+        kickoffBackfill()+    }++    private suspend fun emitConversation(t: Threads.Thread) {+        val contact = if (t.contactsCount > 0) t.getContacts(0) else null+        val peerPhone = contact?.phoneNumber?.takeIf { it.isNotBlank() }+        // Lookup in device contacts (same as the gmessages path).+        val device = peerPhone?.let {+            com.vayunmathur.messages.util.ContactResolver.lookup(appContext, it)+        }++        val isGroup = t.contactsCount > 1+        val displayName: String? = when {+            isGroup -> {+                val names = (0 until t.contactsCount).mapNotNull { idx ->+                    val c = t.getContacts(idx)+                    val phone = c.phoneNumber.takeIf { it.isNotBlank() }+                    val deviceName = phone?.let {+                        com.vayunmathur.messages.util.ContactResolver.lookup(appContext, it)?.displayName+                    }+                    deviceName ?: c.name.takeIf { n -> n.isNotBlank() } ?: phone+                }+                when {+                    names.isEmpty() -> "Group"+                    names.size <= 2 -> names.joinToString(", ")+                    else -> names.take(2).joinToString(", ") + " & ${names.size - 2} others"+                }+            }+            else -> device?.displayName ?: peerPhone ?: contact?.name?.takeIf { it.isNotBlank() }+        }++        val latest: Threads.Message? = if (t.messagesCount > 0) {+            t.getMessages(t.messagesCount - 1)+        } else null+        val preview = latest?.text?.takeIf { it.isNotBlank() }+        // Voice's Message.timestamp is epoch-milliseconds (confirmed+        // against mautrix-gvoice's `time.UnixMilli(msg.Timestamp)`).+        // Don't scale.+        val tsMillis = latest?.timestamp ?: 0L++        _events.emit(+            GMEvent.ConversationUpdate(+                source = source,+                conversationId = t.getID(),+                peerName = displayName,+                peerPhone = if (isGroup) null else peerPhone,+                avatarUrl = device?.photoUri,+                lastPreview = preview,+                lastTimestamp = tsMillis,+                // `Thread.read = false` means there are unread messages.+                unreadCount = if (!t.read) 1 else 0,+                isGroup = isGroup,+                participantCount = t.contactsCount,+                conversationType = "Voice",+            )+        )+    }++    private suspend fun emitMessage(threadId: String, m: Threads.Message) {+        // Skip non-text messages (calls / voicemail / etc.) for v1.+        if (m.text.isBlank()) return+        val outgoing = m.type == Threads.Message.Type.SMS_OUT+        val tsMs = m.timestamp+        val peerPhone = if (m.hasContact()) m.contact.phoneNumber.takeIf { it.isNotBlank() } else null+        _events.emit(+            GMEvent.MessageUpdate(+                source = source,+                conversationId = threadId,+                messageId = m.getID(),+                body = m.text,+                outgoing = outgoing,+                timestamp = tsMs,+                senderName = if (m.hasContact()) m.contact.name.takeIf { it.isNotBlank() } else null,+            )+        )+        if (!outgoing) {+            _events.emit(+                GMEvent.IncomingMessage(+                    source = source,+                    conversationId = threadId,+                    messageId = m.getID(),+                    body = m.text,+                    peerName = if (m.hasContact()) m.contact.name.takeIf { it.isNotBlank() } else null,+                    peerPhone = peerPhone,+                    timestamp = tsMs,+                )+            )+        }+    }+}
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceRpcClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceRpcClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceRpcClient.ktnew file mode 100644index 0000000000..486a83dbb4--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceRpcClient.kt@@ -0,0 +1,315 @@+package com.vayunmathur.messages.gvoice++import android.util.Base64+import android.util.Log+import com.google.protobuf.Message+import com.vayunmathur.messages.gmessages.PbLite+import io.ktor.client.HttpClient+import io.ktor.client.engine.cio.CIO+import io.ktor.client.plugins.HttpTimeout+import io.ktor.client.request.headers+import io.ktor.client.request.preparePost+import io.ktor.client.request.request+import io.ktor.client.request.setBody+import io.ktor.client.statement.HttpResponse+import io.ktor.client.statement.bodyAsBytes+import io.ktor.client.statement.bodyAsChannel+import io.ktor.http.ContentType+import io.ktor.http.HttpMethod+import io.ktor.http.URLBuilder+import io.ktor.http.contentType+import io.ktor.http.encodedPath+import io.ktor.utils.io.ByteReadChannel+import java.security.MessageDigest++/**+ * HTTP transport for the Google Voice protocol.+ *+ * Mirrors `pkg/libgv/request.go`:+ *  - All RPC bodies are pblite-encoded JSON by default; binary protobuf+ *    when explicitly requested.+ *  - Per-host header bundles (`Sec-Fetch-Site`, `X-Client-Version`,+ *    `X-ClientDetails`, `X-Goog-Api-Key`, etc) vary by destination+ *    domain — see [applyHeaders].+ *  - Cookies are sent on every request; the `SAPISID` cookie also+ *    materializes as an `Authorization: SAPISIDHASH …` header (same+ *    algorithm libgm uses).+ *  - Retries network errors and 5xx up to [MAX_RETRIES] with linear+ *    backoff.+ */+class GVoiceRpcClient(+    /** Mutable cookie jar; updated atomically by the session manager+     *  when Set-Cookie headers come back. */+    @Volatile private var cookies: Map<String, String>,+) {+    private val normal: HttpClient = HttpClient(CIO) {+        engine { requestTimeout = 30_000 }+        install(HttpTimeout) {+            requestTimeoutMillis = 30_000+            connectTimeoutMillis = 15_000+            socketTimeoutMillis = 30_000+        }+    }++    private val realtime: HttpClient = HttpClient(CIO) {+        // BrowserChannel long-polls can stay open for several minutes.+        engine { requestTimeout = 0 }+        install(HttpTimeout) {+            requestTimeoutMillis = 6 * 60 * 1000+            connectTimeoutMillis = 15_000+            socketTimeoutMillis = 90_000+        }+    }++    fun updateCookies(newCookies: Map<String, String>) {+        cookies = newCookies+    }++    fun close() {+        runCatching { normal.close() }+        runCatching { realtime.close() }+    }++    /** POST [body] as pblite. Returns the decoded response of type [T]. */+    suspend fun <T : Message> postPbLite(+        url: String,+        body: Message,+        responseTemplate: T,+    ): T {+        val resp = postRetrying(url, PbLite.encode(body).toByteArray(Charsets.UTF_8), pbLite = true)+        return decodeResponse(resp, responseTemplate)+    }++    /**+     * POST a raw JSON literal as a pblite body. Used by the BrowserChannel+     * subscribe path which sends a hardcoded magic JSON literal that has+     * no protobuf representation in the bridge either.+     */+    suspend fun <T : Message> postRawPbLite(+        url: String,+        jsonBody: String,+        responseTemplate: T,+    ): T {+        val resp = postRetrying(url, jsonBody.toByteArray(Charsets.UTF_8), pbLite = true)+        return decodeResponse(resp, responseTemplate)+    }++    /** POST raw bytes as protobuf binary. */+    suspend fun <T : Message> postBinary(+        url: String,+        body: Message,+        responseTemplate: T,+    ): T {+        val resp = postRetrying(url, body.toByteArray(), pbLite = false)+        return decodeResponse(resp, responseTemplate)+    }++    /** POST a form-encoded body. Returns the raw response so the caller+     *  can inspect headers / body shape (BrowserChannel needs this). */+    suspend fun postForm(+        url: String,+        form: Map<String, String>,+    ): HttpResponse {+        val body = form.entries.joinToString("&") { (k, v) ->+            java.net.URLEncoder.encode(k, "UTF-8") + "=" + java.net.URLEncoder.encode(v, "UTF-8")+        }+        return postRetrying(+            url,+            body.toByteArray(Charsets.UTF_8),+            contentType = "application/x-www-form-urlencoded",+            pbLite = false,+        )+    }++    /**+     * GET a streaming response — used by the BrowserChannel long-poll.+     * Caller reads the body via [onResponse] which gets the raw+     * [HttpResponse]; keeping the connection open for the duration of+     * the callback (preparePost-style execution).+     */+    suspend fun <T> getStreaming(+        url: String,+        extraQuery: Map<String, String> = emptyMap(),+        onResponse: suspend (HttpResponse) -> T,+    ): T {+        val finalUrl = buildUrl(url, extraQuery)+        return realtime.preparePost(finalUrl) {+            method = HttpMethod.Get+            applyHeaders(finalUrl, accept = "*/*", contentType = null)+        }.execute { response -> onResponse(response) }+    }++    /** Stream the body of a still-open response. Used by [Utf16ChunkReader]. */+    suspend fun bodyChannel(response: HttpResponse): ByteReadChannel = response.bodyAsChannel()++    // ----------------------------------------------------------------+    // POST core + retry+    // ----------------------------------------------------------------++    private suspend fun postRetrying(+        url: String,+        body: ByteArray,+        pbLite: Boolean = true,+        contentType: String? =+            if (pbLite) "application/json+protobuf" else "application/x-protobuf",+    ): HttpResponse {+        val finalUrl = buildUrl(url, emptyMap())+        var attempt = 0+        while (true) {+            val resp = try {+                normal.request(finalUrl) {+                    method = HttpMethod.Post+                    if (contentType != null) contentType(ContentType.parse(contentType))+                    applyHeaders(finalUrl, accept = "*/*", contentType = contentType)+                    setBody(body)+                }+            } catch (t: Throwable) {+                if (attempt >= MAX_RETRIES) throw t+                attempt+++                Log.w(TAG, "POST $url network error attempt=$attempt: ${t.message}")+                kotlinx.coroutines.delay((attempt * 2_000L))+                continue+            }+            // Retry only on 5xx; 4xx is the caller's problem.+            if (resp.status.value in 500..599 && attempt < MAX_RETRIES) {+                attempt+++                Log.w(TAG, "POST $url ${resp.status.value} attempt=$attempt")+                kotlinx.coroutines.delay((attempt * 2_000L))+                continue+            }+            return resp+        }+    }++    /**+     * Build a URL, appending the standard `key=...` (+ optional `alt=proto`)+     * query parameters that libgv adds for the API + Contacts domains.+     */+    private fun buildUrl(url: String, extraQuery: Map<String, String>): String {+        val builder = URLBuilder(url)+        val host = builder.host+        if (host.endsWith(VoiceEndpoints.ApiDomain) && host != VoiceEndpoints.WaaDomain) {+            builder.parameters.append("key", VoiceEndpoints.ApiKey)+            if (host == VoiceEndpoints.ApiDomain || host == VoiceEndpoints.ContactsDomain) {+                builder.parameters.append("alt", "proto")+            }+        }+        for ((k, v) in extraQuery) builder.parameters.append(k, v)+        return builder.buildString()+    }++    /**+     * Apply the per-host header bundle the bridge documents. Includes the+     * cookie jar + (when SAPISID is present) the SAPISIDHASH authorization.+     */+    private fun io.ktor.client.request.HttpRequestBuilder.applyHeaders(+        url: String,+        accept: String,+        contentType: String?,+    ) {+        val host = URLBuilder(url).host+        headers {+            append("Sec-Ch-Ua", VoiceEndpoints.SecChUa)+            append("Sec-Ch-Ua-Platform", VoiceEndpoints.SecChPlatform)+            append("Sec-Ch-Ua-Mobile", "?0")+            append("User-Agent", VoiceEndpoints.UserAgent)+            append("X-Goog-AuthUser", "0")+            if (host == VoiceEndpoints.ApiDomain) {+                append("X-Client-Version", VoiceEndpoints.ClientVersion)+                append("X-ClientDetails", VoiceEndpoints.ClientDetails)+                append("X-JavaScript-User-Agent", VoiceEndpoints.JavaScriptUserAgent)+                append("X-Requested-With", "XMLHttpRequest")+                append("X-Goog-Encode-Response-If-Executable", "base64")+            }+            if (host == VoiceEndpoints.ContactsDomain) {+                append("X-Goog-Api-Key", VoiceEndpoints.ApiKey)+                append("X-Goog-Encode-Response-If-Executable", "base64")+            }+            if (host == VoiceEndpoints.WaaDomain) {+                append("X-Goog-Api-Key", VoiceEndpoints.WaaApiKey)+                append("X-User-Agent", VoiceEndpoints.WaaXUserAgent)+            }+            append("Sec-Fetch-Dest", "empty")+            append("Sec-Fetch-Mode", "cors")+            val site = if (host.endsWith(".${VoiceEndpoints.ApiDomain}")) "same-site" else "same-origin"+            append("Sec-Fetch-Site", site)+            append("Accept", accept)+            append("Accept-Language", "en-US,en;q=0.5")+            if (host == VoiceEndpoints.UploadDomain) {+                append("Origin", "https://${VoiceEndpoints.UploadDomain}")+                append("Referer", "https://${VoiceEndpoints.UploadDomain}/")+            } else {+                append("Origin", VoiceEndpoints.Origin)+                append("Referer", "${VoiceEndpoints.Origin}/")+            }+            if (contentType != null) append("Content-Type", contentType)++            // Cookies + SAPISIDHASH.+            val cookieHeader = cookies.entries.joinToString("; ") { (k, v) -> "$k=$v" }+            if (cookieHeader.isNotEmpty()) append("Cookie", cookieHeader)+            cookies["SAPISID"]?.let { sapisid ->+                append("Authorization", sapisidHash(VoiceEndpoints.Origin, sapisid))+            }+        }+    }++    // ----------------------------------------------------------------+    // Response decoding+    // ----------------------------------------------------------------++    private suspend fun <T : Message> decodeResponse(resp: HttpResponse, template: T): T {+        if (resp.status.value !in 200..299) {+            val body = runCatching { resp.bodyAsBytes() }.getOrNull()?.let {+                String(it, Charsets.UTF_8).take(500)+            } ?: "<no body>"+            error("HTTP ${resp.status.value}: $body")+        }+        val plainMime = resp.headers["Content-Type"]?.substringBefore(';')?.trim().orEmpty().lowercase()+        val safetyMime = resp.headers["X-Goog-Safety-Content-Type"]+            ?.substringBefore(';')?.trim().orEmpty().lowercase()+        val realMime = safetyMime.ifEmpty { plainMime }++        // utf16-chunk framing on the safety mime. Voice uses this on+        // some endpoints to defeat naive XSSI-style attacks.+        val raw: ByteArray = if (realMime == "text/plain") {+            val channel = resp.bodyAsChannel()+            Utf16ChunkReader(channel).readChunk() ?: error("empty utf16chunk body")+        } else {+            resp.bodyAsBytes()+        }++        @Suppress("UNCHECKED_CAST")+        return when (realMime) {+            "application/x-protobuf" -> {+                // Tolerate the base64-wrapped-protobuf variant Voice+                // sometimes serves (real MIME protobuf, declared MIME+                // text/plain because of the safety header).+                val bytes = if (plainMime == "text/plain") {+                    Base64.decode(raw, Base64.DEFAULT)+                } else raw+                template.parserForType.parseFrom(bytes) as T+            }+            "application/json+protobuf", "text/plain" -> {+                val builder = template.newBuilderForType()+                PbLite.decode<T>(String(raw, Charsets.UTF_8), builder)+            }+            else -> error("unknown response content-type: $realMime")+        }+    }++    companion object {+        private const val TAG = "GVoice/Rpc"+        private const val MAX_RETRIES = 10++        /** Same algorithm as libgm's SAPISIDHASH. Reproduced inline to+         *  avoid a cross-module import. */+        internal fun sapisidHash(origin: String, sapisid: String): String {+            val ts = System.currentTimeMillis() / 1000L+            val toHash = "$ts $sapisid $origin"+            val md = MessageDigest.getInstance("SHA-1")+            val hash = md.digest(toHash.toByteArray(Charsets.UTF_8))+            val hex = hash.joinToString("") { "%02x".format(it) }+            return "SAPISIDHASH ${ts}_$hex"+        }+    }+}
messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.ktnew file mode 100644index 0000000000..26fea56249--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/RealtimeChannel.kt@@ -0,0 +1,318 @@+package com.vayunmathur.messages.gvoice++import android.util.Log+import com.vayunmathur.messages.gmessages.PbLite+import io.ktor.client.statement.HttpResponse+import io.ktor.client.statement.bodyAsBytes+import io.ktor.client.statement.bodyAsChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import webchannel.Webchannel+import kotlin.random.Random++/**+ * Port of `pkg/libgv/channel.go`. Drives the BrowserChannel-based+ * realtime stream Google Voice uses to push new messages and updates.+ *+ * Two phases:+ *   1. [subscribe] — POST a hardcoded magic JSON literal to+ *      `chooseServer`, get back `gSessionID`. Then POST 7 hardcoded+ *      form-encoded event-subscriptions to the channel endpoint, get+ *      back the channel session ID.+ *   2. [run] — blocking loop. GETs the channel endpoint with the+ *      session id, reads framed [Utf16ChunkReader] chunks until EOF or+ *      error. Each chunk is a JSON array of events: noop events bump+ *      the ack counter; reconnect-marker events trigger a re-subscribe;+ *      everything else dispatches a `RealtimeEvent` upstream.+ *+ * Auto-reconnect on Unknown SID (up to 10 attempts with linear backoff),+ * forced re-subscribe every hour as a heartbeat.+ */+class RealtimeChannel(+    private val rpc: GVoiceRpcClient,+    private val onEvent: suspend (RealtimeEvent) -> Unit,+) {+    private var job: Job? = null++    fun start(scope: CoroutineScope) {+        if (job?.isActive == true) return+        job = scope.launch { runLoop() }+    }++    fun stop() {+        job?.cancel()+        job = null+    }++    private suspend fun runLoop() {+        var backoffMs = 0L+        while (true) {+            if (backoffMs > 0) {+                Log.i(TAG, "reconnecting in ${backoffMs / 1000}s")+                delay(backoffMs)+            }+            val ok = try {+                run()+            } catch (t: Throwable) {+                Log.w(TAG, "realtime error: ${t.message}")+                false+            }+            if (!kotlin.coroutines.coroutineContext.isActive) return+            backoffMs = if (ok) 0L else (if (backoffMs == 0L) 5_000L else minOf(60_000L, backoffMs * 2))+        }+    }++    private suspend fun run(): Boolean {+        var subscription = subscribe() ?: return false+        var ackId = 0L+        var failedRequests = 0+        var lastResubscribeMs = System.currentTimeMillis()+        var anyEventSeen = false++        while (true) {+            if (System.currentTimeMillis() - lastResubscribeMs > FORCE_RESUBSCRIBE_INTERVAL_MS) {+                Log.i(TAG, "force re-subscribe (interval elapsed)")+                subscription = subscribe() ?: return anyEventSeen+                ackId = 0+                lastResubscribeMs = System.currentTimeMillis()+            }++            val query = mapOf(+                "VER" to "8",+                "gsessionid" to subscription.gSessionId,+                "RID" to "rpc",+                "SID" to subscription.sessionId,+                "AID" to ackId.toString(),+                "CI" to "0",+                "TYPE" to "xmlhttp",+                "t" to "1",+            )+            Log.d(TAG, "open long-poll AID=$ackId SID=${subscription.sessionId}")++            val outcome = rpc.getStreaming(+                VoiceEndpoints.EndpointRealtimeChannel,+                extraQuery = query,+            ) { resp ->+                if (resp.status.value !in 200..299) {+                    val body = runCatching { resp.bodyAsBytes() }.getOrNull()+                        ?.let { String(it, Charsets.UTF_8) } ?: ""+                    if (body.contains("Unknown SID")) {+                        ChannelOutcome.UnknownSid+                    } else {+                        Log.w(TAG, "long-poll HTTP ${resp.status.value}; body=${body.take(200)}")+                        ChannelOutcome.Error(resp.status.value)+                    }+                } else {+                    if (failedRequests > 0 || ackId == 0L) onEvent(RealtimeEvent.Connected)+                    val newAckId = readChunks(resp, ackId).also { anyEventSeen = anyEventSeen || it.eventCount > 0 }+                    ackId = newAckId.lastAckId+                    if (newAckId.needResubscribe) {+                        ChannelOutcome.Reconnect+                    } else {+                        ChannelOutcome.Ok+                    }+                }+            }++            when (outcome) {+                ChannelOutcome.UnknownSid -> {+                    failedRequests+++                    if (failedRequests > 10) {+                        Log.e(TAG, "too many Unknown SID errors")+                        return anyEventSeen+                    }+                    val sleep = ((failedRequests - 1) * 2_000L).coerceAtLeast(0)+                    if (sleep > 0) delay(sleep)+                    subscription = subscribe() ?: return anyEventSeen+                    ackId = 0+                    lastResubscribeMs = System.currentTimeMillis()+                }+                ChannelOutcome.Reconnect -> {+                    subscription = subscribe() ?: return anyEventSeen+                    ackId = 0+                    lastResubscribeMs = System.currentTimeMillis()+                }+                is ChannelOutcome.Error -> return anyEventSeen+                ChannelOutcome.Ok -> {+                    failedRequests = 0+                }+            }+        }+    }++    private sealed interface ChannelOutcome {+        data object Ok : ChannelOutcome+        data object UnknownSid : ChannelOutcome+        data object Reconnect : ChannelOutcome+        data class Error(val status: Int) : ChannelOutcome+    }++    private data class ReadOutcome(val lastAckId: Long, val needResubscribe: Boolean, val eventCount: Int)++    private suspend fun readChunks(resp: HttpResponse, startAckId: Long): ReadOutcome {+        var ackId = startAckId+        var needResubscribe = false+        var eventCount = 0+        val reader = Utf16ChunkReader(resp.bodyAsChannel())+        while (true) {+            val chunk = reader.readChunk() ?: break+            // Each chunk is a top-level JSON array of entries.+            val chunkStr = String(chunk, Charsets.UTF_8)+            val entries = splitTopLevelJsonArray(chunkStr) ?: run {+                Log.w(TAG, "couldn't split chunk into entries: ${chunkStr.take(2000)}")+                continue+            }+            for (entry in entries) {+                eventCount+++                if (entry.endsWith(NOOP_SUFFIX)) {+                    // Pure-noop: just bump ackId.+                    runCatching {+                        PbLite.decode<Webchannel.WebChannelNoopEvent>(+                            entry, Webchannel.WebChannelNoopEvent.newBuilder(),+                        )+                    }.getOrNull()?.let { ackId = it.arrayID }+                    continue+                }+                val parsed = runCatching {+                    PbLite.decode<Webchannel.WebChannelEvent>(+                        entry, Webchannel.WebChannelEvent.newBuilder(),+                    )+                }.getOrNull()+                if (parsed == null) {+                    Log.w(TAG, "couldn't parse channel entry: ${entry.take(2000)}")+                    continue+                }+                // Reconnect-marker check: a single dataWrapper with altData.reconnect == true.+                if (parsed.dataWrapperCount == 1 &&+                    parsed.getDataWrapper(0).hasAltData() &&+                    parsed.getDataWrapper(0).altData.reconnect+                ) {+                    Log.i(TAG, "got reconnect marker; will re-subscribe")+                    needResubscribe = true+                    break+                }+                ackId = parsed.arrayID+                onEvent(RealtimeEvent.Data(parsed))+            }+            if (needResubscribe) break+        }+        return ReadOutcome(ackId, needResubscribe, eventCount)+    }++    /** Splits a top-level JSON array string `[a, b, c]` into its+     *  element substrings without instantiating a full JSON tree. Used+     *  because we want to PbLite-decode each entry individually. */+    private fun splitTopLevelJsonArray(input: String): List<String>? {+        val s = input.trim()+        if (!s.startsWith("[") || !s.endsWith("]")) return null+        val out = mutableListOf<String>()+        var depth = 0+        var inString = false+        var escape = false+        var start = 1+        for (i in 1 until s.length - 1) {+            val c = s[i]+            when {+                escape -> escape = false+                c == '\\' && inString -> escape = true+                c == '"' -> inString = !inString+                inString -> Unit+                c == '[' || c == '{' -> depth+++                c == ']' || c == '}' -> depth--+                c == ',' && depth == 0 -> {+                    out += s.substring(start, i).trim()+                    start = i + 1+                }+            }+        }+        val last = s.substring(start, s.length - 1).trim()+        if (last.isNotEmpty()) out += last+        return out+    }++    // ----------------------------------------------------------------+    // Subscribe: chooseServer + createChannel+    // ----------------------------------------------------------------++    private data class Subscription(val gSessionId: String, val sessionId: String)++    private suspend fun subscribe(): Subscription? = try {+        Log.i(TAG, "subscribe: chooseServer")+        // The hardcoded literal libgv uses for chooseServer.+        val chooseResp = rpc.postRawPbLite(+            url = VoiceEndpoints.EndpointRealtimeChooseServer,+            jsonBody = REQ_CHOOSE_SERVER,+            responseTemplate = Webchannel.RespChooseServer.getDefaultInstance(),+        )+        val gSessionId = chooseResp.gSessionID+        Log.i(TAG, "subscribe: gSessionID=$gSessionId")++        val rid = Random.nextInt(0, 100_000)+        val createUrl = with(io.ktor.http.URLBuilder(VoiceEndpoints.EndpointRealtimeChannel)) {+            parameters.append("VER", "8")+            parameters.append("gsessionid", gSessionId)+            parameters.append("RID", rid.toString())+            parameters.append("CVER", "22")+            parameters.append("t", "1")+            buildString()+        }+        val form = mapOf(+            "count" to "7",+            "ofs" to "0",+            "req0___data__" to "[[[\"1\",[null,null,null,[7,5],null,[null,[null,1],[[[\"2\"]]]],null,1,2],null,3]]]",+            "req1___data__" to "[[[\"2\",[null,null,null,[7,5],null,[null,[null,1],[[[\"3\"]]]],null,1,2],null,3]]]",+            "req2___data__" to "[[[\"3\",[null,null,null,[7,5],null,[null,[null,1],[[[\"3\"]]]],null,1,2],null,3]]]",+            "req3___data__" to "[[[\"4\",[null,null,null,[7,5],null,[null,[null,1],[[[\"1\"]]]],null,1,2],null,3]]]",+            "req4___data__" to "[[[\"5\",[null,null,null,[7,5],null,[null,[null,1],[[[\"1\"]]]],null,1,2],null,3]]]",+            "req5___data__" to "[[[\"6\",[null,null,null,[7,5],null,[null,[null,1],[[[\"1\"]]]],null,1,2],null,3]]]",+            "req6___data__" to "[[[\"9\",[null,null,null,[7,5],null,[null,[null,1],[[[\"1\"]]]],null,1,2],null,3]]]",+        )+        val createResp = rpc.postForm(createUrl, form)+        if (createResp.status.value !in 200..299) {+            Log.e(TAG, "createChannel HTTP ${createResp.status.value}")+            return null+        }+        // createChannel's response uses the same utf16chunk safety+        // framing the other punctual endpoints do — the body is+        // `<utf16-length>\n<pblite-json>` rather than just the JSON.+        // Detect via X-Goog-Safety-Content-Type and unwrap when needed.+        val safetyMime = createResp.headers["X-Goog-Safety-Content-Type"]+            ?.substringBefore(';')?.trim().orEmpty().lowercase()+        val plainMime = createResp.headers["Content-Type"]+            ?.substringBefore(';')?.trim().orEmpty().lowercase()+        val realMime = safetyMime.ifEmpty { plainMime }+        val raw: ByteArray = if (realMime == "text/plain") {+            Utf16ChunkReader(createResp.bodyAsChannel()).readChunk()+                ?: error("createChannel: empty utf16chunk body")+        } else {+            createResp.bodyAsBytes()+        }+        val parsed = PbLite.decode<Webchannel.RespCreateChannel>(+            String(raw, Charsets.UTF_8),+            Webchannel.RespCreateChannel.newBuilder(),+        )+        val sessionId = parsed.data.session.sessionID+        Log.i(TAG, "subscribe: sessionID=$sessionId")+        Subscription(gSessionId = gSessionId, sessionId = sessionId)+    } catch (t: Throwable) {+        Log.e(TAG, "subscribe failed: ${t.message}", t)+        null+    }++    companion object {+        private const val TAG = "GVoice/Realtime"+        private const val FORCE_RESUBSCRIBE_INTERVAL_MS = 60L * 60L * 1000L+        private const val NOOP_SUFFIX = ",[\"noop\"]]"+        private const val REQ_CHOOSE_SERVER =+            "[[null,null,null,[7,5],null,[null,[null,1],[[[\"3\"]]]]]]"+    }+}++/** Events the realtime channel surfaces. */+sealed interface RealtimeEvent {+    data object Connected : RealtimeEvent+    data class Data(val event: Webchannel.WebChannelEvent) : RealtimeEvent+}
messages/src/main/java/com/vayunmathur/messages/gvoice/Utf16ChunkReader.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/Utf16ChunkReader.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/Utf16ChunkReader.ktnew file mode 100644index 0000000000..f6fc3d734e--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/Utf16ChunkReader.kt@@ -0,0 +1,146 @@+package com.vayunmathur.messages.gvoice++import io.ktor.utils.io.ByteReadChannel+import io.ktor.utils.io.readAvailable+import java.io.EOFException++/**+ * Reads framed payloads where each frame is `<utf16-length>\n<utf8-bytes>`.+ *+ * Direct port of `pkg/libgv/utf16chunk/chunkreader.go` from+ * mautrix-gvoice. Google's BrowserChannel realtime stream frames each+ * server-pushed event as one of these chunks; the length prefix is in+ * UTF-16 code units, not bytes, so surrogate-pair code points count as 2+ * even though they occupy 4 UTF-8 bytes.+ *+ * Reads from a [ByteReadChannel] (the Ktor streaming response body) and+ * exposes a single suspending [readChunk] that returns the next UTF-8+ * payload, or null on EOF.+ */+class Utf16ChunkReader(private val channel: ByteReadChannel) {++    private val buf = ByteArray(32 * 1024)+    private var ptr: Int = 0++    /** Reads one chunk. Returns null at end-of-stream. */+    suspend fun readChunk(): ByteArray? {+        var n = ptr+        var idx = if (ptr != 0) buf.indexOfNewlineUntil(n) else -1+        while (idx == -1 && n < 10) {+            val readN = try {+                channel.readAvailable(buf, ptr, buf.size - ptr)+            } catch (e: EOFException) {+                return null+            }+            if (readN <= 0) {+                if (n == 0) return null+                throw IllegalStateException("EOF before length prefix (have $n bytes)")+            }+            ptr += readN+            n += readN+            idx = buf.indexOfNewlineUntil(n)+        }+        if (idx == -1) error("no newline found in chunk (have $n bytes)")+        var expectedLength = String(buf, 0, idx, Charsets.US_ASCII).trim().toInt()++        val (firstReceivedLength, firstByteCount) =+            utf16Length(buf, idx + 1, n, expectedLength)+        val output = ByteArray(firstByteCount)+        System.arraycopy(buf, idx + 1, output, 0, firstByteCount)++        if (firstReceivedLength >= expectedLength) {+            // Everything fit in the current buffer; shift the remainder+            // forward so the next ReadChunk picks up where we left off.+            val remaining = n - (idx + 1 + firstByteCount)+            if (remaining > 0) System.arraycopy(buf, idx + 1 + firstByteCount, buf, 0, remaining)+            ptr = remaining+            return output+        }++        // Need additional reads to satisfy the full UTF-16 length budget.+        expectedLength -= firstReceivedLength+        val data = java.io.ByteArrayOutputStream(firstByteCount + 4096)+        data.write(output)+        ptr = 0+        while (expectedLength > 0) {+            val readN = channel.readAvailable(buf, 0, buf.size)+            if (readN <= 0) error("EOF mid-chunk (need $expectedLength more code units)")+            val (received, consumed) = utf16Length(buf, 0, readN, expectedLength)+            expectedLength -= received+            data.write(buf, 0, consumed)+            if (consumed < readN) {+                val remaining = readN - consumed+                System.arraycopy(buf, consumed, buf, 0, remaining)+                ptr = remaining+            }+        }+        return data.toByteArray()+    }+}++private fun ByteArray.indexOfNewlineUntil(end: Int): Int {+    for (i in 0 until end) if (this[i] == '\n'.code.toByte()) return i+    return -1+}++/**+ * Count UTF-16 code units in [buf] from [start] (inclusive) until+ * [endExclusive] OR until [maxLength] code units have been counted —+ * whichever comes first. Returns (codeUnitsConsumed, bytesConsumed).+ *+ * Code points in the supplementary plane (>= 0x10000) count as 2 code+ * units (a surrogate pair) even though they occupy 4 UTF-8 bytes.+ */+internal fun utf16Length(+    buf: ByteArray,+    start: Int,+    endExclusive: Int,+    maxLength: Int,+): Pair<Int, Int> {+    var length = 0+    var i = start+    while (i < endExclusive) {+        val first = buf[i].toInt() and 0xFF+        val (codePoint, size) = decodeUtf8At(buf, i, endExclusive, first)+        if (codePoint >= 0x10000) length += 2 else length += 1+        i += size+        if (length >= maxLength) break+    }+    return length to (i - start)+}++/** Decode the UTF-8 code point starting at [pos] in [buf]. Returns the+ *  (codePoint, byteLength). Tolerant of invalid bytes (returns U+FFFD). */+private fun decodeUtf8At(+    buf: ByteArray,+    pos: Int,+    endExclusive: Int,+    firstByte: Int,+): Pair<Int, Int> = when {+    firstByte and 0x80 == 0 -> firstByte to 1+    firstByte and 0xE0 == 0xC0 -> {+        if (pos + 1 >= endExclusive) 0xFFFD to 1+        else {+            val b1 = buf[pos + 1].toInt() and 0x3F+            (((firstByte and 0x1F) shl 6) or b1) to 2+        }+    }+    firstByte and 0xF0 == 0xE0 -> {+        if (pos + 2 >= endExclusive) 0xFFFD to 1+        else {+            val b1 = buf[pos + 1].toInt() and 0x3F+            val b2 = buf[pos + 2].toInt() and 0x3F+            (((firstByte and 0x0F) shl 12) or (b1 shl 6) or b2) to 3+        }+    }+    firstByte and 0xF8 == 0xF0 -> {+        if (pos + 3 >= endExclusive) 0xFFFD to 1+        else {+            val b1 = buf[pos + 1].toInt() and 0x3F+            val b2 = buf[pos + 2].toInt() and 0x3F+            val b3 = buf[pos + 3].toInt() and 0x3F+            (((firstByte and 0x07) shl 18) or (b1 shl 12) or (b2 shl 6) or b3) to 4+        }+    }+    else -> 0xFFFD to 1+}
messages/src/main/java/com/vayunmathur/messages/gvoice/VoiceAuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/VoiceAuthData.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/VoiceAuthData.ktnew file mode 100644index 0000000000..e9cce572c9--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/VoiceAuthData.kt@@ -0,0 +1,43 @@+package com.vayunmathur.messages.gvoice++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Persisted authentication state for a Google Voice session.+ *+ * Voice has no QR-pair or OAuth-token API surface, so this is just a+ * map of the Google session cookies the user pasted at setup time.+ * Persisted to DataStore as a JSON blob under a dedicated key so the+ * gmessages auth state and this don't tread on each other.+ */+@Serializable+data class VoiceAuthData(+    val cookies: Map<String, String>,+) {+    fun hasRequired(): Boolean =+        VoiceEndpoints.RequiredCookies.all { cookies[it]?.isNotBlank() == true }++    suspend fun save(context: Context) {+        DataStoreUtils.getInstance(context).setString(+            DATA_STORE_KEY,+            Json.encodeToString(serializer(), this),+        )+    }++    companion object {+        private const val DATA_STORE_KEY = "gvoice_auth_data"++        suspend fun load(context: Context): VoiceAuthData? {+            val json = DataStoreUtils.getInstance(context).getString(DATA_STORE_KEY) ?: return null+            if (json.isBlank()) return null+            return runCatching { Json.decodeFromString(serializer(), json) }.getOrNull()+        }++        suspend fun clear(context: Context) {+            DataStoreUtils.getInstance(context).setString(DATA_STORE_KEY, "")+        }+    }+}
messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.ktindex 4d05aa8df9..f5851b257d 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -49,7 +49,7 @@ import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.data.MessagesDatabase import com.vayunmathur.messages.util.MessagesSessionManager import com.vayunmathur.messages.util.MessagesViewModel-import com.vayunmathur.messages.gmessages.GMessagesClient+import com.vayunmathur.messages.util.SourceConnectionState import java.text.DateFormat import java.util.Date @@ -91,10 +91,11 @@ fun InboxScreen(                 .padding(padding)                 .fillMaxSize(),         ) {-            // Setup prompt for Messages-for-Web (only source today).+            // Setup prompts for each source.             SetupPrompts(                 states = connectionStates,                 onPairMessages = { backStack.add(Route.PairMessages) },+                onSetupVoice = { backStack.add(Route.LoginVoice) },             )              if (conversations.isEmpty()) {@@ -119,20 +120,16 @@ fun InboxScreen(     } } -/** Shows a source-specific setup card at the top of the inbox when the- *  puppet is in NeedsSetup or Disconnected. */+/** Shows source-specific setup cards at the top of the inbox when+ *  any source needs setup. */ @Composable private fun SetupPrompts(-    states: Map<MessageSource, GMessagesClient.State>,+    states: Map<MessageSource, SourceConnectionState>,     onPairMessages: () -> Unit,+    onSetupVoice: () -> Unit, ) {     val msgsState = states[MessageSource.MESSAGES_WEB]-    // Show the setup card when there's no active pairing. Connected-    // and Pairing both mean "don't bug the user" (Pairing because the-    // pair screen is already up and driving the QR).-    if (msgsState !is GMessagesClient.State.Connected &&-        msgsState !is GMessagesClient.State.Pairing-    ) {+    if (msgsState is SourceConnectionState.NeedsSetup || msgsState is SourceConnectionState.Disconnected) {         SetupCard(             title = stringResource(R.string.inbox_setup_messages_title),             description = stringResource(R.string.inbox_setup_messages_desc),@@ -140,6 +137,15 @@ private fun SetupPrompts(             onAction = onPairMessages,         )     }+    val voiceState = states[MessageSource.VOICE]+    if (voiceState is SourceConnectionState.NeedsSetup || voiceState is SourceConnectionState.Disconnected) {+        SetupCard(+            title = stringResource(R.string.inbox_setup_voice_title),+            description = stringResource(R.string.inbox_setup_voice_desc),+            actionLabel = stringResource(R.string.inbox_setup_voice_action),+            onAction = onSetupVoice,+        )+    } }  @Composable@@ -244,6 +250,7 @@ private fun TypeChip(label: String) { private fun SourceChip(source: MessageSource) {     val (label, color) = when (source) {         MessageSource.MESSAGES_WEB -> "Phone" to MaterialTheme.colorScheme.tertiary+        MessageSource.VOICE -> "Voice" to MaterialTheme.colorScheme.primary     }     Surface(         shape = RoundedCornerShape(8.dp),
messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.ktindex 205e042db3..0b426566a0 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.kt@@ -26,7 +26,7 @@ import com.vayunmathur.messages.Route import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.util.MessagesSessionManager import com.vayunmathur.messages.util.MessagesViewModel-import com.vayunmathur.messages.gmessages.GMessagesClient+import com.vayunmathur.messages.util.SourceConnectionState  @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -56,12 +56,16 @@ fun SettingsScreen(             )             SourceSection(                 title = stringResource(R.string.source_messages),-                state = states[MessageSource.MESSAGES_WEB] ?: GMessagesClient.State.Idle,+                state = states[MessageSource.MESSAGES_WEB] ?: SourceConnectionState.Idle,                 onConfigure = { backStack.add(Route.PairMessages) },-                onDisconnect = {-                    // Clear persisted auth + bounce the session.-                    MessagesSessionManager.stop()-                },+                onDisconnect = { MessagesSessionManager.stop(MessageSource.MESSAGES_WEB) },+            )+            HorizontalDivider(Modifier.padding(vertical = 8.dp))+            SourceSection(+                title = stringResource(R.string.source_voice),+                state = states[MessageSource.VOICE] ?: SourceConnectionState.Idle,+                onConfigure = { backStack.add(Route.LoginVoice) },+                onDisconnect = { MessagesSessionManager.stop(MessageSource.VOICE) },             )             HorizontalDivider(Modifier.padding(vertical = 12.dp))             OutlinedButton(@@ -77,7 +81,7 @@ fun SettingsScreen( @Composable private fun SourceSection(     title: String,-    state: GMessagesClient.State,+    state: SourceConnectionState,     onConfigure: () -> Unit,     onDisconnect: () -> Unit, ) {@@ -97,9 +101,11 @@ private fun SourceSection(     } } -private fun describe(state: GMessagesClient.State): String = when (state) {-    GMessagesClient.State.Idle -> "Not set up"-    is GMessagesClient.State.Pairing -> "Waiting for QR scan…"-    GMessagesClient.State.Connected -> "Connected"-    is GMessagesClient.State.Disconnected -> "Disconnected: ${state.reason}"+private fun describe(state: SourceConnectionState): String = when (state) {+    SourceConnectionState.Idle -> "Not set up"+    is SourceConnectionState.NeedsSetup -> "Setup required"+    is SourceConnectionState.Pairing -> "Waiting for QR scan…"+    SourceConnectionState.Connecting -> "Connecting…"+    SourceConnectionState.Connected -> "Connected"+    is SourceConnectionState.Disconnected -> "Disconnected: ${state.reason}" }
messages/src/main/java/com/vayunmathur/messages/ui/setup/VoiceLoginScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/setup/VoiceLoginScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/setup/VoiceLoginScreen.ktnew file mode 100644index 0000000000..56051d4b1d--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/ui/setup/VoiceLoginScreen.kt@@ -0,0 +1,254 @@+package com.vayunmathur.messages.ui.setup++import android.content.Intent+import android.net.Uri+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Button+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+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.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.messages.R+import com.vayunmathur.messages.Route+import com.vayunmathur.messages.gvoice.CookieParser+import com.vayunmathur.messages.gvoice.GVoiceClient+import com.vayunmathur.messages.gvoice.VoiceEndpoints+import kotlinx.coroutines.launch++/**+ * Cookie-paste sign-in for Google Voice.+ *+ * History (so future-me doesn't re-tread the wrong paths):+ *  - System WebView gets the "Couldn't sign you in, this browser may+ *    not be secure" block. We tried X-Requested-With stripping + UA+ *    spoofing + third-party cookies enablement; still blocked.+ *  - Embedded GeckoView (real Firefox engine) bypasses the block, but+ *    its public StorageController API has no `getCookies` method and+ *    the WebExtension background-script lifecycle is broken for+ *    extensions installed via `ensureBuiltIn` — we couldn't get our+ *    cookie-harvester extension's background.js to actually execute.+ *  - No on-device path for Voice sign-in without Google Play Services+ *    (AccountManager weblogin is GMS-gated).+ *+ * What works: the user signs in to voice.google.com in a browser they+ * already trust, extracts the Google session cookies, and pastes them+ * here. On mobile this means using a browser with cookie-inspection+ * tooling — Kiwi Browser + Cookie-Editor is the cleanest path; Firefox+ * Mobile's about:preferences is a fallback that doesn't require any+ * extension install.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun VoiceLoginScreen(backStack: NavBackStack<Route>) {+    val context = LocalContext.current+    val state by GVoiceClient.state.collectAsState()+    var input by remember { mutableStateOf("") }+    var error by remember { mutableStateOf<String?>(null) }+    var submitting by remember { mutableStateOf(false) }+    val coroutineScope = rememberCoroutineScope()++    LaunchedEffect(state) {+        if (state is GVoiceClient.State.Connected) backStack.pop()+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.setup_voice_title)) },+                navigationIcon = { IconNavigation(backStack) },+            )+        },+    ) { padding ->+        Column(+            modifier = Modifier+                .padding(padding)+                .fillMaxSize()+                .verticalScroll(rememberScrollState())+                .padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(14.dp),+        ) {+            // High-level explainer.+            Text(+                stringResource(R.string.setup_voice_intro),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )++            // Cards for each viable sign-in path. Listed easiest-first.+            InstructionCard(+                title = "Mobile: Kiwi Browser + cookies.txt",+                steps = listOf(+                    "Install Kiwi Browser (sideload from kiwibrowser.com or grab from F-Droid).",+                    "Open Kiwi → ⋮ → Extensions → from store. Search “cookies.txt” (or “Cookie-Editor”) and install one of them.",+                    "Open voice.google.com in Kiwi and sign in normally.",+                    "Tap the extension icon → export. cookies.txt exports a Netscape-format file; Cookie-Editor → Export → Header String.",+                    "Long-press the field below and paste whichever you got.",+                ),+                primaryActionLabel = "Open voice.google.com",+                onPrimaryAction = { openInBrowser(context, "https://voice.google.com/signup") },+            )+            InstructionCard(+                title = "Mobile: Firefox Mobile (no extension)",+                steps = listOf(+                    "Open Firefox on your phone and sign in to voice.google.com.",+                    "In Firefox: address bar → about:preferences#privacy → Cookies and Site Data → Manage Data → search “google.com”.",+                    "Tap each of SID, HSID, SSID, APISID, SAPISID in turn. Copy the value and assemble a JSON object below.",+                ),+                primaryActionLabel = "Open voice.google.com",+                onPrimaryAction = { openInBrowser(context, "https://voice.google.com/signup") },+            )+            InstructionCard(+                title = "Desktop: any browser with devtools",+                steps = listOf(+                    "Sign in to voice.google.com in your desktop browser.",+                    "Open DevTools (⌘+Opt+I / F12) → Application → Cookies → https://voice.google.com.",+                    "Copy the values for SID, HSID, SSID, APISID, SAPISID and paste as JSON below.",+                ),+            )++            // The actual paste field — accepts JSON, cURL, or raw Cookie header.+            Text("Paste cookies", fontWeight = FontWeight.SemiBold)+            OutlinedTextField(+                value = input,+                onValueChange = {+                    input = it+                    error = null+                },+                modifier = Modifier+                    .fillMaxWidth()+                    .height(180.dp),+                placeholder = { Text(stringResource(R.string.setup_voice_placeholder)) },+                shape = RoundedCornerShape(12.dp),+                enabled = !submitting,+                textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),+                supportingText = {+                    when {+                        error != null -> Text(error!!, color = MaterialTheme.colorScheme.error)+                        state is GVoiceClient.State.Connecting -> Text("Validating with Google…")+                        else -> Text(stringResource(R.string.setup_voice_field_hint))+                    }+                },+                isError = error != null,+            )+            Spacer(Modifier.height(4.dp))+            Button(+                onClick = {+                    val parsed = CookieParser.parse(input)+                    if (parsed == null) {+                        error = "Couldn't find any Google cookies in that text. " ++                            "Try a JSON object, a cURL command, or a raw Cookie header."+                        return@Button+                    }+                    val missing = CookieParser.missingRequired(parsed)+                    if (missing.isNotEmpty()) {+                        error = "Missing required cookies: " + missing.joinToString(", ") ++                            ". (Required set: " + VoiceEndpoints.RequiredCookies.joinToString(", ") + ".)"+                        return@Button+                    }+                    submitting = true+                    error = null+                    coroutineScope.launch {+                        val errMsg = GVoiceClient.submitCookies(parsed)+                        submitting = false+                        if (errMsg != null) error = errMsg+                        // On success the LaunchedEffect above pops us.+                    }+                },+                enabled = input.isNotBlank() && !submitting,+                modifier = Modifier.fillMaxWidth(),+                contentPadding = PaddingValues(vertical = 14.dp),+            ) {+                if (submitting) {+                    CircularProgressIndicator(+                        modifier = Modifier.height(20.dp),+                        strokeWidth = 2.dp,+                        color = MaterialTheme.colorScheme.onPrimary,+                    )+                } else {+                    Text(stringResource(R.string.setup_voice_sign_in), fontWeight = FontWeight.SemiBold)+                }+            }+        }+    }+}++@Composable+private fun InstructionCard(+    title: String,+    steps: List<String>,+    primaryActionLabel: String? = null,+    onPrimaryAction: (() -> Unit)? = null,+) {+    Card(+        modifier = Modifier.fillMaxWidth(),+        shape = RoundedCornerShape(12.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.surfaceVariant,+        ),+    ) {+        Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            Text(title, fontWeight = FontWeight.SemiBold)+            steps.forEachIndexed { idx, step ->+                Row(verticalAlignment = androidx.compose.ui.Alignment.Top) {+                    Text(+                        "${idx + 1}.",+                        modifier = Modifier.padding(end = 6.dp),+                        style = MaterialTheme.typography.bodySmall,+                        fontWeight = FontWeight.Medium,+                    )+                    Text(step, style = MaterialTheme.typography.bodySmall)+                }+            }+            if (primaryActionLabel != null && onPrimaryAction != null) {+                Spacer(Modifier.height(4.dp))+                OutlinedButton(+                    onClick = onPrimaryAction,+                    modifier = Modifier.fillMaxWidth(),+                ) {+                    Text(primaryActionLabel)+                }+            }+        }+    }+}++/** Launch [url] in whatever browser the user has set as default.+ *  No reliance on a specific package, no Google-services dependencies. */+private fun openInBrowser(context: android.content.Context, url: String) {+    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))+        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+    runCatching { context.startActivity(intent) }+}
messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.ktindex 1decae490d..efde0cc4c3 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesService.kt@@ -17,7 +17,7 @@ import com.vayunmathur.messages.MainActivity import com.vayunmathur.messages.R import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.gmessages.GMEvent-import com.vayunmathur.messages.gmessages.GMessagesClient+import com.vayunmathur.messages.util.SourceConnectionState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -140,7 +140,7 @@ class MessagesService : Service() {         }     } -    private fun buildSyncNotification(states: Map<MessageSource, GMessagesClient.State>): Notification {+    private fun buildSyncNotification(states: Map<MessageSource, SourceConnectionState>): Notification {         val tap = PendingIntent.getActivity(             this, 0,             Intent(this, MainActivity::class.java),@@ -168,12 +168,18 @@ class MessagesService : Service() {         return builder.build()     } -    private fun describeStates(states: Map<MessageSource, GMessagesClient.State>): String {-        val msgsConnected = states[MessageSource.MESSAGES_WEB] is GMessagesClient.State.Connected-        return if (msgsConnected) {-            getString(R.string.notification_sync_text_messages)-        } else {-            getString(R.string.notification_sync_text_none)+    private fun describeStates(states: Map<MessageSource, SourceConnectionState>): String {+        val msgsConnected = states[MessageSource.MESSAGES_WEB] is SourceConnectionState.Connected+        val voiceConnected = states[MessageSource.VOICE] is SourceConnectionState.Connected+        return when {+            msgsConnected && voiceConnected ->+                getString(R.string.notification_sync_text_both)+            msgsConnected ->+                getString(R.string.notification_sync_text_messages)+            voiceConnected ->+                getString(R.string.notification_sync_text_voice)+            else ->+                getString(R.string.notification_sync_text_none)         }     } 
messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.ktindex 2d769e83fd..340442fec2 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -11,6 +11,7 @@ import com.vayunmathur.messages.data.MessagesDatabase import com.vayunmathur.messages.data.buildMessagesDatabase import com.vayunmathur.messages.gmessages.GMEvent import com.vayunmathur.messages.gmessages.GMessagesClient+import com.vayunmathur.messages.gvoice.GVoiceClient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -25,13 +26,13 @@ import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean  /**- * Bridges [GMessagesClient]'s state + event streams into Room writes and- * notification triggers.+ * Bridges [GMessagesClient] + [GVoiceClient]'s state + event streams+ * into the same Room writes and notification triggers.  *- * Replaces the prior WebView-puppet-based session manager. Same- * external API (so the foreground service / UI keep compiling without- * rewiring): [connectionStates] is the per-source state map, [incoming]- * is the new-message fanout for the notification path.+ * [connectionStates] is the per-source unified state map (see+ * [SourceConnectionState]) and [incoming] is the new-message fanout for+ * the notification path. Adding a new source = subscribing to its state+ * + event flow here; no consumer needs to change.  */ object MessagesSessionManager { @@ -43,12 +44,14 @@ object MessagesSessionManager {     private lateinit var appContext: Context     private lateinit var db: MessagesDatabase -    /** Per-source state map. Today there's only MESSAGES_WEB; the map-     *  keeps the same shape the inbox/service expect. */-    private val _connectionStates = MutableStateFlow<Map<MessageSource, GMessagesClient.State>>(-        mapOf(MessageSource.MESSAGES_WEB to GMessagesClient.State.Idle)+    /** Per-source unified connection state. */+    private val _connectionStates = MutableStateFlow<Map<MessageSource, SourceConnectionState>>(+        mapOf(+            MessageSource.MESSAGES_WEB to SourceConnectionState.Idle,+            MessageSource.VOICE to SourceConnectionState.Idle,+        )     )-    val connectionStates: StateFlow<Map<MessageSource, GMessagesClient.State>> =+    val connectionStates: StateFlow<Map<MessageSource, SourceConnectionState>> =         _connectionStates.asStateFlow()      /** Stream of "you just got a new message" events for the service to@@ -56,17 +59,20 @@ object MessagesSessionManager {     private val _incoming = MutableSharedFlow<GMEvent.IncomingMessage>(extraBufferCapacity = 64)     val incoming: SharedFlow<GMEvent.IncomingMessage> = _incoming.asSharedFlow() -    private var stateCollectorJob: Job? = null-    private var eventCollectorJob: Job? = null+    private val collectorJobs = mutableListOf<Job>()      /** Don't fire incoming-message notifications during the initial scan. */-    private val backfillComplete = mutableMapOf(MessageSource.MESSAGES_WEB to false)+    private val backfillComplete = mutableMapOf(+        MessageSource.MESSAGES_WEB to false,+        MessageSource.VOICE to false,+    )      fun init(context: Context) {         if (!initialized.compareAndSet(false, true)) return         appContext = context.applicationContext         db = buildMessagesDatabase(appContext)         GMessagesClient.init(appContext)+        GVoiceClient.init(appContext)         Log.i(TAG, "init")         wireCollectors()     }@@ -76,11 +82,24 @@ object MessagesSessionManager {     fun start() {         if (!initialized.get()) return         GMessagesClient.start()+        GVoiceClient.start()     }      fun stop() {         GMessagesClient.stop()+        GVoiceClient.stop()         backfillComplete[MessageSource.MESSAGES_WEB] = false+        backfillComplete[MessageSource.VOICE] = false+    }++    /** Stop one source independently — used from the per-source+     *  Disconnect button in Settings. */+    fun stop(source: MessageSource) {+        when (source) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.stop()+            MessageSource.VOICE -> GVoiceClient.stop()+        }+        backfillComplete[source] = false     }      suspend fun sendMessage(conversationId: String, body: String): Boolean {@@ -99,7 +118,13 @@ object MessagesSessionManager {                 senderName = null,             )         )-        val ok = GMessagesClient.sendMessage(conversationId, body)+        val ok = when (source) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.sendMessage(conversationId, body)+            // Voice send isn't wired up yet — same stub-and-FAIL path+            // the gmessages send had before the SendMessageRequest+            // builder existed.+            MessageSource.VOICE -> false+        }         db.messageDao().updateState(             pendingId,             if (ok) MessageState.SENT else MessageState.FAILED,@@ -113,8 +138,9 @@ object MessagesSessionManager {      /**      * Bulk-write a backfill batch of messages in ONE transaction.-     * Called by [GMessagesClient] when LIST_MESSAGES returns — saves-     * dozens of separate Flow notifications when populating a thread.+     * Called by the protocol clients when LIST_MESSAGES / GetThread+     * returns — saves dozens of separate Flow notifications when+     * populating a thread.      */     suspend fun bulkUpsertMessages(messages: List<Message>) {         if (messages.isEmpty()) return@@ -123,19 +149,39 @@ object MessagesSessionManager {      fun forceResync() {         GMessagesClient.forceResync()+        GVoiceClient.forceResync()+    }++    fun fetchMessages(conversationId: String) {+        when (sourceFor(conversationId)) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.fetchMessages(conversationId)+            MessageSource.VOICE -> GVoiceClient.fetchMessages(conversationId)+            null -> Unit+        }     }      private fun wireCollectors() {-        stateCollectorJob?.cancel()-        stateCollectorJob = scope.launch {+        collectorJobs.forEach { it.cancel() }+        collectorJobs.clear()++        collectorJobs += scope.launch {             GMessagesClient.state.collect { s ->-                _connectionStates.value = _connectionStates.value + (MessageSource.MESSAGES_WEB to s)+                _connectionStates.value =+                    _connectionStates.value + (MessageSource.MESSAGES_WEB to s.toUnified())             }         }-        eventCollectorJob?.cancel()-        eventCollectorJob = scope.launch {+        collectorJobs += scope.launch {+            GVoiceClient.state.collect { s ->+                _connectionStates.value =+                    _connectionStates.value + (MessageSource.VOICE to s.toUnified())+            }+        }+        collectorJobs += scope.launch {             GMessagesClient.events.collect { handleEvent(it) }         }+        collectorJobs += scope.launch {+            GVoiceClient.events.collect { handleEvent(it) }+        }     }      private suspend fun handleEvent(event: GMEvent) {@@ -198,6 +244,7 @@ object MessagesSessionManager {      private fun sourceFor(conversationId: String): MessageSource? = when {         conversationId.startsWith("${MessageSource.MESSAGES_WEB.idPrefix}:") -> MessageSource.MESSAGES_WEB+        conversationId.startsWith("${MessageSource.VOICE.idPrefix}:") -> MessageSource.VOICE         else -> null     } }
messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.ktindex bcba735385..86692dcfc2 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt@@ -4,7 +4,6 @@ import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.messages.data.MessagesDatabase-import com.vayunmathur.messages.gmessages.GMessagesClient import kotlinx.coroutines.launch  /**@@ -38,7 +37,7 @@ class MessagesViewModel(application: Application) : AndroidViewModel(application     }      fun fetchMessages(conversationId: String) {-        GMessagesClient.fetchMessages(conversationId)+        MessagesSessionManager.fetchMessages(conversationId)     }      fun markRead(conversationId: String) {
messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt b/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.ktnew file mode 100644index 0000000000..db776ab4aa--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/util/SourceConnectionState.kt@@ -0,0 +1,41 @@+package com.vayunmathur.messages.util++import com.vayunmathur.messages.gmessages.GMessagesClient+import com.vayunmathur.messages.gvoice.GVoiceClient++/**+ * Source-agnostic connection state.+ *+ * Both [GMessagesClient] and [GVoiceClient] have their own internal state+ * machines that share the same conceptual phases (idle / awaiting-setup /+ * connecting / connected / disconnected). This sealed type collapses+ * them so the UI + notification path can treat both sources uniformly,+ * without `when (source)` casts to the source-specific state class.+ */+sealed interface SourceConnectionState {+    data object Idle : SourceConnectionState+    /** Awaiting user setup. [setupHint] is a tiny inline action label+     *  the inbox uses ("Set up", "Sign in", etc). */+    data class NeedsSetup(val setupHint: String) : SourceConnectionState+    /** Active setup-in-progress with a QR code to render (Messages-for-Web+     *  only). */+    data class Pairing(val qrUrl: String) : SourceConnectionState+    data object Connecting : SourceConnectionState+    data object Connected : SourceConnectionState+    data class Disconnected(val reason: String) : SourceConnectionState+}++fun GMessagesClient.State.toUnified(): SourceConnectionState = when (this) {+    GMessagesClient.State.Idle -> SourceConnectionState.NeedsSetup("Set up")+    is GMessagesClient.State.Pairing -> SourceConnectionState.Pairing(qrUrl)+    GMessagesClient.State.Connected -> SourceConnectionState.Connected+    is GMessagesClient.State.Disconnected -> SourceConnectionState.Disconnected(reason)+}++fun GVoiceClient.State.toUnified(): SourceConnectionState = when (this) {+    GVoiceClient.State.Idle -> SourceConnectionState.Idle+    GVoiceClient.State.NeedsSetup -> SourceConnectionState.NeedsSetup("Sign in")+    GVoiceClient.State.Connecting -> SourceConnectionState.Connecting+    GVoiceClient.State.Connected -> SourceConnectionState.Connected+    is GVoiceClient.State.Disconnected -> SourceConnectionState.Disconnected(reason)+}
messages/src/main/proto/account.proto
diff --git a/messages/src/main/proto/account.proto b/messages/src/main/proto/account.protonew file mode 100644index 0000000000..493ad4c1f0--- /dev/null+++ b/messages/src/main/proto/account.proto@@ -0,0 +1,208 @@+syntax = "proto3";+package account;+option go_package = "../gvproto";++message Account {+    string primaryDestinationID = 1;+    repeated Phone phones = 3;+    Communication communication = 4;+    //Integration integration = 6;+    //ClientAccess clientAccess = 7;+    //Promos promos = 8;+    //Accessibility accessibility = 9;+    //Status status = 10;+    //DisplayHints displayHints = 11;+    //Address address = 12;+    AccountVersion version = 13;+    //InboxSupport inboxSupport = 14;+    //Feedback feedback = 15;+}++message AccountVersion {+    string versionToken = 1;+}++enum ClientType {+    UNKNOWN_CLIENT_TYPE = 0;+    GV_WEB = 3;+}++enum ClientSetting {+    UNKNOWN_CLIENT_SETTING = 0;+    DISABLED = 1;+    ENABLED = 2;+}++enum ApplicabilityLevel {+    UNKNOWN_APPLICABILITY_LEVEL = 0;+    APPLICABLE = 1;+    NOT_APPLICABLE_HIDDEN = 2;+}++enum SupportLevel {+    UNKNOWN_SUPPORT_LEVEL = 0;+    SUPPORTED_FOR_ACCOUNT = 1;+    UNSUPPORTED_FOR_ACCOUNT = 2;+}++message Communication {+    message DoNotDisturb {+        message ApplicabilityMask {+            bool enabled = 1;+        }++        message ApplicabilityLevels {+            ApplicabilityLevel enabled = 1;+            ApplicabilityLevel expiration = 2;+            ApplicabilityLevel enableDndOutsideWorkHours = 3;+            ApplicabilityLevel enableDndOutOfOffice = 4;+            ApplicabilityLevel dndReason = 5;+            ApplicabilityLevel allLines = 6;+            ApplicabilityLevel directLines = 7;+            ApplicabilityLevel allRgLines = 8;+        }++        bool enabled = 1;+        bool enableDndOutsideWorkHours = 2;+        bool enableDndOutOfOffice = 3;+        //DndReason dndReason = 4 or 5;+        //unknown unknown = 5 or 4;+        //InvertedClientSetting allLines = 6;+        //InvertedClientSetting directLines = 7;+        //InvertedClientSetting allRgLines = 8;+        ApplicabilityMask applicabilityMask = 202;+        ApplicabilityLevels applicabilityLevels = 203;+    }++    message Transcription {+        message ApplicabilityMask {+            bool enableForVoicemail = 1;+            bool consentsToMachineAnalysis = 2;+        }++        message ApplicabilityLevels {+            ApplicabilityLevel enableForVoicemail = 1;+            ApplicabilityLevel consentsToMachineAnalysis = 2;+        }++        bool enableForVoicemail = 1;+        bool consentsToMachineAnalysis = 2;+        ApplicabilityMask applicabilityMask = 202;+        ApplicabilityLevels applicabilityLevels = 203;+    }++    message SupportedActions {+        message ApplicabilityLevels {+            ApplicabilityLevel useHangoutsForCalling = 8;+        }++        bool clickToCall = 1;+        SupportLevel sendSMS = 2;+        bool interceptAndroidDialerCalling = 3;+        SupportLevel makeEmergencyVoIPCall = 4;+        repeated string emergencyVoIPCallSupportedCountries = 5;+        SupportLevel makeShortCodeProxyCall = 6;+        SupportLevel transferCall = 7;+        SupportLevel useHangoutsForCalling = 8;+        SupportLevel allowAllShortCodeDialing = 9;+        SupportLevel allowArbitraryPhoneNumberDialing = 10;+        //AllowTransferCallingSupportLevel allowTransferCalling = 11;++        ApplicabilityLevels applicabilityLevels = 203;+    }++    bool enableGlobalSpamFiltering = 1;+    DoNotDisturb doNotDisturb = 2;+    Transcription transcription = 3;+    SupportedActions supportedActions = 4;+    //MessagingSupport messagingSupport = 5;+    bool enableInCallCommands = 6;+    //EmailForwardingModalities emailForwardingModalities = 8;+    //CallScreening callScreening = 9;+    string defaultOutgoingNumberRegionCode = 10;+    //VoicemailGreeting voicemailGreeting = 11;+    //VoIP voip = 12;+    //EmergencyCallbackMode emergencyCallbackMode = 13;+    bool enableAnonymousOutboundCalls = 14;+    bool useDestinationIDAsCallerID = 15;+    PhoneNumber defaultOutboundCallerID = 16;+    //AnotherSupportLevel manageInboundCallRules = 17;+    //VoicemailAccess voicemailAccess = 18;+    //ApplicabilityMask applicabilityMask = 202;+    //ApplicabilityLevels applicabilityLevels = 203;+}++message Phone {+    AccountPhone accountPhone = 1;+    LinkedPhoneRestrictions linkedPhoneRestrictions = 4;+    repeated LinkedVoIPDevice linkedVoIPDevices = 5;+    DefaultVoIPSettings defaultVoIPSettings = 6;+    repeated CallAsPhone callAsPhone = 7;+    bool signupForNewNumber = 8;+    bool eligibleForSelfSignup = 9;+    bool eligibleForAdminSignup = 10;+}++message LinkedPhoneRestrictions {+    message CountryWhitelist {+        repeated string regionCode = 1;+    }+    CountryWhitelist countryWhitelist = 1;+}++message LinkedVoIPDevice {+    string SIPDeviceID = 1;+    ClientType clientType = 2;+    string name = 3;+    // TODO forwardingModalities+    ClientSetting inboundCalls = 6;+    ClientSetting outboundCalls = 7;+    // TODO modifiabilityMask+    // TODO availableUpdateActions+}++message DefaultVoIPSettings {+    ClientSetting preferVoIP = 1;+}++message CallAsPhone {+    enum DisplayHint {+        UNKNOWN_DISPLAY_HINT = 0;+        DIRECT = 3;+    }+    PhoneNumber phoneNumber = 1;+    bool initialSelection = 2;+    DisplayHint displayHint = 4;+}++message AccountPhone {+    enum Branding {+        UNKNOWN_BRANDING = 0;+        GOOGLE_VOICE = 1;+    }++    message SupportedActions {+        bool remove = 1;+        bool transfer = 2;+        bool change = 3;+        bool lock = 4;+        bool unlock = 5;+    }++    message ApplicabilityLevels {+        ApplicabilityLevel defaultForOutboundCommunications = 2;+        ApplicabilityLevel expirationTime = 5;+        ApplicabilityLevel isPermanent = 6;+    }++    PhoneNumber phoneNumber = 1;+    bool defaultForOutboundCommunications = 2;+    Branding branding = 3;+    SupportedActions supportedActions = 4;+    bool isPermanent = 6;+    ApplicabilityLevels applicabilityLevels = 203;+}++message PhoneNumber {+    string e164 = 1;+}
messages/src/main/proto/contacts.proto
diff --git a/messages/src/main/proto/contacts.proto b/messages/src/main/proto/contacts.protonew file mode 100644index 0000000000..a2a1299616--- /dev/null+++ b/messages/src/main/proto/contacts.proto@@ -0,0 +1,106 @@+syntax = "proto3";+package contacts;+option go_package = "../gvproto";++message ContactID {+    string phone = 2;+}++message ContactSourceID {+    string profileID = 1;+    string contactID = 2;+}++message ContactPhone {+    string displayValue = 1;+    string canonicalValue = 2;+    string originalValue = 3;+}++message ContactEmail {+    string email = 1;+}++message ContactDisplayInfo {+    message Photo {+        enum Type {+            UNKNOWN_TYPE = 0;+            MONOGRAM = 1;+            USER_SPECIFIED = 3;+        }++        string URL = 1;+        Type type = 2;+    }++    message Name {+        enum SourceType {+            UNKNOWN_SOURCE_TYPE = 0;+            CONTACT = 2;+        }++        string value = 1;+        string givenName = 2;+        SourceType sourceType = 4;+    }++    Photo photo = 1;+    Name name = 2;+    Affinity affinity = 3;+    bool primary = 4;+}++message StructuredPhone {+    enum ValidationResult {+        IS_POSSIBLE = 0;+    }++    message I18nData {+        string nationalNumber = 1;+        string internationalNumber = 2;+        int32 countryCode = 3;+        string regionCode = 4;+        bool isValid = 5;+        ValidationResult validationResult = 6;+    }++    message Phone {+        string e164 = 1;+        I18nData i18nData = 2;+    }++    Phone phone = 1;+    string type = 3;+}++message PhoneExtendedData {+    StructuredPhone structuredPhone = 1;+}++message PeopleStackFieldExtendedData {+    PhoneExtendedData phoneExtendedData = 2;+}++message ContactMethod {+    ContactDisplayInfo displayInfo = 1;+    ContactEmail email = 2;+    ContactPhone phone = 3;+    repeated ContactSourceID sourceIDs = 5;+    bool isPersonal = 8;+    PeopleStackFieldExtendedData extendedData = 9;+    string typeLabel = 10;+}++message Affinity {+    string loggingID = 1;+    double value = 2;+}++message Person {+    repeated ContactMethod contactMethods = 1;+    Affinity affinity = 2;+}++message PersonWrapper {+    Person person = 1;+}
messages/src/main/proto/requests.proto
diff --git a/messages/src/main/proto/requests.proto b/messages/src/main/proto/requests.protonew file mode 100644index 0000000000..e8fb20855d--- /dev/null+++ b/messages/src/main/proto/requests.proto@@ -0,0 +1,89 @@+syntax = "proto3";+package requests;+option go_package = "../gvproto";++import "threads.proto";+import "contacts.proto";++message ReqGetAccount {+    int32 unknownInt2 = 2; // 1+}++message ReqSendSMS {+    message WrappedTxnID {+        int64 ID = 1;+    }++    message TrackingData {+        string data = 1;+    }++    message Media {+        enum Type {+            UNKNOWN_TYPE = 0;+            JPEG = 1;+            PNG = 2;+            TIFF = 3;+            GIF = 4;+            BMP = 5;+            WEBP = 6;+        }+        Type type = 1;+        bytes data = 2;+        string URL = 4;+    }++    string text = 5;+    string threadID = 6;+    repeated string recipients = 7;+    WrappedTxnID transactionID = 9;+    Media media = 10;+    TrackingData trackingData = 11;+}++message UnknownWrapper {+    int32 unknownInt2 = 2; // 1+    int32 unknownInt3 = 3; // 1+}++message ReqListThreads {+    threads.ThreadFolder folder = 1;+    int32 unknownInt2 = 2; // 10 or 20+    int32 unknownInt3 = 3; // 15+    string versionToken = 5;+    UnknownWrapper unknownWrapper = 6;+}++message ReqGetThread {+    string threadID = 1;+    int32 maybeMessageCount = 2; // 100+    string paginationToken = 3;+    UnknownWrapper unknownWrapper = 4;+}++message ReqGetThreadingInfo {++}++message ReqUpdateAttributes {+    threads.ThreadAttributes attributes = 1;+    threads.ThreadAttributes otherAttributes = 2;+    int32 unknownInt = 3;+}++message ReqDeleteThread {+    string threadID = 1;+}++message ReqAutocompleteContacts {+    int32 unknownInt1 = 1; // 243+    string query = 2;+    repeated int32 unknownInts3 = 3; // 1,2+    int32 maxResults = 4; // 15 or 500+}++message ReqLookupContacts {+    int32 unknownInt1 = 1; // 243+    repeated int32 unknownInts2 = 2; // 1,2+    repeated contacts.ContactID targets = 3;+}
messages/src/main/proto/responses.proto
diff --git a/messages/src/main/proto/responses.proto b/messages/src/main/proto/responses.protonew file mode 100644index 0000000000..f8812f70b9--- /dev/null+++ b/messages/src/main/proto/responses.proto@@ -0,0 +1,78 @@+syntax = "proto3";+package responses;+option go_package = "../gvproto";++import "threads.proto";+import "account.proto";+import "contacts.proto";++message RespGetThread {+    threads.Thread thread = 1;+}++message RespListThreads {+    repeated threads.Thread threads = 1;+    string versionToken = 3;+}++message RespSendSMS {+    string threadID = 2;+    string threadItemID = 3;+    int64 timestampMS = 4;+    repeated threads.ThreadFolder threadFolders = 5;+}++message RespUpdateAttributes {+    threads.ThreadAttributes attributes = 1;+}++message RespBatchUpdateAttributes {+    RespUpdateAttributes items = 1;+}++message RespGetAccount {+    account.Account account = 1;+}++message RespDeleteThread {++}++message RespAutocompleteContacts {+    message AffinityResponseContext {+        message Feature {+            enum Type {+                UNKNOWN_TYPE = 0;+                IS_CONTACT_STARRED = 6;+                HAS_POSTAL_ADDRESS = 7;+                HAS_NICKNAME = 8;+                HAS_AVATAR = 11;+                NUM_RAW_CONTACTS = 16;+            }++            Type type = 1;+            double weight = 2;+            double exponent = 3;+        }+        int32 affinityVersion = 1;+        repeated Feature features = 3;+    }++    repeated contacts.PersonWrapper results = 1;+    AffinityResponseContext affinityResponseContext = 2;+}++message RespLookupContacts {+    message Match {+        enum FailureType {+            NO_FAILURE = 0;+            PERMANENT = 1;+        }++        contacts.ContactID ID = 1;+        contacts.PersonWrapper autocompletion = 2;+        FailureType failureType = 3;+    }++    repeated Match matches = 1;+}
messages/src/main/proto/threads.proto
diff --git a/messages/src/main/proto/threads.proto b/messages/src/main/proto/threads.protonew file mode 100644index 0000000000..0e3c102153--- /dev/null+++ b/messages/src/main/proto/threads.proto@@ -0,0 +1,156 @@+syntax = "proto3";+package threads;+option go_package = "../gvproto";++enum ThreadFolder {+    UNKNOWN_THREAD_FOLDER = 0;+    ALL_THREADS = 1;+    TEXT_THREADS = 2;+    ALL_CALL_THREADS = 3; // uncertain+    ALL_VOICEMAIL_THREADS = 4; // uncertain+    ALL_SPAM_THREADS = 5; // uncertain+    ALL_ARCHIVED_THREADS = 6;+}++enum ContactSpammerStatus {+    UNKNOWN_CONTACT_SPAMMER_STATUS = 0;+    USER_UNMARKED_SPAM = 4;+}++message Thread {+    string ID = 1;+    bool read = 2;+    repeated Message messages = 3;+    string paginationToken = 4;+    repeated Contact contacts = 5;+    repeated ThreadFolder folders = 6;+    bool isText = 8;+    repeated string phoneNumbers = 9;+    repeated Contact suspectedSpamContacts = 12;+}++message ThreadAttributes {+    string threadID = 1;+    bool isBlocked = 2;+    bool isSpammer = 3;+    bool read = 4;+    repeated ThreadFolder folders = 5;+    bool archived = 6;+    string groupName = 7;+    ContactSpammerStatus contactSpammerStatus = 8;+}++message Message {+    enum Type {+        MISSED_CALL = 0;+        INCOMING_CALL = 1;+        VOICEMAIL = 2;+        OUTGOING_CALL = 7;+        SMS_IN = 10;+        SMS_OUT = 11;+        OUTGOING_CALL_CANCELLED = 14;+    }+    enum CoarseType {+        CALL_TYPE_MISSED = 0;+        CALL_TYPE_INCOMING = 1;+        CALL_TYPE_OUTGOING = 2;+        CALL_TYPE_VOICEMAIL = 3;+        CALL_TYPE_SMS_IN = 5;+        CALL_TYPE_SMS_OUT = 6;+    }++    enum Status {+        UNREAD = 0;+        READ = 1;+    }++    enum TranscriptStatus {+        UNKNOWN_STATUS = 0;+        RECEIVED = 1;+    }++    message UserFeedback {+        enum Status {+            UNKNOWN_STATUS = 0;+            NOT_APPLICABLE = 1;+        }++        Status status = 2;+    }++    message Transcript {+        float confidence = 1;+        repeated TranscriptToken tokens = 2;+    }++    message TranscriptToken {+        bytes text = 1;+        float confidence = 4;+    }++    string ID = 1;+    int64 timestamp = 2;+    string destinationID = 3;+    Contact contact = 4;+    Type type = 5;+    Status status = 6;+    Transcript transcript = 7;+    float durationSeconds = 9;+    string text = 10;+    string mediaURL = 12;+    CoarseType coarseType = 13;+    TranscriptStatus transcriptStatus = 14;+    MMSMessage MMS = 15;+    string phoneNumberKeyToThreadContact = 16;+    bool isArtificialErrorMessage = 17;+    int64 transactionID = 18;+    UserFeedback userFeedback = 19;+}++message MMSMessage {+    string text = 1;+    string subject = 2;+    repeated Attachment attachments = 3;+    repeated Contact participants = 4;+    string senderPhoneNumber = 5;+    repeated string phoneNumberKeyToThreadContact = 6;+}++message Attachment {+    enum Status {+        UNKNOWN_STATUS = 0;+        AVAILABLE = 1;+        NOT_SUPPORTED = 3;+    }++    enum MediaType {+        UNKNOWN_TYPE = 0;+        PHOTO = 3;+    }++    message Metadata {+        enum SizeSpec {+            UNKNOWN = 0;+            ORIGINAL = 1;+            S128 = 2;+            S512 = 3;+            S1280 = 4;+        }++        SizeSpec size = 1;+        int32 width = 2;+        int32 height = 3;+    }++    string mimeType = 1;+    string ID = 2;+    Status status = 3;+    repeated Metadata metadata = 4;+    MediaType mediaType = 5;+}++message Contact {+    string name = 1;+    string phoneNumber = 2;+    bool blocked = 7;+}
messages/src/main/proto/waa.proto
diff --git a/messages/src/main/proto/waa.proto b/messages/src/main/proto/waa.protonew file mode 100644index 0000000000..8cc7c56c06--- /dev/null+++ b/messages/src/main/proto/waa.proto@@ -0,0 +1,34 @@+syntax = "proto3";+package waa;+option go_package = "../gvproto";++message ReqCreateWaa {+    string requestKey = 1;+}++message ReqPingWaa {+    string requestKey = 1;+    string payload = 2;+    int64 i1 = 3;+    int64 i2 = 4;+}++message RespCreateWaa {+    CreatedWaa waa = 1;+}++message RespPingWaa {+}++message CreatedWaa {+    message InterpreterURL {+        string URL = 4;+    }++    string respID = 1;+    // When using binary protobuf, these are offset down by 1 and there's no respID+    InterpreterURL interpreterURL = 3;+    string interpreterHash = 4;+    string program = 5;+    string globalName = 6;+}
messages/src/main/proto/webchannel.proto
diff --git a/messages/src/main/proto/webchannel.proto b/messages/src/main/proto/webchannel.protonew file mode 100644index 0000000000..52a85c87a9--- /dev/null+++ b/messages/src/main/proto/webchannel.proto@@ -0,0 +1,89 @@+syntax = "proto3";+package webchannel;+option go_package = "../gvproto";++message RespChooseServer {+    string gSessionID = 1;+    int32 unknownInt = 2; // 3+}++message RespCreateChannel {+    WebChannelSessionData data = 1;+}++message WebChannelSessionData {+    int32 field1 = 1; // 0+    WebChannelSession session = 2;+}++message WebChannelSession {+    string field1 = 1; // "c"?+    string sessionID = 2;+    string field3 = 3; // empty string+    uint32 field4 = 4; // 8, version?+    uint32 field5 = 5; // 12, ???+    uint32 pingInterval = 6; // 30000+}++message WebChannelEvent {+    uint64 arrayID = 1;+    repeated WebChannelEventDataWrapper data_wrapper = 2;+}++message WebChannelNoopEvent {+    uint64 arrayID = 1;+    repeated string noop = 2;+}++message WebChannelEventDataWrapper {+    message AltData {+        bool reconnect = 1;+    }++    // TODO this may also be the string "noop"+    repeated WebChannelEventData data = 1;+    AltData altData = 2;+}++message WebChannelEventData {+    string eventSource = 1; // Seems to be 1, 2, 3, 4, 5, 6 or 9. Same as the create channel reqX___data__'s+    Event event = 2;+}++message Event {+    EventSub1 sub1 = 1;+    EventSub2 sub2 = 2;+    EventSub3 sub3 = 3;+}++message Empty {}++message EventSub1 {+    string unknown1 = 1;+}++message EventSub2 {+    repeated EventSub2Data data = 1;+}++message EventSub2Data {+    message NestedData {+        string ts1 = 1;+        string ts2 = 2;+        string ts3 = 3;+        string ts4 = 4;+        string ts5 = 5;+        string ts6 = 6;+        string ts7 = 7;+        string ts9 = 9;+    }+    bytes unknownBytes = 2;+    string unknownTimestampMillis = 3;+    string unknownTimestampMicros = 4;+    NestedData unknownNestedData = 5;+    // 5 has a nested value of some kind+}++message EventSub3 {+    string unknownTimestamp = 1;+}
messages/src/main/res/values/strings.xml
diff --git a/messages/src/main/res/values/strings.xml b/messages/src/main/res/values/strings.xmlindex 5296993270..e1e0a28c98 100644--- a/messages/src/main/res/values/strings.xml+++ b/messages/src/main/res/values/strings.xml@@ -9,6 +9,7 @@     <string name="inbox_setup_messages_desc">Pair with your phone\'s Google Messages app to see your SMS conversations here.</string>     <string name="inbox_setup_voice_title">Sign in to Google Voice</string>     <string name="inbox_setup_voice_desc">Sign in to your Google Voice number to see messages sent to it.</string>+    <string name="inbox_setup_voice_action">Sign in</string>     <string name="inbox_setup_action">Set up</string>     <string name="inbox_repair_messages">Phone pairing expired — tap to re-pair</string>     <string name="inbox_relogin_voice">Voice sign-in expired — tap to sign in again</string>@@ -23,6 +24,10 @@     <string name="setup_messages_title">Pair Google Messages</string>     <string name="setup_messages_hint">On your phone, open Google Messages, tap the menu, then \"Device pairing\", and scan the QR code below.</string>     <string name="setup_voice_title">Sign in to Google Voice</string>+    <string name="setup_voice_intro">Google blocks embedded sign-ins to voice.google.com from inside other apps, so we can\'t open a normal sign-in form here. The workaround: sign in via a real desktop browser and paste your session cookies below.</string>+    <string name="setup_voice_placeholder">{\"SID\":\"…\",\"HSID\":\"…\",\"SSID\":\"…\",\"APISID\":\"…\",\"SAPISID\":\"…\"}</string>+    <string name="setup_voice_field_hint">JSON, cookies.txt (Netscape), cURL command, or raw Cookie header.</string>+    <string name="setup_voice_sign_in">Sign in</string>     <string name="setup_done">Done</string>     <string name="setup_back">Back</string>