communicate: various fixes for gvoice
- Commit
4c88dff2a034d5c55e11276d1c233588833e4d71- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 21:09 UTC (3 months ago)
- Parents
4b4ecbb
Diff
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 35e4956674..92d4585932 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -16,6 +16,8 @@ dependencies { // Google Voice virtual line: protojson RPCs + SIP-over-WSS transport go through // the repo's own Android-only HTTP/WebSocket stack (no OkHttp/Ktor). implementation(project(":library:network"))+ // Local Compose image loading for Google Voice MMS previews (remote https + content://).+ implementation(project(":library:image")) // Maintained prebuilt WebRTC (org.webrtc.*) for the calling audio session. implementation(libs.stream.webrtc.android) // E.164 normalization to reconcile SIM vs Google Voice numbers.
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 7d5f8b3c03..c257bf408c 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -21,8 +21,10 @@ <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" /> <uses-feature android:name="android.hardware.telephony"@@ -140,6 +142,11 @@ </intent-filter> </service> + <service+ android:name=".telephony.GoogleVoiceSyncService"+ android:exported="false"+ android:foregroundServiceType="remoteMessaging" />+ <service android:name=".telephony.GoogleVoiceCallForegroundService" android:exported="false"
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex d18ac1698f..0013640e87 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -1,5 +1,8 @@ package com.vayunmathur.communicate +import android.Manifest+import android.content.pm.PackageManager+import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent@@ -23,6 +26,7 @@ import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.communicate.data.googlevoice.call.CallPhase import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import com.vayunmathur.communicate.telephony.GoogleVoiceSyncService import com.vayunmathur.communicate.telephony.GoogleVoiceTelecom import com.vayunmathur.communicate.ui.AccountsScreen import com.vayunmathur.communicate.ui.CallLogsScreen@@ -57,12 +61,22 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) enableEdgeToEdge() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+ checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED+ ) {+ requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_POST_NOTIFICATIONS)+ }+ setContent { DynamicTheme { CommunicateApp() } } }++ companion object {+ private const val REQUEST_POST_NOTIFICATIONS = 1001+ } } @Composable@@ -72,13 +86,16 @@ private fun CommunicateApp() { val gvSignedIn by session.signedInFlow.collectAsState(initial = false) val callState by GoogleVoiceCallManager.state.collectAsState() - // Make Google Voice a selectable line and route inbound SIP INVITEs to the system.+ // Keep the Telecom account fresh, but let the foreground service own always-on receive state. LaunchedEffect(gvSignedIn) { GoogleVoiceCallManager.init(context) GoogleVoiceCallManager.onIncomingCall = { from -> GoogleVoiceTelecom.addIncoming(context, from) } if (gvSignedIn) { val number = session.phoneNumber() ?: context.getString(R.string.account_google_voice) GoogleVoiceTelecom.registerPhoneAccount(context, number)+ GoogleVoiceSyncService.start(context)+ } else {+ GoogleVoiceSyncService.stop(context) } }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex a327368287..400f70a5a8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -13,6 +13,7 @@ import android.telecom.PhoneAccount import android.telecom.TelecomManager import androidx.core.content.ContextCompat import androidx.core.net.toUri+import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceWebSender@@ -321,15 +322,25 @@ object CommunicateRepository { address: String, body: String, threadRemoteId: String? = null,+ attachments: List<CommunicateAttachment> = emptyList(), ): Boolean = when (choice) {- is LineChoice.Sim -> sendSimSms(context, choice.subscriptionId, address, body)+ is LineChoice.Sim -> if (attachments.isEmpty()) {+ sendSimSms(context, choice.subscriptionId, address, body)+ } else {+ false+ } LineChoice.GoogleVoice -> runCatching { // The bot-defense token is minted invisibly in an offscreen WebView; the app then- // builds and sends the sendsms API call itself using that token.+ // builds and sends the sendsms API call itself using that token. For MMS, let the+ // real web composer upload media and build the media-bearing body, then replay it. val activity = context as? android.app.Activity ?: return@runCatching false- val token = GoogleVoiceWebSender.mintToken(activity, address, body) ?: return@runCatching false- val sendBody = com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser- .buildSendSmsBody(address, body, threadRemoteId, botToken = token)+ val sendBody = if (attachments.isEmpty()) {+ val token = GoogleVoiceWebSender.mintToken(activity, address, body) ?: return@runCatching false+ com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+ .buildSendSmsBody(address, body, threadRemoteId, botToken = token)+ } else {+ GoogleVoiceWebSender.mintPreparedBody(activity, address, body, attachments) ?: return@runCatching false+ } GoogleVoiceClient.get(context).sendPreparedSms(sendBody) true }.getOrDefault(false)@@ -400,7 +411,7 @@ object CommunicateRepository { threadId = stableThreadId(id), address = phoneNumber, displayName = displayName ?: findContactName(context, phoneNumber),- snippet = snippet,+ snippet = snippet.ifBlank { if (messages.any { it.hasMedia }) context.getString(R.string.gv_media_message) else "" }, timestampMillis = timestampMillis, unreadCount = unreadCount, line = CommunicateLine.GoogleVoice,@@ -411,7 +422,7 @@ object CommunicateRepository { id = ("$threadId#$id").hashCode().toLong(), threadId = threadId, address = phoneNumber,- body = text,+ body = text.ifBlank { if (hasMedia) context.getString(R.string.gv_media_message) else "" }, timestampMillis = timestampMillis, outgoing = outgoing, read = read,
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.ktindex 3fefa5d82a..0e061cf315 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt@@ -32,6 +32,7 @@ data class GvMessage( val outgoing: Boolean, val read: Boolean, val mediaUrls: List<String> = emptyList(),+ val hasMedia: Boolean = mediaUrls.isNotEmpty(), ) data class GvThread(
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.ktindex 6f3527c614..e012c0c504 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt@@ -273,14 +273,18 @@ object GoogleVoiceParser { // Direction is the type field: 10 = inbound SMS, 11 = outbound SMS (confirmed from the wire). val type = longAt(ITEM_TYPE) val outgoing = type == 11L+ val mediaUrls = mediaUrlsIn(this)+ val hasMedia = mediaUrls.isNotEmpty() || hasMediaMetadata() return GvMessage( id = strAt(ITEM_ID) ?: "$threadId#$index", threadId = threadId, phoneNumber = counterparty,- text = strAt(ITEM_BODY).orEmpty(),+ text = normalizedBodyText(hasMedia), timestampMillis = ts, outgoing = outgoing, read = true,+ mediaUrls = mediaUrls,+ hasMedia = hasMedia, ) } @@ -294,6 +298,77 @@ object GoogleVoiceParser { return null } + private fun JsonArray.normalizedBodyText(hasMedia: Boolean): String {+ val raw = strAt(ITEM_BODY).orEmpty()+ return if (hasMedia && raw.trim().isMmsStatusLabel()) "" else raw+ }++ private fun String.isMmsStatusLabel(): Boolean = when (trim().lowercase()) {+ "mms sent", "mms received" -> true+ else -> false+ }++ private fun JsonArray.hasMediaMetadata(): Boolean = getOrNull(16)?.let(::hasMediaMetadataIn) == true++ private fun hasMediaMetadataIn(el: JsonElement): Boolean = allStrings(el).any {+ it.looksLikeMimeType() || it.looksLikeAttachmentId()+ }++ private fun String.looksLikeMimeType(): Boolean {+ val lower = trim().lowercase()+ return lower.startsWith("image/") || lower.startsWith("video/") || lower.startsWith("audio/")+ }++ private fun String.looksLikeAttachmentId(): Boolean = Regex("^[A-Za-z0-9_.-]+-\\d+$").matches(trim())++ private fun mediaUrlsIn(item: JsonArray): List<String> {+ val text = item.strAt(ITEM_BODY).orEmpty()+ val knownNonMedia = buildSet {+ item.strAt(ITEM_ID)?.let(::add)+ item.strAt(ITEM_OWN)?.let(::add)+ text.takeIf { it.isNotBlank() }?.let(::add)+ item.strAt(15)?.let(::add)+ }+ return mediaUrlStrings(item)+ .filterNot { it in knownNonMedia }+ .distinct()+ }++ private fun mediaUrlStrings(el: JsonElement): List<String> {+ val out = mutableListOf<String>()+ fun visit(e: JsonElement) {+ when (e) {+ is JsonArray -> e.forEach { visit(it) }+ is JsonObject -> e.values.forEach { visit(it) }+ is JsonPrimitive -> if (e.isString) {+ val url = e.content.trim()+ if (looksLikeMediaUrl(url)) out.add(url)+ }+ }+ }+ visit(el)+ return out+ }++ private fun looksLikeMediaUrl(raw: String): Boolean {+ val lower = raw.lowercase()+ if (!lower.startsWith("https://")) return false+ val isGoogleAttachmentHost = lower.contains("googleusercontent.com") ||+ lower.contains("ggpht.com") ||+ lower.contains("lh3.google.com") ||+ lower.contains("voice.google.com/media")+ if (!isGoogleAttachmentHost) return false+ return lower.contains("=s") ||+ lower.contains("/mms") ||+ lower.contains("/media") ||+ lower.contains("image") ||+ lower.endsWith(".jpg") ||+ lower.endsWith(".jpeg") ||+ lower.endsWith(".png") ||+ lower.endsWith(".gif") ||+ lower.endsWith(".webp")+ }+ private fun recordId(record: JsonArray): String? = (record.firstOrNull() as? JsonPrimitive)?.takeIf { it.isString }?.content
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.ktindex 1afb004429..ba070e3773 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceSession.kt@@ -31,6 +31,13 @@ class GoogleVoiceSession private constructor(private val store: DataStoreUtils) /** The account's Google Voice phone number (from `account/get`), for display + line label. */ suspend fun phoneNumber(): String? = store.getStringAwait(KEY_PHONE_NUMBER) + /** New-message notification watermark; zero means the first background poll should seed it. */+ suspend fun lastSeenMessageTimestampMillis(): Long = store.getLongAwait(KEY_LAST_SEEN_MESSAGE_TS) ?: 0L++ suspend fun setLastSeenMessageTimestampMillis(timestampMillis: Long) {+ store.setLong(KEY_LAST_SEEN_MESSAGE_TS, timestampMillis)+ }+ suspend fun isSignedIn(): Boolean = store.getBooleanAwait(KEY_SIGNED_IN, default = false) /** Reactive sign-in state for UI (Accounts screen, line pickers). */@@ -71,7 +78,7 @@ class GoogleVoiceSession private constructor(private val store: DataStoreUtils) suspend fun signOut() { store.removeKeys(- listOf(KEY_COOKIE, KEY_SAPISID, KEY_API_KEY, KEY_AUTHUSER, KEY_PHONE_NUMBER),+ listOf(KEY_COOKIE, KEY_SAPISID, KEY_API_KEY, KEY_AUTHUSER, KEY_PHONE_NUMBER, KEY_LAST_SEEN_MESSAGE_TS), ) store.setBoolean(KEY_SIGNED_IN, false) }@@ -86,6 +93,7 @@ class GoogleVoiceSession private constructor(private val store: DataStoreUtils) private const val KEY_AUTHUSER = "gv_authuser" private const val KEY_PHONE_NUMBER = "gv_phone_number" private const val KEY_SIGNED_IN = "gv_signed_in"+ private const val KEY_LAST_SEEN_MESSAGE_TS = "gv_last_seen_message_ts" fun get(context: Context): GoogleVoiceSession = GoogleVoiceSession(DataStoreUtils.getInstance(context.applicationContext))
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.ktindex a7dcaa80aa..768d809694 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceWebSender.kt@@ -2,14 +2,18 @@ package com.vayunmathur.communicate.data.googlevoice import android.annotation.SuppressLint import android.app.Activity+import android.net.Uri import android.util.Log import android.view.ViewGroup import android.webkit.CookieManager import android.webkit.JavascriptInterface+import android.webkit.ValueCallback+import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import androidx.webkit.WebViewCompat import androidx.webkit.WebViewFeature+import com.vayunmathur.communicate.data.CommunicateAttachment import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -31,6 +35,9 @@ object GoogleVoiceWebSender { private const val TAG = "GVAUTO" private var webView: WebView? = null+ private var currentRecipient: String = ""+ private var currentText: String = ""+ private var currentAttachments: List<Uri> = emptyList() @Volatile private var pending: CompletableDeferred<String>? = null@@ -45,21 +52,54 @@ object GoogleVoiceWebSender { return GoogleVoiceParser.extractBotToken(body) } + /** Return the full web-constructed sendsms body, including media upload metadata. */+ suspend fun mintPreparedBody(+ activity: Activity,+ recipient: String,+ text: String,+ attachments: List<CommunicateAttachment>,+ ): String? = mintBody(+ activity = activity,+ recipient = recipient,+ text = text,+ attachments = attachments.map { Uri.parse(it.contentUri) },+ )+ /** Drive the offscreen WebView to produce the exact sendsms body (with token). */- private suspend fun mintBody(activity: Activity, recipient: String, text: String): String? {+ private suspend fun mintBody(+ activity: Activity,+ recipient: String,+ text: String,+ attachments: List<Uri> = emptyList(),+ ): String? { val deferred = CompletableDeferred<String>() withContext(Dispatchers.Main) { pending = deferred- val wv = ensureWebView(activity, recipient, text)+ currentRecipient = recipient+ currentText = text+ currentAttachments = attachments+ disposeWebView()+ val wv = ensureWebView(activity) wv.loadUrl("https://voice.google.com/u/0/messages") }- val body = withTimeoutOrNull(60_000) { deferred.await() }- withContext(Dispatchers.Main) { runCatching { webView?.stopLoading() } }+ val body = withTimeoutOrNull(if (attachments.isEmpty()) 60_000 else 120_000) { deferred.await() }+ withContext(Dispatchers.Main) {+ disposeWebView()+ currentAttachments = emptyList()+ } return body } + private fun disposeWebView() {+ val old = webView ?: return+ runCatching { old.stopLoading() }+ runCatching { (old.parent as? ViewGroup)?.removeView(old) }+ runCatching { old.destroy() }+ webView = null+ }+ @SuppressLint("SetJavaScriptEnabled")- private fun ensureWebView(activity: Activity, recipient: String, text: String): WebView {+ private fun ensureWebView(activity: Activity): WebView { webView?.let { return it } CookieManager.getInstance().setAcceptCookie(true) val wv = WebView(activity)@@ -86,9 +126,24 @@ object GoogleVoiceWebSender { } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url)- if (injected || url == null || !url.contains("voice.google.com/u/")) return+ if (url == null || !url.contains("voice.google.com/u/")) return+ if (injected) return injected = true- view?.evaluateJavascript(automationScript(recipient, text), null)+ view?.evaluateJavascript(+ automationScript(currentRecipient, currentText, hasAttachments = currentAttachments.isNotEmpty()),+ null,+ )+ }+ }+ wv.webChromeClient = object : WebChromeClient() {+ override fun onShowFileChooser(+ webView: WebView?,+ filePathCallback: ValueCallback<Array<Uri>>?,+ fileChooserParams: FileChooserParams?,+ ): Boolean {+ Log.d(TAG, "file chooser requested for ${currentAttachments.size} attachment(s)")+ filePathCallback?.onReceiveValue(currentAttachments.toTypedArray())+ return true } } // Place the WebView BEHIND the app's opaque UI: it must lay out on-screen for GV's CDK@@ -157,13 +212,14 @@ object GoogleVoiceWebSender { * the sendsms request. Sequence: open composer โ fill recipient โ fill message โ click the real * "Send message" button (NOT the "Send new message" FAB). Dumps DOM to Logcat for tuning. */- private fun automationScript(recipient: String, text: String): String {+ private fun automationScript(recipient: String, text: String, hasAttachments: Boolean): String { val num = recipient.replace("\"", "") val body = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n")+ val wantsAttachment = if (hasAttachments) "true" else "false" return """ (function(){ function log(m){ try{ AndroidGV.log(""+m);}catch(e){} }- var NUM="$num", TEXT="$body";+ var NUM="$num", TEXT="$body", WANT_ATTACH=$wantsAttachment; function qa(s){ return Array.prototype.slice.call(document.querySelectorAll(s)); } function q(s){ return document.querySelector(s); } function lbl(e){ return (e.getAttribute('aria-label')||'').toLowerCase(); }@@ -177,6 +233,8 @@ object GoogleVoiceWebSender { function type(el,val){ el.focus(); var ok=false; try{ ok=document.execCommand('insertText',false,val);}catch(e){} if(!ok){ if(el.tagName==='TEXTAREA'||el.tagName==='INPUT'){ setNative(el,val);} else { el.textContent=val; el.dispatchEvent(new InputEvent('input',{bubbles:true,data:val,inputType:'insertText'})); } } } function typeReal(el,val){ el.focus(); try{ el.value=''; }catch(e){} for(var i=0;i<val.length;i++){ var ch=val.charAt(i); el.dispatchEvent(new KeyboardEvent('keydown',{bubbles:true,key:ch})); try{ el.value=(el.value||'')+ch; }catch(e){} el.dispatchEvent(new InputEvent('input',{bubbles:true,data:ch,inputType:'insertText'})); el.dispatchEvent(new KeyboardEvent('keyup',{bubbles:true,key:ch})); } el.dispatchEvent(new Event('change',{bubbles:true})); } function enter(el){ ['keydown','keypress','keyup'].forEach(function(t){ el.dispatchEvent(new KeyboardEvent(t,{bubbles:true,key:'Enter',code:'Enter',keyCode:13,which:13})); }); }+ function visibleButtons(){ return qa('button,[role="button"],[aria-label]').filter(vis); }+ function findAttach(){ var bs=visibleButtons(); for(var i=0;i<bs.length;i++){ var l=lbl(bs[i]); if(l.indexOf('attach')>=0||l.indexOf('photo')>=0||l.indexOf('image')>=0||l.indexOf('media')>=0||l.indexOf('mms')>=0) return bs[i]; } var file=q('input[type="file"]'); if(file) return file; return null; } var B=document.body; var step=0; var timer=setInterval(function(){@@ -226,9 +284,17 @@ object GoogleVoiceWebSender { } if(!B.dataset.gvRecip){ log('await recip '+step); return; } if(!B.dataset.gvRecipDone){ log('await recip commit '+step); return; }- // Fill the message once the recipient chip is committed.- if(msg && !B.dataset.gvMsg){ B.dataset.gvMsg='1'; log('fill message ['+fld(msg)+']'); type(msg,TEXT); return; }+ // Fill the message once the recipient chip is committed. MMS can be media-only,+ // but entering text when present helps the web composer enable its final send path.+ if(msg && !B.dataset.gvMsg){ B.dataset.gvMsg='1'; log('fill message ['+fld(msg)+']'); if(TEXT.length>0) type(msg,TEXT); return; } if(!B.dataset.gvMsg){ if(step%4===0) dumpFields('FIELDS@'+step); log('await msg '+step); return; }+ if(WANT_ATTACH && !B.dataset.gvAttach){+ var attach=findAttach();+ if(attach){ B.dataset.gvAttach='1'; log('click attach ['+attach.tagName+' '+lbl(attach)+']'); attach.click(); return; }+ log('await attach '+step+' labels='+JSON.stringify(labels()).slice(0,900)); return;+ }+ if(WANT_ATTACH && !B.dataset.gvAttachWait){ B.dataset.gvAttachWait=String(step); return; }+ if(WANT_ATTACH && (step-(parseInt(B.dataset.gvAttachWait)||step))<6){ log('wait upload '+step); return; } if(send){ var dis=(send.getAttribute('aria-disabled')==='true'||send.disabled); if(!dis){ log('click SEND ['+lbl(send)+']'); send.click(); clearInterval(timer); log('sent-clicked'); return; } else { log('send disabled '+step+' recipVal='+((recip&&(recip.value||recip.textContent))||'')); return; } } log('await send '+step+' recip='+!!recip+' msg='+!!msg); }catch(e){ log('auto err '+e); }
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.ktindex 3f4fda5e14..670af7e24a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/GoogleVoiceCallManager.kt@@ -5,7 +5,9 @@ import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -49,6 +51,7 @@ object GoogleVoiceCallManager { private var gvNumber: String = "" private var remoteNumber: String = "" private var registered = false+ private var registrationJob: Job? = null private var remoteApplied = false private var pendingInviteTarget: String? = null private var pendingInviteSdp: String? = null@@ -77,10 +80,13 @@ object GoogleVoiceCallManager { val offer = a.createOffer() pendingInviteTarget = number pendingInviteSdp = offer- val s = SipClient(info, gvNumber, scope, sipListener())- sip = s+ val s = ensureSipClient(info) s.connect()- s.register()+ if (registered) {+ s.invite(number, offer)+ } else {+ s.register()+ } }.onFailure { android.util.Log.e("GoogleVoiceCall", "placeCall setup failed", it) fail(it.message ?: "call setup failed")@@ -91,20 +97,35 @@ object GoogleVoiceCallManager { /** Connect + register without placing a call, so inbound INVITEs can arrive. */ fun startRegistration() { val ctx = appContext ?: return- if (sip != null) return- scope.launch {+ if (registrationJob?.isActive == true || registered) return+ registrationJob = scope.launch { runCatching { val session = GoogleVoiceSession.get(ctx) val info = GoogleVoiceClient.get(ctx).getSipRegisterInfo() gvNumber = session.phoneNumber() ?: info.phoneNumber.orEmpty()- val s = SipClient(info, gvNumber, scope, sipListener())- sip = s+ val s = ensureSipClient(info) s.connect() s.register()- }.onFailure { fail(it.message ?: "registration failed") }+ }.onFailure { reason ->+ android.util.Log.e("GoogleVoiceCall", "registration failed", reason)+ stopRegistration()+ } } } + fun stopRegistration() {+ registrationJob?.cancel()+ registrationJob = null+ registered = false+ pendingInviteTarget = null+ pendingInviteSdp = null+ runCatching { sip?.close() }+ sip = null+ runCatching { audio?.close() }+ audio = null+ _state.value = CallState()+ }+ fun answer() { val ctx = appContext ?: return scope.launch {@@ -151,6 +172,7 @@ object GoogleVoiceCallManager { private fun sipListener() = object : SipClient.Listener { override fun onRegistered() { registered = true+ scheduleRegistrationRefresh() val target = pendingInviteTarget val sdp = pendingInviteSdp if (target != null && sdp != null) {@@ -205,27 +227,43 @@ object GoogleVoiceCallManager { } private fun endCall() {- cleanup()+ cleanupCall() _state.value = CallState(phase = CallPhase.Ended, remoteNumber = remoteNumber) connection?.onCallEnded() } private fun fail(reason: String) { android.util.Log.e("GoogleVoiceCall", "call failed: $reason")- cleanup()+ cleanupCall() _state.value = CallState(phase = CallPhase.Ended, remoteNumber = remoteNumber) connection?.onCallEnded()+ if (!registered) stopRegistration() } - private fun cleanup() {- runCatching { sip?.close() }+ private fun cleanupCall() { runCatching { audio?.close() }- sip = null audio = null- registered = false remoteApplied = false pendingInviteTarget = null pendingInviteSdp = null+ remoteNumber = ""+ }++ private fun ensureSipClient(info: com.vayunmathur.communicate.data.googlevoice.GvSipRegisterInfo): SipClient {+ sip?.let { return it }+ return SipClient(info, gvNumber, scope, sipListener()).also { sip = it }+ }++ private fun scheduleRegistrationRefresh() {+ registrationJob?.cancel()+ registrationJob = scope.launch {+ delay(50 * 60 * 1000L)+ registered = false+ runCatching { sip?.register() }.onFailure {+ android.util.Log.e("GoogleVoiceCall", "registration refresh failed", it)+ stopRegistration()+ }+ } } /** Reset to Idle once the UI has consumed a terminal state. */
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.ktindex 5a6cc88527..7d6afc6de9 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/call/SipClient.kt@@ -64,6 +64,7 @@ class SipClient( private var lastExpires = 3600 private var registerRetried = false private var authRetried = false+ private var inboundInvite: InboundInvite? = null // The SIP AOR/username is credential[0]; the digest password is credential[1] (from // sipregisterinfo/get). The AOR user is credential[0] URL-encoded ("=" -> "%3D").@@ -73,6 +74,7 @@ class SipClient( private val contactUser = randomToken(8) suspend fun connect() {+ if (socket != null) return socket = WebSocketClient.connect( urlStr = WS_URL, headers = mapOf(@@ -163,25 +165,24 @@ class SipClient( /** Answer an inbound INVITE with our answer SDP (200 OK). */ suspend fun answerInbound(answerSdp: String) {- // Best-effort: echo a 200 OK for the pending inbound INVITE.- val response = buildString {- append("SIP/2.0 200 OK\r\n")- append("Content-Type: application/sdp\r\n")- append("Content-Length: ${answerSdp.toByteArray().size}\r\n")- append("\r\n")- append(answerSdp)- }- send(response)+ val invite = inboundInvite ?: return+ send(buildInboundResponse(invite, 200, "OK", body = answerSdp, contentType = "application/sdp")) } /** Decline an inbound INVITE (603). */ suspend fun declineInbound() {- send("SIP/2.0 603 Decline\r\nContent-Length: 0\r\n\r\n")+ val invite = inboundInvite ?: return+ send(buildInboundResponse(invite, 603, "Decline"))+ inboundInvite = null } fun close() { readJob?.cancel()- scope.launch { runCatching { socket?.close() } }+ readJob = null+ val s = socket+ socket = null+ inboundInvite = null+ scope.launch { runCatching { s?.close() } } } // ------------------------------------------------------------------@@ -248,10 +249,31 @@ class SipClient( } } firstLine.startsWith("INVITE", true) -> {+ val invite = InboundInvite.from(message, headers)+ inboundInvite = invite+ scope.launch {+ runCatching { send(buildInboundResponse(invite, 100, "Trying")) }+ runCatching { send(buildInboundResponse(invite, 180, "Ringing")) }+ } val from = headers["from"]?.let { extractUserFromHeader(it) } ?: "Unknown" listener.onIncomingInvite(body, from) }- firstLine.startsWith("BYE", true) -> listener.onEnded()+ firstLine.startsWith("CANCEL", true) -> {+ val invite = inboundInvite+ scope.launch {+ runCatching { send(buildCancelOk(message, headers)) }+ if (invite != null) {+ runCatching { send(buildInboundResponse(invite, 487, "Request Terminated")) }+ }+ }+ inboundInvite = null+ listener.onEnded()+ }+ firstLine.startsWith("BYE", true) -> {+ scope.launch { runCatching { send(buildByeOk(message, headers)) } }+ inboundInvite = null+ listener.onEnded()+ } } } @@ -288,6 +310,64 @@ class SipClient( } } + private fun buildInboundResponse(+ invite: InboundInvite,+ code: Int,+ reason: String,+ body: String? = null,+ contentType: String? = null,+ ): String {+ val bytes = body?.toByteArray()?.size ?: 0+ return buildString {+ append("SIP/2.0 $code $reason\r\n")+ invite.viaLines.forEach { append("$it\r\n") }+ append("From: ${invite.from}\r\n")+ append("To: ${invite.to}${invite.toTagForResponse(code)}\r\n")+ append("Call-ID: ${invite.callId}\r\n")+ append("CSeq: ${invite.cseq}\r\n")+ invite.recordRouteLines.forEach { append("$it\r\n") }+ if (code == 200) append("Contact: <sip:$contactUser@$localHost;transport=wss>\r\n")+ if (contentType != null) append("Content-Type: $contentType\r\n")+ append("Content-Length: $bytes\r\n")+ append("\r\n")+ if (body != null) append(body)+ }+ }++ private fun buildCancelOk(message: String, headers: Map<String, String>): String {+ val viaLines = headerLines(message, "Via")+ val from = headers["from"].orEmpty()+ val to = headers["to"].orEmpty()+ val callId = headers["call-id"].orEmpty()+ val cseq = headers["cseq"].orEmpty()+ return buildString {+ append("SIP/2.0 200 OK\r\n")+ viaLines.forEach { append("$it\r\n") }+ append("From: $from\r\n")+ append("To: $to\r\n")+ append("Call-ID: $callId\r\n")+ append("CSeq: $cseq\r\n")+ append("Content-Length: 0\r\n\r\n")+ }+ }++ private fun buildByeOk(message: String, headers: Map<String, String>): String {+ val viaLines = headerLines(message, "Via")+ val from = headers["from"].orEmpty()+ val to = headers["to"].orEmpty()+ val callId = headers["call-id"].orEmpty()+ val cseq = headers["cseq"].orEmpty()+ return buildString {+ append("SIP/2.0 200 OK\r\n")+ viaLines.forEach { append("$it\r\n") }+ append("From: $from\r\n")+ append("To: $to\r\n")+ append("Call-ID: $callId\r\n")+ append("CSeq: $cseq\r\n")+ append("Content-Length: 0\r\n\r\n")+ }+ }+ /** The remote target URI from a response's Contact header (used for in-dialog ACK/BYE). */ private fun extractContact(message: String): String? { val line = message.lineSequence().firstOrNull { it.trim().startsWith("Contact:", true) } ?: return null@@ -304,6 +384,15 @@ class SipClient( private fun fromUri() = "<sip:$aorUser@$SIP_DOMAIN>" + private fun headerLines(message: String, name: String): List<String> {+ val prefix = "$name:"+ return message.lineSequence()+ .map { it.trimEnd() }+ .takeWhile { it.isNotEmpty() }+ .filter { it.startsWith(prefix, ignoreCase = true) }+ .toList()+ }+ private fun parseHeaders(message: String): Map<String, String> { val out = mutableMapOf<String, String>() for (line in message.lineSequence()) {@@ -342,9 +431,39 @@ class SipClient( private fun extractUserFromHeader(headerValue: String): String? = Regex("sip:([^@>;\\s]+)@").find(headerValue)?.groupValues?.getOrNull(1) - private fun randomToken(len: Int): String {- val chars = "abcdefghijklmnopqrstuvwxyz0123456789"- return (1..len).map { chars[Random.nextInt(chars.length)] }.joinToString("")+ private data class InboundInvite(+ val viaLines: List<String>,+ val recordRouteLines: List<String>,+ val from: String,+ val to: String,+ val callId: String,+ val cseq: String,+ val responseToTag: String = randomToken(8),+ ) {+ fun toTagForResponse(code: Int): String {+ if (to.contains(";tag=", ignoreCase = true)) return ""+ return if (code > 100) ";tag=$responseToTag" else ""+ }++ companion object {+ fun from(message: String, headers: Map<String, String>) = InboundInvite(+ viaLines = headerLinesStatic(message, "Via"),+ recordRouteLines = headerLinesStatic(message, "Record-Route"),+ from = headers["from"].orEmpty(),+ to = headers["to"].orEmpty(),+ callId = headers["call-id"].orEmpty(),+ cseq = headers["cseq"].orEmpty(),+ )++ private fun headerLinesStatic(message: String, name: String): List<String> {+ val prefix = "$name:"+ return message.lineSequence()+ .map { it.trimEnd() }+ .takeWhile { it.isNotEmpty() }+ .filter { it.startsWith(prefix, ignoreCase = true) }+ .toList()+ }+ } } companion object {@@ -354,3 +473,8 @@ class SipClient( private const val SIP_DOMAIN = "web.c.pbx.voice.sip.google.com" } }++private fun randomToken(len: Int): String {+ val chars = "abcdefghijklmnopqrstuvwxyz0123456789"+ return (1..len).map { chars[Random.nextInt(chars.length)] }.joinToString("")+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.ktindex 48946dce58..cd1fc80c51 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceCallForegroundService.kt@@ -1,6 +1,7 @@ package com.vayunmathur.communicate.telephony import android.app.Notification+import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context@@ -33,6 +34,16 @@ class GoogleVoiceCallForegroundService : Service() { override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ when (intent?.action) {+ ACTION_ANSWER -> GoogleVoiceCallManager.answer()+ ACTION_HANGUP -> {+ if (GoogleVoiceCallManager.state.value.phase == CallPhase.Incoming) {+ GoogleVoiceCallManager.reject()+ } else {+ GoogleVoiceCallManager.hangup()+ }+ }+ } startForegroundWithNotification() observeJob?.cancel() observeJob = scope.launch {@@ -47,18 +58,14 @@ class GoogleVoiceCallForegroundService : Service() { } private fun startForegroundWithNotification() {- ensureNotificationChannel(CHANNEL_ID, getString(R.string.gv_call_channel_name))- val contentIntent = PendingIntent.getActivity(- this, 0, Intent(this, MainActivity::class.java),- PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,- )- val notification: Notification = Notification.Builder(this, CHANNEL_ID)- .setContentTitle(getString(R.string.gv_ongoing_call))- .setContentText(GoogleVoiceCallManager.state.value.remoteNumber)- .setSmallIcon(android.R.drawable.sym_action_call)- .setOngoing(true)- .setContentIntent(contentIntent)- .build()+ ensureChannels()+ val state = GoogleVoiceCallManager.state.value+ val contentIntent = callActivityIntent(0)+ val notification = if (state.phase == CallPhase.Incoming) {+ buildIncomingCallNotification(state.remoteNumber, contentIntent)+ } else {+ buildOngoingCallNotification(state.phase, state.remoteNumber, contentIntent)+ } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)@@ -67,6 +74,85 @@ class GoogleVoiceCallForegroundService : Service() { } } + private fun ensureChannels() {+ ensureNotificationChannel(CHANNEL_ID, getString(R.string.gv_call_channel_name))+ ensureNotificationChannel(+ id = INCOMING_CHANNEL_ID,+ name = getString(R.string.gv_incoming_call_channel_name),+ importance = NotificationManager.IMPORTANCE_HIGH,+ description = getString(R.string.gv_incoming_call_channel_desc),+ ) {+ lockscreenVisibility = Notification.VISIBILITY_PUBLIC+ }+ }++ private fun buildIncomingCallNotification(remoteNumber: String, contentIntent: PendingIntent): Notification {+ val fullScreenIntent = callActivityIntent(1)+ return Notification.Builder(this, INCOMING_CHANNEL_ID)+ .setContentTitle(getString(R.string.call_state_incoming))+ .setContentText(remoteNumber.ifBlank { getString(R.string.account_google_voice) })+ .setSmallIcon(android.R.drawable.sym_call_incoming)+ .setCategory(Notification.CATEGORY_CALL)+ .setPriority(Notification.PRIORITY_MAX)+ .setVisibility(Notification.VISIBILITY_PUBLIC)+ .setOngoing(true)+ .setAutoCancel(false)+ .setContentIntent(contentIntent)+ .setFullScreenIntent(fullScreenIntent, true)+ .addAction(+ android.R.drawable.sym_call_incoming,+ getString(R.string.call_answer),+ serviceActionIntent(ACTION_ANSWER, 2),+ )+ .addAction(+ android.R.drawable.ic_menu_close_clear_cancel,+ getString(R.string.call_decline),+ serviceActionIntent(ACTION_HANGUP, 3),+ )+ .build()+ }++ private fun buildOngoingCallNotification(+ phase: CallPhase,+ remoteNumber: String,+ contentIntent: PendingIntent,+ ): Notification {+ val title = when (phase) {+ CallPhase.Dialing -> getString(R.string.call_state_dialing)+ CallPhase.Ringing -> getString(R.string.call_state_ringing)+ else -> getString(R.string.gv_ongoing_call)+ }+ return Notification.Builder(this, CHANNEL_ID)+ .setContentTitle(title)+ .setContentText(remoteNumber)+ .setSmallIcon(android.R.drawable.sym_action_call)+ .setCategory(Notification.CATEGORY_CALL)+ .setOngoing(true)+ .setContentIntent(contentIntent)+ .addAction(+ android.R.drawable.ic_menu_close_clear_cancel,+ getString(R.string.call_end),+ serviceActionIntent(ACTION_HANGUP, 3),+ )+ .build()+ }++ private fun serviceActionIntent(action: String, requestCode: Int): PendingIntent = PendingIntent.getService(+ this,+ requestCode,+ Intent(this, GoogleVoiceCallForegroundService::class.java).apply { this.action = action },+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )++ private fun callActivityIntent(requestCode: Int): PendingIntent = PendingIntent.getActivity(+ this,+ requestCode,+ Intent(this, MainActivity::class.java).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)+ },+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ private fun stopSelfSafely() { androidx.core.app.ServiceCompat.stopForeground( this, androidx.core.app.ServiceCompat.STOP_FOREGROUND_REMOVE,@@ -81,7 +167,10 @@ class GoogleVoiceCallForegroundService : Service() { companion object { private const val CHANNEL_ID = "gv_calls"+ private const val INCOMING_CHANNEL_ID = "gv_calls_incoming" private const val NOTIFICATION_ID = 4711+ private const val ACTION_ANSWER = "com.vayunmathur.communicate.googlevoice.ANSWER_CALL"+ private const val ACTION_HANGUP = "com.vayunmathur.communicate.googlevoice.HANGUP_CALL" fun start(context: Context) { ContextCompat.startForegroundService(
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.ktindex ed87e0171e..a2f8a29181 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionService.kt@@ -6,6 +6,7 @@ import android.telecom.ConnectionRequest import android.telecom.ConnectionService import android.telecom.PhoneAccountHandle import android.telecom.TelecomManager+import android.telecom.VideoProfile import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager /**@@ -39,7 +40,12 @@ class GoogleVoiceConnectionService : ConnectionService() { GoogleVoiceCallManager.init(applicationContext) val address = request?.extras?.getParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS) as? Uri val connection = GoogleVoiceConnection().apply {- if (address != null) setAddress(address, TelecomManager.PRESENTATION_ALLOWED)+ if (address != null) {+ setAddress(address, TelecomManager.PRESENTATION_ALLOWED)+ setCallerDisplayName(address.schemeSpecificPart, TelecomManager.PRESENTATION_ALLOWED)+ }+ videoState = VideoProfile.STATE_AUDIO_ONLY+ setInitializing() setRinging() connectionProperties = connectionProperties or Connection.PROPERTY_SELF_MANAGED }
communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceSyncService.ktnew file mode 100644index 0000000000..6779f3d146--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/GoogleVoiceSyncService.kt@@ -0,0 +1,250 @@+package com.vayunmathur.communicate.telephony++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.Person+import androidx.core.content.ContextCompat+import com.vayunmathur.communicate.MainActivity+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceAuthException+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.communicate.data.googlevoice.GvFolder+import com.vayunmathur.communicate.data.googlevoice.GvMessage+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch++/**+ * Foreground owner for Google Voice receive state: SIP registration for inbound calls plus+ * conservative polling for new message notifications while Communicate is backgrounded.+ */+class GoogleVoiceSyncService : Service() {++ private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var pollJob: Job? = null+ private lateinit var session: GoogleVoiceSession++ override fun onCreate() {+ super.onCreate()+ session = GoogleVoiceSession.get(this)+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ if (intent?.action == ACTION_STOP) {+ shutdown()+ return START_NOT_STICKY+ }++ ensureChannels()+ startForegroundCompat(buildSyncNotification())+ GoogleVoiceCallManager.init(this)+ GoogleVoiceCallManager.onIncomingCall = { from -> GoogleVoiceTelecom.addIncoming(this, from) }++ serviceScope.launch {+ if (!session.hasUsableCredentials()) {+ shutdown()+ return@launch+ }+ val number = session.phoneNumber() ?: getString(R.string.account_google_voice)+ GoogleVoiceTelecom.registerPhoneAccount(this@GoogleVoiceSyncService, number)+ GoogleVoiceCallManager.startRegistration()+ startPollingMessages()+ }++ return START_STICKY+ }++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onDestroy() {+ pollJob?.cancel()+ serviceScope.cancel()+ super.onDestroy()+ }++ override fun onTimeout(startId: Int, fgsType: Int) {+ Log.w(TAG, "FGS timeout for type=$fgsType; leaving foreground to avoid crash")+ stopForeground(STOP_FOREGROUND_DETACH)+ }++ private fun startPollingMessages() {+ if (pollJob?.isActive == true) return+ pollJob = serviceScope.launch {+ while (isActive) {+ runCatching { pollOnce() }+ .onFailure { error ->+ if (error is GoogleVoiceAuthException) {+ Log.w(TAG, "Google Voice auth rejected; stopping sync service")+ shutdown()+ return@launch+ }+ Log.w(TAG, "Google Voice message poll failed", error)+ }+ delay(POLL_INTERVAL_MILLIS)+ }+ }+ }++ private suspend fun pollOnce() {+ val client = GoogleVoiceClient.get(this)+ val threads = (client.listThreads(GvFolder.Inbox) + client.listThreads(GvFolder.All))+ .distinctBy { it.id }+ val allMessages = threads+ .flatMap { it.messages }+ .sortedBy { it.timestampMillis }+ val newestTimestamp = allMessages.maxOfOrNull { it.timestampMillis } ?: return+ val lastSeen = session.lastSeenMessageTimestampMillis()+ if (lastSeen <= 0L) {+ val serviceStartWindow = System.currentTimeMillis() - FIRST_POLL_NOTIFY_WINDOW_MILLIS+ allMessages+ .filter { it.timestampMillis >= serviceStartWindow && it.shouldNotify() }+ .forEach { showIncomingNotification(it) }+ session.setLastSeenMessageTimestampMillis(newestTimestamp)+ return+ }++ allMessages+ .filter { it.timestampMillis > lastSeen && it.shouldNotify() }+ .forEach { showIncomingNotification(it) }+ if (newestTimestamp > lastSeen) {+ session.setLastSeenMessageTimestampMillis(newestTimestamp)+ }+ }++ private fun ensureChannels() {+ ensureNotificationChannel(+ id = SYNC_CHANNEL_ID,+ name = getString(R.string.gv_sync_channel_name),+ importance = NotificationManager.IMPORTANCE_LOW,+ description = getString(R.string.gv_sync_channel_desc),+ ) {+ setSound(null, null)+ enableVibration(false)+ }+ ensureNotificationChannel(+ id = INCOMING_CHANNEL_ID,+ name = getString(R.string.gv_incoming_channel_name),+ importance = NotificationManager.IMPORTANCE_HIGH,+ description = getString(R.string.gv_incoming_channel_desc),+ )+ }++ private fun buildSyncNotification(): Notification {+ val tap = PendingIntent.getActivity(+ this,+ 0,+ Intent(this, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val stop = PendingIntent.getService(+ this,+ 1,+ Intent(this, GoogleVoiceSyncService::class.java).apply { action = ACTION_STOP },+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ return NotificationCompat.Builder(this, SYNC_CHANNEL_ID)+ .setContentTitle(getString(R.string.gv_sync_notification_title))+ .setContentText(getString(R.string.gv_sync_notification_text))+ .setSmallIcon(R.mipmap.ic_launcher)+ .setOngoing(true)+ .setSilent(true)+ .setOnlyAlertOnce(true)+ .setContentIntent(tap)+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+ .addAction(0, getString(R.string.notification_action_stop), stop)+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)+ .build()+ }++ private fun showIncomingNotification(message: GvMessage) {+ val notificationId = message.id.hashCode()+ val tap = PendingIntent.getActivity(+ this,+ notificationId,+ Intent(this, MainActivity::class.java).apply {+ addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)+ putExtra(EXTRA_OPEN_GOOGLE_VOICE_THREAD, message.threadId)+ },+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val sender = Person.Builder()+ .setName(message.phoneNumber.ifBlank { getString(R.string.account_google_voice) })+ .build()+ val self = Person.Builder().setName(getString(R.string.you)).build()+ val body = message.notificationText()+ val notification = NotificationCompat.Builder(this, INCOMING_CHANNEL_ID)+ .setSmallIcon(R.mipmap.ic_launcher)+ .setContentTitle(sender.name)+ .setContentText(body)+ .setStyle(NotificationCompat.MessagingStyle(self).addMessage(body, message.timestampMillis, sender))+ .setContentIntent(tap)+ .setAutoCancel(true)+ .setCategory(NotificationCompat.CATEGORY_MESSAGE)+ .setDefaults(NotificationCompat.DEFAULT_ALL)+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .build()+ val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager+ nm.notify(message.threadId, notificationId, notification)+ }++ private fun GvMessage.shouldNotify(): Boolean = !outgoing++ private fun GvMessage.notificationText(): String = text.ifBlank {+ if (hasMedia) getString(R.string.gv_media_message) else getString(R.string.new_message)+ }++ private fun startForegroundCompat(notification: Notification) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ startForeground(SYNC_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING)+ } else {+ startForeground(SYNC_NOTIFICATION_ID, notification)+ }+ }++ private fun shutdown() {+ pollJob?.cancel()+ pollJob = null+ GoogleVoiceCallManager.stopRegistration()+ stopForeground(STOP_FOREGROUND_REMOVE)+ stopSelf()+ }++ companion object {+ private const val TAG = "GoogleVoiceSync"+ private const val POLL_INTERVAL_MILLIS = 60_000L+ private const val FIRST_POLL_NOTIFY_WINDOW_MILLIS = 2 * 60_000L+ private const val SYNC_NOTIFICATION_ID = 4720+ private const val SYNC_CHANNEL_ID = "gv_sync"+ private const val INCOMING_CHANNEL_ID = "gv_messages_incoming"+ private const val ACTION_STOP = "com.vayunmathur.communicate.googlevoice.STOP_SYNC"+ const val EXTRA_OPEN_GOOGLE_VOICE_THREAD = "open_google_voice_thread"++ fun start(context: Context) {+ ContextCompat.startForegroundService(context, Intent(context, GoogleVoiceSyncService::class.java))+ }++ fun stop(context: Context) {+ ContextCompat.startForegroundService(+ context,+ Intent(context, GoogleVoiceSyncService::class.java).apply { action = ACTION_STOP },+ )+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex dd30abea84..59366fb882 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -1,6 +1,10 @@ package com.vayunmathur.communicate.ui import android.Manifest+import android.content.Intent+import android.net.Uri+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column@@ -9,6 +13,7 @@ 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.heightIn import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size@@ -26,6 +31,8 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight@@ -37,6 +44,7 @@ import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.IconArchive import com.vayunmathur.library.ui.IconAttachment+import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSend import com.vayunmathur.library.ui.IconSms@@ -47,16 +55,19 @@ import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.compose.AsyncImageState import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateAttachment import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.LineChoice import com.vayunmathur.communicate.data.SmsMessage import com.vayunmathur.communicate.data.SmsThread import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import android.content.Intent @Composable fun ConversationScreen(@@ -70,19 +81,29 @@ fun ConversationScreen( val context = LocalContext.current val scope = rememberCoroutineScope() var draft by remember(threadId) { mutableStateOf("") }+ var selectedAttachments by remember(threadId) { mutableStateOf<List<CommunicateAttachment>>(emptyList()) } // Bumped after a send to re-fetch the thread. var refresh by remember(threadId) { mutableIntStateOf(0) } val lineChoices = rememberLineChoices()- // Default the send line to this thread's line (matching SIM subscription when known).- var selectedLine by remember(threadId, lineChoices) {- mutableStateOf(- when (line) {- CommunicateLine.GoogleVoice ->- lineChoices.firstOrNull { it is com.vayunmathur.communicate.data.LineChoice.GoogleVoice }- CommunicateLine.Sim ->- lineChoices.firstOrNull { it is com.vayunmathur.communicate.data.LineChoice.Sim && it.subscriptionId == subscriptionId }- } ?: lineChoices.firstOrNull(),- )+ val fixedLineChoice = remember(line, subscriptionId, lineChoices) {+ when (line) {+ CommunicateLine.GoogleVoice -> LineChoice.GoogleVoice+ CommunicateLine.Sim -> lineChoices+ .filterIsInstance<LineChoice.Sim>()+ .firstOrNull { subscriptionId == null || it.subscriptionId == subscriptionId }+ ?: LineChoice.Sim(subscriptionId ?: -1, context.getString(R.string.line_sim))+ }+ }+ val attachmentPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->+ selectedAttachments = uris.map { uri ->+ runCatching {+ context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ CommunicateAttachment(+ contentUri = uri.toString(),+ mimeType = context.contentResolver.getType(uri) ?: "application/octet-stream",+ )+ } } val thread = remember(threadId) { SmsThread(@@ -166,24 +187,29 @@ fun ConversationScreen( ComposeSmsRow( draft = draft, onDraftChange = { draft = it },- lineSelector = {- val sel = selectedLine- if (lineChoices.size > 1 && sel != null) {- LineSelector(choices = lineChoices, selected = sel, onSelect = { selectedLine = it })- }+ attachments = selectedAttachments,+ onAttach = { attachmentPicker.launch(arrayOf("image/*", "video/*")) },+ onRemoveAttachment = { attachment ->+ selectedAttachments = selectedAttachments.filterNot { it.contentUri == attachment.contentUri } }, onSend = { val text = draft.trim()- val choice = selectedLine- if (text.isEmpty() || choice == null) return@ComposeSmsRow+ val attachments = selectedAttachments+ if (text.isEmpty() && attachments.isEmpty()) return@ComposeSmsRow+ if (fixedLineChoice is LineChoice.Sim && attachments.isNotEmpty()) {+ AppMessages.show(context.getString(R.string.sim_mms_unsupported))+ return@ComposeSmsRow+ } draft = ""+ selectedAttachments = emptyList() scope.launch { val ok = CommunicateRepository.sendMessage( context,- choice,+ fixedLineChoice, address, text,- if (choice is com.vayunmathur.communicate.data.LineChoice.GoogleVoice) remoteId else null,+ if (fixedLineChoice is LineChoice.GoogleVoice) remoteId else null,+ attachments, ) if (ok) refresh++ else AppMessages.show(context.getString(R.string.gv_send_failed)) }@@ -213,6 +239,91 @@ fun ConversationScreen( } } +@Composable+private fun MessageAttachment(+ attachment: CommunicateAttachment,+ bubbleColor: androidx.compose.ui.graphics.Color,+ contentColor: androidx.compose.ui.graphics.Color,+ shape: RoundedCornerShape,+) {+ val context = LocalContext.current+ val openAttachment = {+ ExternalIntents.launch(+ context,+ Intent(Intent.ACTION_VIEW, attachment.contentUri.toUri()),+ )+ Unit+ }+ if (attachment.mimeType.startsWith("image/")) {+ var showFallback by remember(attachment.contentUri) { mutableStateOf(false) }+ if (!showFallback) {+ Surface(+ shape = shape,+ modifier = Modifier+ .widthIn(max = 320.dp)+ .heightIn(max = 260.dp)+ .padding(top = 2.dp)+ .clickable(onClick = openAttachment),+ ) {+ AsyncImage(+ model = attachment.contentUri,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ onState = { state -> showFallback = state is AsyncImageState.Error },+ modifier = Modifier+ .widthIn(min = 180.dp, max = 320.dp)+ .heightIn(min = 120.dp, max = 260.dp),+ )+ }+ }+ if (showFallback) {+ AttachmentFallbackRow(+ attachment = attachment,+ bubbleColor = bubbleColor,+ contentColor = contentColor,+ shape = shape,+ onClick = openAttachment,+ )+ }+ } else {+ AttachmentFallbackRow(+ attachment = attachment,+ bubbleColor = bubbleColor,+ contentColor = contentColor,+ shape = shape,+ onClick = openAttachment,+ )+ }+}++@Composable+private fun AttachmentFallbackRow(+ attachment: CommunicateAttachment,+ bubbleColor: androidx.compose.ui.graphics.Color,+ contentColor: androidx.compose.ui.graphics.Color,+ shape: RoundedCornerShape,+ onClick: () -> Unit,+) {+ Surface(+ color = bubbleColor,+ contentColor = contentColor,+ shape = shape,+ modifier = Modifier+ .widthIn(max = 320.dp)+ .padding(top = 2.dp)+ .clickable(onClick = onClick),+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconAttachment()+ Spacer(Modifier.size(6.dp))+ Text(attachment.mimeType, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+}+ @Composable private fun MessagesList(padding: PaddingValues, refresh: Int, load: suspend () -> List<SmsMessage>) { val messages = produceState<List<SmsMessage>?>(initialValue = null, refresh) {@@ -248,7 +359,9 @@ private fun MessagesContent(padding: PaddingValues, rows: List<SmsMessage>?) { private fun ComposeSmsRow( draft: String, onDraftChange: (String) -> Unit,- lineSelector: @Composable () -> Unit,+ attachments: List<CommunicateAttachment>,+ onAttach: () -> Unit,+ onRemoveAttachment: (CommunicateAttachment) -> Unit, onSend: () -> Unit, ) { Surface(@@ -257,25 +370,88 @@ private fun ComposeSmsRow( .fillMaxWidth() .imePadding(), ) {- Row(+ Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp, vertical = 8.dp),+ ) {+ if (attachments.isNotEmpty()) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ attachments.forEach { attachment ->+ SelectedAttachmentPreview(+ attachment = attachment,+ onRemove = { onRemoveAttachment(attachment) },+ )+ }+ }+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconButton(onClick = onAttach) {+ IconAttachment()+ }+ OutlinedTextField(+ value = draft,+ onValueChange = onDraftChange,+ modifier = Modifier+ .weight(1f)+ .padding(horizontal = 4.dp),+ placeholder = { Text(stringResource(R.string.message_hint)) },+ maxLines = 5,+ shape = RoundedCornerShape(24.dp),+ )+ IconButton(onClick = onSend, enabled = draft.isNotBlank() || attachments.isNotEmpty()) {+ IconSend()+ }+ }+ }+ }+}++@Composable+private fun SelectedAttachmentPreview(+ attachment: CommunicateAttachment,+ onRemove: () -> Unit,+) {+ Surface(+ shape = RoundedCornerShape(14.dp),+ color = MaterialTheme.colorScheme.surfaceVariant,+ contentColor = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.widthIn(max = 160.dp),+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, ) {- lineSelector()- OutlinedTextField(- value = draft,- onValueChange = onDraftChange,- modifier = Modifier- .weight(1f)- .padding(horizontal = 4.dp),- placeholder = { Text(stringResource(R.string.message_hint)) },- maxLines = 5,- shape = RoundedCornerShape(24.dp),+ if (attachment.mimeType.startsWith("image/")) {+ AsyncImage(+ model = Uri.parse(attachment.contentUri),+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier+ .size(40.dp)+ .clip(RoundedCornerShape(10.dp)),+ )+ } else {+ IconAttachment()+ }+ Spacer(Modifier.size(6.dp))+ Text(+ attachment.mimeType,+ fontSize = 12.sp,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f, fill = false), )- IconButton(onClick = onSend, enabled = draft.isNotBlank()) {- IconSend()+ IconButton(onClick = onRemove) {+ IconClose(Modifier.size(18.dp)) } } }@@ -321,29 +497,12 @@ private fun MessageBubble(message: SmsMessage) { } } message.attachments.forEach { attachment ->- Surface(- color = bubbleColor,+ MessageAttachment(+ attachment = attachment,+ bubbleColor = bubbleColor, contentColor = contentColor, shape = shape,- modifier = Modifier- .widthIn(max = 320.dp)- .padding(top = 2.dp)- .clickable {- ExternalIntents.launch(- context,- Intent(Intent.ACTION_VIEW, attachment.contentUri.toUri()),- )- },- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- IconAttachment()- Spacer(Modifier.size(6.dp))- Text(attachment.mimeType, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)- }- }+ ) } Row( modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.ktindex 2bd69c674f..86e75a5ef8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt@@ -18,6 +18,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState@@ -38,6 +39,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateContact import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.LineChoice import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager import com.vayunmathur.communicate.telephony.GoogleVoiceTelecom@@ -70,12 +72,23 @@ fun DialerScreen() { val scope = rememberCoroutineScope() var number by remember { mutableStateOf("") } val lineChoices = rememberLineChoices()- var selectedLine by remember(lineChoices) { mutableStateOf(lineChoices.firstOrNull()) }+ var selectedLine by remember { mutableStateOf<LineChoice?>(null) }+ var userSelectedLine by remember { mutableStateOf(false) }++ LaunchedEffect(lineChoices) {+ val current = selectedLine+ if (current == null || current !in lineChoices) {+ selectedLine = lineChoices.firstOrNull { it is LineChoice.GoogleVoice } ?: lineChoices.firstOrNull()+ userSelectedLine = false+ } else if (!userSelectedLine && lineChoices.any { it is LineChoice.GoogleVoice }) {+ selectedLine = lineChoices.first { it is LineChoice.GoogleVoice }+ }+ } fun place(target: String) { if (target.isBlank()) return val choice = selectedLine- if (choice is com.vayunmathur.communicate.data.LineChoice.GoogleVoice) {+ if (choice is LineChoice.GoogleVoice) { GoogleVoiceCallManager.init(context) } CommunicateRepository.placeCall(context, choice, target)@@ -91,7 +104,10 @@ fun DialerScreen() { LineSelector( choices = lineChoices, selected = sel,- onSelect = { selectedLine = it },+ onSelect = {+ selectedLine = it+ userSelectedLine = true+ }, modifier = Modifier.padding(end = 8.dp), ) }
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex deac2c2929..77dc0ff25f 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -58,6 +58,16 @@ <string name="choose_line">Send from</string> <string name="gv_send_failed">Couldn\'t send via Google Voice</string> <string name="gv_action_failed">Google Voice action failed</string>+ <string name="sim_mms_unsupported">SIM MMS attachments are not supported yet</string>+ <string name="gv_media_message">Media message</string>+ <string name="gv_sync_channel_name">Google Voice receive</string>+ <string name="gv_sync_channel_desc">Keeps Google Voice calls and messages available in the background.</string>+ <string name="gv_incoming_channel_name">Google Voice messages</string>+ <string name="gv_incoming_channel_desc">New Google Voice message alerts.</string>+ <string name="gv_sync_notification_title">Google Voice receive active</string>+ <string name="gv_sync_notification_text">Listening for calls and checking for new messages</string>+ <string name="notification_action_stop">Stop</string>+ <string name="you">You</string> <string name="call_mute">Mute</string> <string name="call_unmute">Unmute</string> <string name="call_speaker">Speaker</string>@@ -72,6 +82,8 @@ <string name="call_state_incoming">Incoming Google Voice call</string> <string name="call_state_idle">Idle</string> <string name="gv_call_channel_name">Google Voice calls</string>+ <string name="gv_incoming_call_channel_name">Incoming Google Voice calls</string>+ <string name="gv_incoming_call_channel_desc">Full-screen alerts for incoming Google Voice calls.</string> <string name="gv_ongoing_call">Ongoing Google Voice call</string> <string name="gv_call_failed">Google Voice call failed</string> </resources>
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.ktindex 9cbff4e7a8..9df5254d0d 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt@@ -125,6 +125,82 @@ class GoogleVoiceParserTest { assertTrue(outbound.outgoing) } + @Test+ fun parseThreadMessages_keepsTextOnlyMessagesWithoutMedia() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"plain text\",null,null,5,1,null,\"+14152124034\",0]]," ++ "null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("plain text", message.text)+ assertEquals(emptyList(), message.mediaUrls)+ }++ @Test+ fun parseThreadMessages_extractsGoogleHostedMediaUrls() {+ val media = "https://lh3.googleusercontent.com/voice-mms/photo.jpg=s1024"+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"photo\",null,[null,\"$media\"],5,1,null,\"+14152124034\",0]]," ++ "null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals(listOf(media), message.mediaUrls)+ assertTrue(message.hasMedia)+ }++ @Test+ fun parseThreadMessages_blanksOutboundMediaOnlyStatusLabel() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],11,1,null,null,null,\"MMS Sent\",null,null,5,1,null,\"+14152124034\"," ++ "[[null,\"image/jpeg\",\"m1-1\"]]]],null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("", message.text)+ assertEquals(emptyList(), message.mediaUrls)+ assertTrue(message.hasMedia)+ assertTrue(message.outgoing)+ }++ @Test+ fun parseThreadMessages_blanksInboundMediaOnlyStatusLabel() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"mMs ReCeIvEd\",null,null,5,1,null,\"+14152124034\"," ++ "[[null,\"image/jpeg\",\"m1-1\"]]]],null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("", message.text)+ assertEquals(emptyList(), message.mediaUrls)+ assertTrue(message.hasMedia)+ assertFalse(message.outgoing)+ }++ @Test+ fun parseThreadMessages_preservesCaptionTextWithMediaMetadata() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"real caption\",null,null,5,1,null,\"+14152124034\"," ++ "[[null,\"image/jpeg\",\"m1-1\"]]]],null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("real caption", message.text)+ assertTrue(message.hasMedia)+ }++ @Test+ fun parseThreadMessages_ignoresMalformedSlot16Metadata() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"MMS Received\",null,null,5,1,null,\"+14152124034\"," ++ "[null,123,{}]]],null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("MMS Received", message.text)+ assertFalse(message.hasMedia)+ }++ @Test+ fun parseThreadMessages_ignoresMalformedNullAndNonMediaShapes() {+ val body = "[[[\"t.+14152124034\",1,[[\"m1\",1786000000000,\"+12133945548\"," ++ "[\"+14152124034\"],10,1,null,null,null,\"https://example.com/not-media\",null," ++ "[null,123,null,[\"https://accounts.google.com/signin\"]],5,1,null,\"+14152124034\",0]]," ++ "null,[[\"+14152124034\"]]]]]"+ val message = GoogleVoiceParser.parseThreadMessages(body, "t.+14152124034").single()+ assertEquals("https://example.com/not-media", message.text)+ assertEquals(emptyList(), message.mediaUrls)+ }+ @Test fun parseAccount_findsPrimaryNumber() { val body = "[\"+15550001111\",null,[\"settings\"]]"