communicate: read receipts, WhatsApp+SIM MMS group chats, WhatsApp gated behind DEV_BUILD
- Commit
14bb952af70766a8f5f839116197955351d34aa3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-13 21:39 UTC (3 months ago)
- Parents
b8657d8
Diff
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 67305c9ace..985075f768 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -157,6 +157,17 @@ android:name=".telephony.GoogleVoiceCallForegroundService" android:exported="false" android:foregroundServiceType="phoneCall" />++ <!-- Exposes the temporary M-Send.req PDU file to the system MMS service. -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.mmsfileprovider"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/mms_file_paths" />+ </provider> </application> </manifest>
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 9ba821ff0b..4c684d8cb5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -58,6 +58,9 @@ sealed interface Route : NavKey { val line: CommunicateLine = CommunicateLine.Sim, val remoteId: String? = null, val subscriptionId: Int? = null,+ val isGroup: Boolean = false,+ val participants: List<String> = emptyList(),+ val groupTitle: String? = null, ) : Route } @@ -93,8 +96,9 @@ private fun CommunicateApp() { val waSignedIn by waSession.signedInFlow.collectAsState(initial = false) val callState by GoogleVoiceCallManager.state.collectAsState() - // Own the WhatsApp always-on receive state via its foreground sync service.+ // Own the WhatsApp always-on receive state via its foreground sync service (dev-only). LaunchedEffect(waSignedIn) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return@LaunchedEffect if (waSignedIn) WhatsAppSyncService.start(context) else WhatsAppSyncService.stop(context) } @@ -148,6 +152,9 @@ private fun CommunicateApp() { line = thread.line, remoteId = thread.remoteId, subscriptionId = thread.subscriptionId,+ isGroup = thread.isGroup,+ participants = thread.participants,+ groupTitle = thread.groupTitle, ), ) },@@ -160,8 +167,16 @@ private fun CommunicateApp() { AccountsScreen( onBack = { backStack.pop() }, onSignIn = { backStack.add(Route.GoogleVoiceSignIn) },- onRegisterWhatsApp = { backStack.add(Route.WhatsAppRegistration) },- onImportBackup = { backStack.add(Route.WhatsAppBackupImport) },+ onRegisterWhatsApp = {+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ backStack.add(Route.WhatsAppRegistration)+ }+ },+ onImportBackup = {+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ backStack.add(Route.WhatsAppBackupImport)+ }+ }, ) } entry<Route.GoogleVoiceSignIn> {@@ -188,6 +203,9 @@ private fun CommunicateApp() { line = route.line, remoteId = route.remoteId, subscriptionId = route.subscriptionId,+ isGroup = route.isGroup,+ participants = route.participants,+ groupTitle = route.groupTitle, onBack = { backStack.pop() }, ) }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex 775b045795..6dc822ebe8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -92,8 +92,27 @@ data class SmsThread( val isGroup: Boolean = false, /** Optional avatar URL/path for the thread (WhatsApp contact/group photo). */ val avatarUrl: String? = null,+ /**+ * Group participants (addresses/JIDs). Empty for 1:1 threads. Used to render the+ * group subtitle ("Alice, Bob +N") and, for SIM/GV groups, to route sends.+ */+ val participants: List<String> = emptyList(),+ /** Explicit group name/subject when known (WhatsApp subject, MMS group name). */+ val groupTitle: String? = null, ) +/**+ * Delivery lifecycle of an outgoing message, rendered as ticks in the bubble.+ * [None] means "don't show a tick" (inbound messages, or lines without receipts).+ */+enum class MessageStatus {+ None,+ Sent,+ Delivered,+ Read,+ Failed,+}+ data class SmsMessage( val id: Long, val threadId: Long,@@ -111,4 +130,11 @@ data class SmsMessage( * (reactions/polls/edited/revoked/quoted/group). Null for SIM/GV. */ val serviceData: String? = null,+ /**+ * Sender address/JID for inbound group messages, used to render a per-message+ * sender label. Null for 1:1 threads and outgoing messages.+ */+ val senderAddress: String? = null,+ /** Delivery status for outgoing messages (drives the sent/delivered/read ticks). */+ val status: MessageStatus = MessageStatus.None, )
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 aa61579d77..fe63832241 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -139,25 +139,191 @@ object CommunicateRepository { fun loadSmsThreads(context: Context): List<SmsThread> { if (!context.hasPermission(Manifest.permission.READ_SMS)) return emptyList()- return loadSmsMessages(context, threadId = null)+ val recipientsByThread = loadThreadRecipients(context)+ // Merge SMS + MMS messages so group MMS threads (which have no SMS rows) still appear.+ val byThread = (loadSmsMessages(context, threadId = null) + loadMmsMessages(context, threadId = null)) .groupBy { it.threadId }- .values- .mapNotNull { messages ->- val newest = messages.maxByOrNull { it.timestampMillis } ?: return@mapNotNull null- val address = newest.address- SmsThread(- threadId = newest.threadId,- address = address,- displayName = findContactName(context, address),- snippet = newest.body,- timestampMillis = newest.timestampMillis,- unreadCount = messages.count { !it.outgoing && !it.read },- subscriptionId = newest.subscriptionId,- )+ return byThread.values.mapNotNull { messages ->+ val newest = messages.maxByOrNull { it.timestampMillis } ?: return@mapNotNull null+ val threadId = newest.threadId+ val participants = recipientsByThread[threadId]+ ?: messages.mapNotNull { it.senderAddress }.distinct().ifEmpty { listOf(newest.address) }+ val isGroup = participants.size > 1+ val primary = participants.firstOrNull()?.takeIf { it.isNotBlank() } ?: newest.address+ val displayName = if (isGroup) {+ participants.joinToString(", ") { findContactName(context, it) ?: it }+ } else {+ findContactName(context, primary)+ }+ SmsThread(+ threadId = threadId,+ address = primary,+ displayName = displayName,+ snippet = newest.body,+ timestampMillis = newest.timestampMillis,+ unreadCount = messages.count { !it.outgoing && !it.read },+ subscriptionId = newest.subscriptionId,+ isGroup = isGroup,+ participants = if (isGroup) participants else emptyList(),+ )+ }.sortedByDescending { it.timestampMillis }+ }++ /**+ * Map each provider thread id to its recipient addresses via `mms-sms/conversations` ++ * `mms-sms/canonical-addresses`. Threads with >1 recipient are group threads. Empty on any+ * provider error (falls back to per-message address inference).+ */+ private fun loadThreadRecipients(context: Context): Map<Long, List<String>> = runCatching {+ // recipient_ids is a space-separated list of ids into the canonical-addresses table.+ val canonical = HashMap<String, String>()+ context.contentResolver.query(+ Uri.parse("content://mms-sms/canonical-addresses"),+ arrayOf("_id", "address"),+ null, null, null,+ )?.use { c ->+ val idIdx = c.getColumnIndexOrThrow("_id")+ val addrIdx = c.getColumnIndexOrThrow("address")+ while (c.moveToNext()) canonical[c.getString(idIdx)] = c.getString(addrIdx).orEmpty()+ }+ val result = HashMap<Long, List<String>>()+ context.contentResolver.query(+ Telephony.Threads.CONTENT_URI.buildUpon().appendQueryParameter("simple", "true").build(),+ arrayOf(Telephony.Threads._ID, Telephony.Threads.RECIPIENT_IDS),+ null, null, null,+ )?.use { c ->+ val idIdx = c.getColumnIndexOrThrow(Telephony.Threads._ID)+ val ridIdx = c.getColumnIndexOrThrow(Telephony.Threads.RECIPIENT_IDS)+ while (c.moveToNext()) {+ val tid = c.getLong(idIdx)+ val addrs = c.getString(ridIdx).orEmpty().split(" ")+ .mapNotNull { rid -> canonical[rid]?.takeIf { it.isNotBlank() } }+ if (addrs.isNotEmpty()) result[tid] = addrs+ }+ }+ result+ }.getOrDefault(emptyMap())++ /**+ * Read MMS messages (text + image parts) from `Telephony.Mms`, with the per-message sender+ * (from `Telephony.Mms.Addr`, for group labeling) and image/text attachments. Returns them in+ * the shared [SmsMessage] model so they merge with SMS by threadId.+ */+ fun loadMmsMessages(context: Context, threadId: Long?): List<SmsMessage> {+ if (!context.hasPermission(Manifest.permission.READ_SMS)) return emptyList()+ val selection = threadId?.let { "${Telephony.Mms.THREAD_ID} = ?" }+ val args = threadId?.let { arrayOf(it.toString()) }+ return runCatching {+ context.contentResolver.query(+ Telephony.Mms.CONTENT_URI,+ arrayOf(+ Telephony.Mms._ID,+ Telephony.Mms.THREAD_ID,+ Telephony.Mms.DATE,+ Telephony.Mms.MESSAGE_BOX,+ Telephony.Mms.READ,+ Telephony.Mms.SUBSCRIPTION_ID,+ ),+ selection, args,+ "${Telephony.Mms.DATE} ASC",+ )?.use { c ->+ val idIdx = c.getColumnIndexOrThrow(Telephony.Mms._ID)+ val threadIdx = c.getColumnIndexOrThrow(Telephony.Mms.THREAD_ID)+ val dateIdx = c.getColumnIndexOrThrow(Telephony.Mms.DATE)+ val boxIdx = c.getColumnIndexOrThrow(Telephony.Mms.MESSAGE_BOX)+ val readIdx = c.getColumnIndexOrThrow(Telephony.Mms.READ)+ val subIdx = c.getColumnIndex(Telephony.Mms.SUBSCRIPTION_ID)+ buildList {+ while (c.moveToNext()) {+ val mmsId = c.getLong(idIdx)+ val box = c.getInt(boxIdx)+ val outgoing = box == Telephony.Mms.MESSAGE_BOX_SENT ||+ box == Telephony.Mms.MESSAGE_BOX_OUTBOX+ val (text, attachments) = loadMmsParts(context, mmsId)+ val sender = if (!outgoing) loadMmsSender(context, mmsId) else null+ add(+ SmsMessage(+ // Keep MMS ids clear of SMS ids (both are provider row ids).+ id = mmsId or 0x2_0000_0000L,+ threadId = c.getLong(threadIdx),+ address = sender.orEmpty(),+ body = text,+ // MMS DATE is in seconds, unlike SMS (ms).+ timestampMillis = c.getLong(dateIdx) * 1000L,+ outgoing = outgoing,+ read = c.getInt(readIdx) != 0,+ attachments = attachments,+ subscriptionId = subIdx.takeIf { it >= 0 }?.let { c.getInt(it) }?.takeIf { it >= 0 },+ senderAddress = sender,+ status = if (outgoing) MessageStatus.Sent else MessageStatus.None,+ )+ )+ }+ }+ }.orEmpty()+ }.getOrDefault(emptyList())+ }++ /** Extract the text body + image attachments from an MMS message's parts. */+ private fun loadMmsParts(context: Context, mmsId: Long): Pair<String, List<CommunicateAttachment>> {+ val text = StringBuilder()+ val attachments = ArrayList<CommunicateAttachment>()+ runCatching {+ context.contentResolver.query(+ Uri.parse("content://mms/part"),+ arrayOf("_id", "ct", "text", "_data"),+ "mid = ?", arrayOf(mmsId.toString()), null,+ )?.use { c ->+ val idIdx = c.getColumnIndexOrThrow("_id")+ val ctIdx = c.getColumnIndexOrThrow("ct")+ val textIdx = c.getColumnIndexOrThrow("text")+ val dataIdx = c.getColumnIndexOrThrow("_data")+ while (c.moveToNext()) {+ val ct = c.getString(ctIdx).orEmpty()+ when {+ ct == "text/plain" -> {+ val hasData = c.getString(dataIdx) != null+ if (hasData) {+ // Body stored as a file part; read via the part content uri.+ text.append(readMmsTextPart(context, c.getLong(idIdx)))+ } else {+ text.append(c.getString(textIdx).orEmpty())+ }+ }+ ct.startsWith("image/") || ct.startsWith("video/") -> {+ attachments.add(+ CommunicateAttachment(+ contentUri = "content://mms/part/${c.getLong(idIdx)}",+ mimeType = ct,+ ),+ )+ }+ // application/smil and others are ignored.+ }+ } }- .sortedByDescending { it.timestampMillis }+ }+ return text.toString() to attachments } + private fun readMmsTextPart(context: Context, partId: Long): String = runCatching {+ context.contentResolver.openInputStream(Uri.parse("content://mms/part/$partId"))?.use {+ it.readBytes().toString(Charsets.UTF_8)+ }.orEmpty()+ }.getOrDefault("")++ /** The inbound sender address for an MMS (Addr rows with type=FROM=137). */+ private fun loadMmsSender(context: Context, mmsId: Long): String? = runCatching {+ context.contentResolver.query(+ Uri.parse("content://mms/$mmsId/addr"),+ arrayOf("address", "type"),+ "type = 137", null, null,+ )?.use { c ->+ val addrIdx = c.getColumnIndexOrThrow("address")+ if (c.moveToFirst()) c.getString(addrIdx)?.takeIf { it.isNotBlank() && it != "insert-address-token" } else null+ }+ }.getOrNull()+ fun loadSmsMessages(context: Context, threadId: Long?): List<SmsMessage> { if (!context.hasPermission(Manifest.permission.READ_SMS)) return emptyList() @@ -169,6 +335,7 @@ object CommunicateRepository { Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.READ,+ Telephony.Sms.STATUS, Telephony.Sms.SUBSCRIPTION_ID, ) val selection = threadId?.let { "${Telephony.Sms.THREAD_ID} = ?" }@@ -189,9 +356,14 @@ object CommunicateRepository { val date = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE) val type = cursor.getColumnIndexOrThrow(Telephony.Sms.TYPE) val read = cursor.getColumnIndexOrThrow(Telephony.Sms.READ)+ val status = cursor.getColumnIndex(Telephony.Sms.STATUS) val sub = cursor.getColumnIndex(Telephony.Sms.SUBSCRIPTION_ID) while (cursor.moveToNext()) {+ val msgType = cursor.getInt(type)+ val outgoing = msgType == Telephony.Sms.MESSAGE_TYPE_SENT ||+ msgType == Telephony.Sms.MESSAGE_TYPE_OUTBOX+ val statusVal = status.takeIf { it >= 0 }?.let { cursor.getInt(it) } ?: -1 add( SmsMessage( id = cursor.getLong(id),@@ -199,10 +371,10 @@ object CommunicateRepository { address = cursor.getString(address).orEmpty(), body = cursor.getString(body).orEmpty(), timestampMillis = cursor.getLong(date),- outgoing = cursor.getInt(type) == Telephony.Sms.MESSAGE_TYPE_SENT ||- cursor.getInt(type) == Telephony.Sms.MESSAGE_TYPE_OUTBOX,+ outgoing = outgoing, read = cursor.getInt(read) != 0, subscriptionId = sub.takeIf { it >= 0 }?.let { cursor.getInt(it) }?.takeIf { it >= 0 },+ status = smsStatus(msgType, outgoing, statusVal), ) ) }@@ -211,6 +383,15 @@ object CommunicateRepository { }.getOrDefault(emptyList()) } + /** Map a SIM SMS/MMS provider TYPE + STATUS into the shared [MessageStatus] tick model. */+ private fun smsStatus(msgType: Int, outgoing: Boolean, status: Int): MessageStatus = when {+ msgType == Telephony.Sms.MESSAGE_TYPE_FAILED -> MessageStatus.Failed+ !outgoing -> MessageStatus.None+ status == Telephony.Sms.STATUS_COMPLETE -> MessageStatus.Delivered+ status == Telephony.Sms.STATUS_FAILED -> MessageStatus.Failed+ else -> MessageStatus.Sent // STATUS_PENDING / STATUS_NONE → single tick+ }+ fun findContactName(context: Context, number: String): String? { if (!context.hasPermission(Manifest.permission.READ_CONTACTS) || number.isBlank()) return null return runCatching {@@ -284,6 +465,17 @@ object CommunicateRepository { Telephony.Threads.getOrCreateThreadId(context, address) }.getOrNull() + /**+ * Get (or create) the provider thread id for a multi-recipient MMS group thread. All replies to+ * a group land in this single thread. Returns null if the set is empty or the provider rejects+ * it (e.g. MMS unavailable). Used by both group creation and group MMS send.+ */+ fun getOrCreateSmsGroupThreadId(context: Context, recipients: List<String>): Long? = runCatching {+ val set = recipients.map { it.trim() }.filter { it.isNotEmpty() }.toSet()+ if (set.isEmpty()) return null+ Telephony.Threads.getOrCreateThreadId(context, set)+ }.getOrNull()+ // ------------------------------------------------------------------ // Google Voice merge (second line) //@@ -304,7 +496,9 @@ object CommunicateRepository { /** Route by line: SIM threads read the provider; GV threads hit `api2thread/get`. */ suspend fun loadSmsMessagesMerged(context: Context, thread: SmsThread): List<SmsMessage> = when (thread.line) {- CommunicateLine.Sim -> loadSmsMessages(context, thread.threadId)+ CommunicateLine.Sim -> (loadSmsMessages(context, thread.threadId) ++ loadMmsMessages(context, thread.threadId))+ .sortedBy { it.timestampMillis } CommunicateLine.GoogleVoice -> { val remoteId = thread.remoteId ?: return emptyList() runCatching {@@ -339,11 +533,18 @@ object CommunicateRepository { body: String, threadRemoteId: String? = null, attachments: List<CommunicateAttachment> = emptyList(),+ participants: List<String> = emptyList(), ): Boolean = when (choice) {- is LineChoice.Sim -> if (attachments.isEmpty()) {- sendSimSms(context, choice.subscriptionId, address, body)- } else {- false+ is LineChoice.Sim -> withContext(Dispatchers.IO) {+ // Group (multi-recipient) or media messages go out as MMS so all replies land in one+ // thread; plain 1:1 text stays SMS.+ val recipients = participants.map { it.trim() }.filter { it.isNotEmpty() }.ifEmpty { listOf(address) }+ val isGroup = recipients.size > 1+ if (attachments.isEmpty() && !isGroup) {+ sendSimSms(context, choice.subscriptionId, address, body)+ } else {+ sendSimMms(context, choice.subscriptionId, recipients, body, attachments)+ } } LineChoice.GoogleVoice -> runCatching { // The bot-defense token is minted invisibly in an offscreen WebView; the app then@@ -365,16 +566,19 @@ object CommunicateRepository { // For WhatsApp the conversation is addressed by JID: use the thread's remoteId when // replying to an existing chat, else derive a 1:1 JID from the phone number. val jid = threadRemoteId ?: toWhatsAppJid(context, address)- val ok = if (attachments.isEmpty()) {+ val sentId = if (attachments.isEmpty()) { WhatsAppClient.sendMessage(jid, body) } else { // Media send goes through the dedicated path; here just send any caption text.- if (body.isNotBlank()) WhatsAppClient.sendMessage(jid, body) else true+ if (body.isNotBlank()) WhatsAppClient.sendMessage(jid, body) else "" } // Echo the outgoing message into the local cache so it shows in our own thread- // (a primary-only line gets no server echo of its own sends).- if (ok && body.isNotBlank()) cacheOutgoingWhatsApp(context, jid, body)- ok+ // (a primary-only line gets no server echo of its own sends). Cache under the real+ // WA message id so delivery/read receipts can advance its status ticks.+ if (sentId != null && body.isNotBlank()) {+ cacheOutgoingWhatsApp(context, jid, body, sentId.ifBlank { "local-${java.util.UUID.randomUUID()}" })+ }+ sentId != null }.getOrDefault(false) } }@@ -405,12 +609,96 @@ object CommunicateRepository { put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_SENT) if (subscriptionId >= 0) put(Telephony.Sms.SUBSCRIPTION_ID, subscriptionId) }- context.contentResolver.insert(Telephony.Sms.Sent.CONTENT_URI, values)+ context.contentResolver.insert(Telephony.Sms.Sent.CONTENT_URI, values)+ }+ true+ }.getOrDefault(false)+ }++ private fun smsManagerFor(context: Context, subscriptionId: Int): android.telephony.SmsManager {+ val base = context.getSystemService(android.telephony.SmsManager::class.java)+ return if (subscriptionId >= 0) base.createForSubscriptionId(subscriptionId) else base+ }++ /**+ * Send a group / media message as MMS via [android.telephony.SmsManager.sendMultimediaMessage].+ * Composes an M-Send.req PDU ([MmsPdu]), hands it to the system MMS service through a+ * FileProvider uri, and records the message in the provider so it shows in the group thread.+ * Best-effort / carrier-dependent (see plan caveat).+ */+ private fun sendSimMms(+ context: Context,+ subscriptionId: Int,+ recipients: List<String>,+ body: String,+ attachments: List<CommunicateAttachment>,+ ): Boolean {+ if (recipients.isEmpty()) return false+ if (!context.hasPermission(Manifest.permission.SEND_SMS)) return false+ return runCatching {+ val txnId = "T${System.currentTimeMillis()}"+ val mediaParts = attachments.mapNotNull { att ->+ runCatching {+ val bytes = context.contentResolver.openInputStream(att.contentUri.toUri())+ ?.use { it.readBytes() } ?: return@mapNotNull null+ com.vayunmathur.communicate.telephony.MmsPdu.Part(att.mimeType, bytes)+ }.getOrNull() }+ val pdu = com.vayunmathur.communicate.telephony.MmsPdu.composeSendReq(+ txnId, recipients, body.takeIf { it.isNotBlank() }, mediaParts,+ )+ val dir = java.io.File(context.cacheDir, "mms").apply { mkdirs() }+ val file = java.io.File(dir, "$txnId.pdu").apply { writeBytes(pdu) }+ val uri = androidx.core.content.FileProvider.getUriForFile(+ context, "${context.packageName}.mmsfileprovider", file,+ )+ smsManagerFor(context, subscriptionId).sendMultimediaMessage(context, uri, null, null, null)+ persistOutgoingMms(context, subscriptionId, recipients, body) true }.getOrDefault(false) } + /** Record an outgoing MMS (Sent box) + its text part + recipient/sender addr rows. */+ private fun persistOutgoingMms(+ context: Context,+ subscriptionId: Int,+ recipients: List<String>,+ body: String,+ ) {+ runCatching {+ val threadId = getOrCreateSmsGroupThreadId(context, recipients)+ val values = android.content.ContentValues().apply {+ if (threadId != null) put(Telephony.Mms.THREAD_ID, threadId)+ put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L)+ put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT)+ put(Telephony.Mms.READ, 1)+ put(Telephony.Mms.SEEN, 1)+ put(Telephony.Mms.MESSAGE_TYPE, 128) // M-Send.req+ if (subscriptionId >= 0) put(Telephony.Mms.SUBSCRIPTION_ID, subscriptionId)+ }+ val mmsUri = context.contentResolver.insert(Telephony.Mms.CONTENT_URI, values) ?: return+ val mmsId = mmsUri.lastPathSegment ?: return+ // Text part.+ if (body.isNotBlank()) {+ val partValues = android.content.ContentValues().apply {+ put("mid", mmsId)+ put("ct", "text/plain")+ put("text", body)+ }+ context.contentResolver.insert(Uri.parse("content://mms/$mmsId/part"), partValues)+ }+ // Address rows: TO (151) per recipient.+ for (r in recipients) {+ val addrValues = android.content.ContentValues().apply {+ put("address", r)+ put("type", 151)+ put("charset", 106)+ }+ context.contentResolver.insert(Uri.parse("content://mms/$mmsId/addr"), addrValues)+ }+ }+ }+ /** Toggle a Google Voice thread attribute (read/archive/spam) via batchupdateattributes. */ suspend fun updateGoogleVoiceThread( context: Context,@@ -449,18 +737,23 @@ object CommunicateRepository { val isVirtualLine = setOf(CommunicateLine.GoogleVoice, CommunicateLine.WhatsApp) private suspend fun loadWhatsAppThreads(context: Context): List<SmsThread> {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return emptyList() if (!WhatsAppLineSession.get(context).isSignedIn()) return emptyList() return runCatching { val db = WhatsAppDatabase.getDatabase(context) db.cachedMessageDao().getLatestPerConversation().map { m -> val sd = WhatsAppServiceData.parse(m.serviceData) val jid = m.conversationJid- val isGroup = sd?.isGroup ?: jid.endsWith("@g.us")- val unread = db.conversationDao().getConversation(jid)?.unreadCount ?: 0+ val conv = db.conversationDao().getConversation(jid)+ val isGroup = conv?.isGroup ?: sd?.isGroup ?: jid.endsWith("@g.us")+ val unread = conv?.unreadCount ?: 0+ val participants = parseParticipantsCsv(conv?.participants)+ val groupTitle = conv?.name?.takeIf { it.isNotBlank() } SmsThread( threadId = stableThreadId(jid), address = jidToDisplayAddress(jid),- displayName = whatsAppDisplayName(context, jid, sd),+ displayName = if (isGroup) (groupTitle ?: whatsAppDisplayName(context, jid, sd))+ else whatsAppDisplayName(context, jid, sd), snippet = if (m.isRevoked) "This message was deleted" else m.body, timestampMillis = m.timestamp, unreadCount = unread,@@ -468,11 +761,25 @@ object CommunicateRepository { remoteId = jid, isGroup = isGroup, avatarUrl = null,+ participants = participants,+ groupTitle = groupTitle, ) } }.getOrDefault(emptyList()) } + /** Parse the conversation's stored participants column (JSON array of names) into a list. */+ private fun parseParticipantsCsv(stored: String?): List<String> {+ if (stored.isNullOrBlank()) return emptyList()+ return runCatching {+ val arr = org.json.JSONArray(stored)+ (0 until arr.length()).map { arr.getString(it) }+ }.getOrElse {+ // Legacy/plain CSV fallback.+ stored.split(",").map { it.trim() }.filter { it.isNotEmpty() }+ }+ }+ private suspend fun loadWhatsAppMessages(context: Context, jid: String): List<SmsMessage> = runCatching { val db = WhatsAppDatabase.getDatabase(context)@@ -488,6 +795,12 @@ object CommunicateRepository { line = CommunicateLine.WhatsApp, remoteId = m.messageId, serviceData = m.serviceData,+ senderAddress = m.senderJid.takeIf { it.isNotBlank() && !m.outgoing },+ status = m.status.let { s ->+ com.vayunmathur.communicate.data.MessageStatus.entries.getOrElse(s) {+ com.vayunmathur.communicate.data.MessageStatus.None+ }+ }, ) } }.getOrDefault(emptyList())@@ -532,6 +845,27 @@ object CommunicateRepository { suspend fun sendWhatsAppMedia(jid: String, bytes: ByteArray, mimeType: String, fileName: String?): Boolean = withContext(Dispatchers.IO) { WhatsAppClient.sendMedia(jid, bytes, mimeType, fileName) } + /** True only when the WhatsApp primary client is logged in (needed for send/group ops). */+ fun isWhatsAppConnected(): Boolean = WhatsAppClient.isConnected()++ /**+ * Create a WhatsApp group with [subject] and the given [contacts] (phone numbers / addresses).+ * Each contact is normalized to a full WhatsApp user JID before the create IQ is sent. Returns+ * the new group's `@g.us` JID on success so the caller can open the thread, or null on failure.+ */+ suspend fun createWhatsAppGroup(+ context: Context,+ subject: String,+ contacts: List<String>,+ ): String? = withContext(Dispatchers.IO) {+ val jids = contacts+ .map { toWhatsAppJid(context, it) }+ .filter { it.endsWith("@s.whatsapp.net") }+ .distinct()+ if (jids.isEmpty()) return@withContext null+ WhatsAppClient.createGroup(subject, jids)+ }+ suspend fun sendWhatsAppReadReceipt( jid: String, lastMessageId: String?,@@ -611,17 +945,19 @@ object CommunicateRepository { } /** Insert an outgoing WhatsApp message into the local cache so it shows in our own thread. */- private suspend fun cacheOutgoingWhatsApp(context: Context, jid: String, body: String) {+ private suspend fun cacheOutgoingWhatsApp(context: Context, jid: String, body: String, messageId: String) { runCatching { val db = WhatsAppDatabase.getDatabase(context) val now = System.currentTimeMillis() db.cachedMessageDao().upsert( WhatsAppCachedMessage(- messageId = "local-${java.util.UUID.randomUUID()}",+ messageId = messageId, conversationJid = jid, body = body, timestamp = now, outgoing = true,+ // Sent (1) = single grey tick until a delivery/read receipt advances it.+ status = 1, ), ) val existing = db.conversationDao().getConversation(jid)
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktindex 9ca27a650d..814d39d90c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -73,6 +73,9 @@ object WhatsAppClient { val source: MessageSource = MessageSource.WHATSAPP + /** True only when the Noise socket is logged in (`<success>`). Group/message ops require it. */+ fun isConnected(): Boolean = _state.value is State.Connected+ private val _state = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> = _state.asStateFlow() @@ -1162,12 +1165,6 @@ object WhatsAppClient { val isDelivered = receiptType == null || receiptType.isEmpty() if (!isRead && !isDelivered) return - // Log delivery receipts (Go handleWAReceipt ReceiptTypeDelivered)- if (isDelivered) {- Log.d(TAG, "Delivery receipt from ${node.attrs["from"]} for ${node.attrs["id"]}")- return- }- val from = node.attrs["from"] ?: return val participant = node.attrs["participant"] @@ -1177,11 +1174,15 @@ object WhatsAppClient { val messageId = node.attrs["id"] ?: return val timestamp = (node.attrs["t"]?.toLongOrNull() ?: System.currentTimeMillis() / 1000) * 1000 + // Delivery (type absent/empty) advances our sent message to "delivered" (grey ✓✓); a+ // read/read-self receipt advances to "read" (blue ✓✓). Both are surfaced as ReadReceipt. _events.emit(WhatsAppEvent.ReadReceipt( source = MessageSource.WHATSAPP, conversationId = "wa:$from", messageId = messageId,+ senderId = sender, timestamp = timestamp,+ isDelivery = isDelivered, )) // Handle additional message IDs in list node@@ -1192,7 +1193,9 @@ object WhatsAppClient { source = MessageSource.WHATSAPP, conversationId = "wa:$from", messageId = itemId,+ senderId = sender, timestamp = timestamp,+ isDelivery = isDelivered, )) } }@@ -1863,6 +1866,7 @@ object WhatsAppClient { if (msgs.isEmpty()) return 0 // Register the conversation row first.+ val isGroupChat = chatJid.endsWith("@g.us") _events.emit( WhatsAppEvent.ConversationUpdate( source = MessageSource.WHATSAPP,@@ -1873,6 +1877,7 @@ object WhatsAppClient { lastPreview = lastBody, lastTimestamp = lastTs, unreadCount = conv.unreadCount,+ isGroup = isGroupChat, ) ) // Then backfill its messages.@@ -1988,20 +1993,24 @@ object WhatsAppClient { return out.toByteArray() } - suspend fun sendMessage(conversationId: String, body: String): Boolean {- if (_state.value !is State.Connected) { WhatsAppDiag.log(TAG, "send: not connected"); return false }- val ws = webSocket ?: return false+ /**+ * Send a 1:1/group text message. Returns the WhatsApp message id on success (so callers can cache+ * the outgoing echo under the same id that delivery/read receipts reference), or null on failure.+ */+ suspend fun sendMessage(conversationId: String, body: String): String? {+ if (_state.value !is State.Connected) { WhatsAppDiag.log(TAG, "send: not connected"); return null }+ val ws = webSocket ?: return null - val to = extractJid(conversationId) ?: run { WhatsAppDiag.log(TAG, "send: bad convId $conversationId"); return false }+ val to = extractJid(conversationId) ?: run { WhatsAppDiag.log(TAG, "send: bad convId $conversationId"); return null } val id = WhatsAppProtocol.generateMessageId(authData?.wid) WhatsAppDiag.log(TAG, "send: building message to $to") - val node = buildEncryptedTextNode(to, id, body) ?: run { WhatsAppDiag.log(TAG, "send: build FAILED (no enc)"); return false }+ val node = buildEncryptedTextNode(to, id, body) ?: run { WhatsAppDiag.log(TAG, "send: build FAILED (no enc)"); return null } pendingMessageIDs.add(id) val sent = ws.send(WhatsAppProtocol.encodeNode(node)) if (!sent) pendingMessageIDs.remove(id) WhatsAppDiag.log(TAG, "send: stanza sent=$sent id=$id")- return sent+ return if (sent) id else null } // ---------------------------------------------------------------------------------------------@@ -2877,6 +2886,40 @@ object WhatsAppClient { return ws.send(WhatsAppProtocol.encodeNode(node)) } + /**+ * Create a new group with [subject] and [participantJids] (full user JIDs, e.g.+ * `[email protected]`). Sends the `w:g2` create IQ, awaits the `<group>` result, and+ * returns the new group's `@g.us` JID (or null on failure). On success it also fetches + emits+ * the group info so the thread appears named + flagged with its participants persisted.+ * Ref whatsmeow group.go CreateGroup.+ */+ suspend fun createGroup(subject: String, participantJids: List<String>): String? {+ if (_state.value !is State.Connected) { WhatsAppDiag.log(TAG, "createGroup: not connected"); return null }+ if (participantJids.isEmpty()) { WhatsAppDiag.log(TAG, "createGroup: no participants"); return null }++ val id = generateMessageId()+ // whatsmeow uses a client-chosen unique key (unix seconds) echoed back in the response.+ val key = (System.currentTimeMillis() / 1000).toString()+ val iq = WhatsAppProtocol.buildCreateGroup(subject, participantJids, id, key)+ val resp = sendIqAndWait(iq) ?: run { WhatsAppDiag.log(TAG, "createGroup: no response"); return null }+ if (resp.attrs["type"] == "error") {+ val err = resp.getChildByTag("error")+ WhatsAppDiag.log(+ TAG,+ "createGroup: server error code=${err?.attrs?.get("code")} text=${err?.attrs?.get("text")}",+ )+ return null+ }+ val group = resp.getChildByTag("group") ?: run { WhatsAppDiag.log(TAG, "createGroup: no <group>"); return null }+ // Response group node carries the new JID either as `jid` or as a bare `id` local-part.+ val groupJid = group.attrs["jid"]+ ?: group.attrs["id"]?.let { if (it.contains("@")) it else "[email protected]" }+ ?: run { WhatsAppDiag.log(TAG, "createGroup: no group jid in resp"); return null }+ WhatsAppDiag.log(TAG, "createGroup: created $groupJid")+ runCatching { fetchAndEmitGroupInfo(groupJid) }+ return groupJid+ }+ /** * Delete a chat, optionally leaving group, with AppState mutations. * From Go HandleMatrixDeleteChat.
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.ktindex 48b6327a78..54f4929806 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt@@ -24,6 +24,9 @@ import com.vayunmathur.library.util.DatabaseMigrations * * v7 (Rust migration): E2E tables now hold Rust's own versioned blobs (RECORD_VERSION=1) * rather than Java SignalRecord. Old Java blobs are incompatible, so migration clears E2E tables.+ *+ * communicate v2: adds message delivery status (sent/delivered/read ticks) and group metadata+ * (isGroup/name/participants) on conversations. */ @Database( entities = [@@ -44,7 +47,7 @@ import com.vayunmathur.library.util.DatabaseMigrations WhatsAppCachedMessage::class, WhatsAppCachedReaction::class, ],- version = 1,+ version = 2, exportSchema = false ) @TypeConverters(WhatsAppTypeConverters::class)@@ -68,8 +71,28 @@ abstract class WhatsAppDatabase : RoomDatabase() { @Volatile private var INSTANCE: WhatsAppDatabase? = null - // Fresh database in communicate (v1) — no migration history to carry from messages.- override val migrations: List<Migration> = emptyList()+ /**+ * v1 → v2: message delivery status (ticks) + group metadata on conversations. All new+ * columns are additive with defaults, so existing rows stay valid.+ */+ private val MIGRATION_1_2 = object : Migration(1, 2) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL(+ "ALTER TABLE whatsapp_cached_message ADD COLUMN status INTEGER NOT NULL DEFAULT 0",+ )+ db.execSQL(+ "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN isGroup INTEGER NOT NULL DEFAULT 0",+ )+ db.execSQL(+ "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN name TEXT",+ )+ db.execSQL(+ "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN participants TEXT NOT NULL DEFAULT ''",+ )+ }+ }++ override val migrations: List<Migration> = listOf(MIGRATION_1_2) fun getDatabase(context: Context): WhatsAppDatabase { return INSTANCE ?: synchronized(this) {@@ -113,6 +136,12 @@ data class WhatsAppConversation( val ephemeralSettingTimestamp: Long = 0L, val markedAsUnread: Boolean = false, val unreadCount: Int = 0,+ /** communicate v2: true for group chats (@g.us). */+ val isGroup: Boolean = false,+ /** communicate v2: group subject / display name when known. */+ val name: String? = null,+ /** communicate v2: CSV of participant JIDs for groups (empty for 1:1). */+ val participants: String = "", ) @Dao@@ -410,6 +439,11 @@ data class WhatsAppCachedMessage( val mediaMime: String? = null, val mediaName: String? = null, val serviceData: String? = null,+ /**+ * communicate v2: outgoing delivery status, encoded as the [com.vayunmathur.communicate.data.MessageStatus]+ * ordinal (0=None, 1=Sent, 2=Delivered, 3=Read, 4=Failed). Inbound messages stay 0.+ */+ val status: Int = 0, ) @Dao@@ -443,6 +477,14 @@ interface WhatsAppCachedMessageDao { @Query("UPDATE whatsapp_cached_message SET serviceData = :serviceData WHERE messageId = :messageId") suspend fun updateServiceData(messageId: String, serviceData: String?) + /** Advance to Delivered (2) only from a lower state (won't downgrade a Read message). */+ @Query("UPDATE whatsapp_cached_message SET status = 2 WHERE messageId = :messageId AND status < 2")+ suspend fun markDelivered(messageId: String)++ /** Advance to Read (3) only from a lower state. */+ @Query("UPDATE whatsapp_cached_message SET status = 3 WHERE messageId = :messageId AND status < 3")+ suspend fun markReadStatus(messageId: String)+ @Query("DELETE FROM whatsapp_cached_message WHERE conversationJid = :jid") suspend fun deleteConversation(jid: String)
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.ktindex 34a59676e2..f6fea86532 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt@@ -124,7 +124,23 @@ class WhatsAppEventProcessor(private val db: WhatsAppDatabase) { } is WhatsAppEvent.ConversationUpdate -> {- touchConversation(chatJid(event.conversationId), event.lastTimestamp, incrementUnread = false)+ val jid = chatJid(event.conversationId)+ touchConversation(jid, event.lastTimestamp, incrementUnread = false)+ // Persist group metadata (name + participants) so groups render named/flagged and+ // survive restarts. Only overwrite with non-empty values so a later bare update+ // (e.g. a plain message touch) doesn't clobber a good name/participant list.+ val isGroup = event.isGroup || jid.endsWith("@g.us")+ val participantsJson = participantsJsonFromServiceData(event.serviceData)+ if (isGroup || !event.peerName.isNullOrBlank() || participantsJson != null) {+ val existing = conversations.getConversation(jid) ?: WhatsAppConversation(chatJid = jid)+ conversations.upsert(+ existing.copy(+ isGroup = isGroup || existing.isGroup,+ name = event.peerName?.takeIf { it.isNotBlank() } ?: existing.name,+ participants = participantsJson ?: existing.participants,+ ),+ )+ } } is WhatsAppEvent.ConversationDeleted -> {@@ -132,6 +148,15 @@ class WhatsAppEventProcessor(private val db: WhatsAppDatabase) { conversations.delete(chatJid(event.conversationId)) } + is WhatsAppEvent.ReadReceipt -> {+ // Advance the outgoing message's tick: delivery → Delivered (grey ✓✓), read → Read+ // (blue ✓✓). The client emits one event per message id (incl. <list><item> batches),+ // so a single update per event covers the batch case.+ event.messageId?.let { id ->+ if (event.isDelivery) messages.markDelivered(id) else messages.markReadStatus(id)+ }+ }+ is WhatsAppEvent.HistorySync -> { val rows = ArrayList<WhatsAppCachedMessage>() for (conv in event.conversations) {@@ -167,6 +192,21 @@ class WhatsAppEventProcessor(private val db: WhatsAppDatabase) { return s.substring(0, at).substringBefore(':') + s.substring(at) } + /**+ * Extract the group's participant display names from a [WhatsAppEvent.ConversationUpdate]'s+ * serviceData blob (`{"participantNames":[...]}`, emitted by `fetchAndEmitGroupInfo`) and+ * re-serialize them as a JSON array for the conversation's `participants` column. Returns null+ * when there is nothing to persist (so we don't clobber an existing list).+ */+ private fun participantsJsonFromServiceData(serviceData: String?): String? {+ if (serviceData.isNullOrBlank()) return null+ return runCatching {+ val arr = org.json.JSONObject(serviceData).optJSONArray("participantNames") ?: return null+ if (arr.length() == 0) return null+ arr.toString()+ }.getOrNull()+ }+ private suspend fun touchConversation(jid: String, timestamp: Long, incrementUnread: Boolean) { val existing = conversations.getConversation(jid) val unread = (existing?.unreadCount ?: 0) + if (incrementUnread) 1 else 0
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppFeature.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppFeature.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppFeature.ktnew file mode 100644index 0000000000..cc70c01b4a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppFeature.kt@@ -0,0 +1,18 @@+package com.vayunmathur.communicate.data.whatsapp++import com.vayunmathur.communicate.BuildConfig++/**+ * Single on/off gate for the experimental **WhatsApp primary client** feature.+ *+ * Backed by [BuildConfig.DEV_BUILD], which is `true` for `assembleDev`/`assembleDebug` and `false`+ * for `assembleRelease`. Because it's a compile-time constant, every `if (WhatsAppFeature.enabled)`+ * branch (and everything it reaches) is stripped from release builds by R8, so the release variant+ * never registers, connects, or exposes WhatsApp UI/lines.+ *+ * WhatsApp is an unofficial primary-client reimplementation and carries real ToS/ban risk (a live+ * test number was banned with `violation_type:15`), so it must not ship in the release variant.+ */+object WhatsAppFeature {+ val enabled: Boolean get() = BuildConfig.DEV_BUILD+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.ktindex d5e626596f..cc48522302 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppProtocol.kt@@ -1776,6 +1776,39 @@ object WhatsAppProtocol { ) } + /**+ * Build a create-group IQ node (whatsmeow group.go CreateGroup):+ * `<iq to="g.us" type="set" xmlns="w:g2" id=...><create subject=".." key="..">+ * <participant jid="..."/>…</create></iq>`.+ * [key] is a client-chosen unique id echoed back in the response so we can correlate.+ */+ fun buildCreateGroup(+ subject: String,+ participantJids: List<String>,+ id: String,+ key: String,+ ): Node {+ val participants = participantJids.map { jid ->+ Node(tag = "participant", attrs = mapOf("jid" to jid))+ }+ return Node(+ tag = "iq",+ attrs = mapOf(+ "id" to id,+ "type" to "set",+ "xmlns" to "w:g2",+ "to" to "g.us",+ ),+ content = listOf(+ Node(+ tag = "create",+ attrs = mapOf("subject" to subject, "key" to key),+ content = participants,+ ),+ ),+ )+ }+ /** * Build a group participant change IQ node. * From whatsmeow group.go UpdateGroupParticipants
communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.ktindex 046281f065..8515ee25f5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsDeliverReceiver.kt@@ -1,9 +1,129 @@ package com.vayunmathur.communicate.telephony +import android.app.PendingIntent import android.content.BroadcastReceiver+import android.content.ContentValues import android.content.Context import android.content.Intent+import android.net.Uri+import android.provider.Telephony+import android.telephony.SmsManager+import android.util.Log+import java.io.File +/**+ * Handles inbound MMS (WAP push) as the default SMS app: parse the `M-Notification.ind`, download+ * the full message via [SmsManager.downloadMultimediaMessage], then parse the retrieved+ * `M-Retrieve.conf` and insert it (sender + text + media parts) into the MMS provider so it shows in+ * the (group) thread. Best-effort / carrier-dependent — see the plan caveat.+ */ class MmsDeliverReceiver : BroadcastReceiver() {- override fun onReceive(context: Context, intent: Intent) = Unit+ override fun onReceive(context: Context, intent: Intent) {+ when (intent.action) {+ Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION -> handlePush(context, intent)+ ACTION_MMS_DOWNLOADED -> handleDownloaded(context, intent)+ else -> Unit+ }+ }++ private fun handlePush(context: Context, intent: Intent) {+ val pdu = intent.getByteArrayExtra("data") ?: return+ runCatching {+ val notif = MmsPduReader.parseNotification(pdu)+ val location = notif.contentLocation ?: run {+ Log.w(TAG, "MMS push had no content-location"); return+ }+ val dir = File(context.cacheDir, "mms").apply { mkdirs() }+ val file = File(dir, "in_${System.currentTimeMillis()}.pdu")+ file.createNewFile()+ val contentUri = androidx.core.content.FileProvider.getUriForFile(+ context, "${context.packageName}.mmsfileprovider", file,+ )+ // The system MMS service (phone uid) writes the downloaded PDU into our file.+ context.grantUriPermission(+ "com.android.mms.service", contentUri,+ Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION,+ )+ val done = Intent(ACTION_MMS_DOWNLOADED).apply {+ setClass(context, MmsDeliverReceiver::class.java)+ putExtra(EXTRA_FILE, file.absolutePath)+ putExtra(EXTRA_LOCATION, location)+ }+ val pi = PendingIntent.getBroadcast(+ context, location.hashCode(), done,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+ )+ val sms = context.getSystemService(SmsManager::class.java) ?: run {+ Log.w(TAG, "no SmsManager"); return+ }+ sms.downloadMultimediaMessage(context, location, contentUri, null, pi)+ Log.d(TAG, "MMS download triggered for $location")+ }.onFailure { Log.e(TAG, "handlePush failed", it) }+ }++ private fun handleDownloaded(context: Context, intent: Intent) {+ val path = intent.getStringExtra(EXTRA_FILE) ?: return+ val pending = goAsync()+ Thread {+ runCatching {+ val bytes = File(path).readBytes()+ val msg = MmsPduReader.parseRetrieved(bytes)+ insertInboundMms(context, msg)+ Log.d(TAG, "MMS stored from=${msg.from} parts=${msg.parts.size}")+ }.onFailure { Log.e(TAG, "handleDownloaded failed", it) }+ runCatching { File(path).delete() }+ pending.finish()+ }.start()+ }++ private fun insertInboundMms(context: Context, msg: MmsPduReader.Retrieved) {+ val from = msg.from+ val threadId = from?.let {+ runCatching { Telephony.Threads.getOrCreateThreadId(context, it) }.getOrNull()+ }+ val values = ContentValues().apply {+ if (threadId != null) put(Telephony.Mms.THREAD_ID, threadId)+ put(Telephony.Mms.DATE, msg.dateSeconds)+ put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_INBOX)+ put(Telephony.Mms.READ, 0)+ put(Telephony.Mms.SEEN, 0)+ put(Telephony.Mms.MESSAGE_TYPE, 132) // M-Retrieve.conf+ msg.subject?.let { put(Telephony.Mms.SUBJECT, it) }+ }+ val mmsUri = context.contentResolver.insert(Telephony.Mms.CONTENT_URI, values) ?: return+ val mmsId = mmsUri.lastPathSegment ?: return+ // Parts.+ for (p in msg.parts) {+ val pv = ContentValues().apply {+ put("mid", mmsId)+ put("ct", p.contentType)+ if (p.contentType == "text/plain") {+ put("text", p.text.orEmpty())+ }+ }+ val partUri = context.contentResolver.insert(Uri.parse("content://mms/$mmsId/part"), pv)+ // Write binary media bytes into the part's data stream.+ if (partUri != null && !p.contentType.startsWith("text/") && p.data.isNotEmpty()) {+ runCatching {+ context.contentResolver.openOutputStream(partUri)?.use { it.write(p.data) }+ }+ }+ }+ // Sender addr row (FROM = 137).+ if (from != null) {+ val av = ContentValues().apply {+ put("address", from)+ put("type", 137)+ put("charset", 106)+ }+ context.contentResolver.insert(Uri.parse("content://mms/$mmsId/addr"), av)+ }+ }++ companion object {+ private const val TAG = "MmsDeliverReceiver"+ private const val ACTION_MMS_DOWNLOADED = "com.vayunmathur.communicate.MMS_DOWNLOADED"+ private const val EXTRA_FILE = "file"+ private const val EXTRA_LOCATION = "location"+ } }
communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPdu.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPdu.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPdu.ktnew file mode 100644index 0000000000..7aa898dbfd--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPdu.kt@@ -0,0 +1,141 @@+package com.vayunmathur.communicate.telephony++import java.io.ByteArrayOutputStream++/**+ * Minimal MMS PDU composer for outgoing group/media messages (M-Send.req), following the+ * WAP-209 MMS Encapsulation + WSP encoding specs. Supports multiple recipients (group MMS),+ * a text/plain part, and image/video parts. The resulting bytes are handed to+ * [android.telephony.SmsManager.sendMultimediaMessage] via a content Uri.+ *+ * This is a compact, dependency-free encoder (AOSP's `com.google.android.mms.pdu` is @hide).+ * It is best-effort and carrier-dependent — see the plan's caveat; the caller persists the+ * message to the provider regardless so it shows in the thread.+ */+object MmsPdu {+ // Header field identifiers (already OR'd with 0x80 = "well-known field, short form").+ private const val FIELD_MESSAGE_TYPE = 0x8C+ private const val FIELD_TRANSACTION_ID = 0x98+ private const val FIELD_MMS_VERSION = 0x8D+ private const val FIELD_FROM = 0x89+ private const val FIELD_TO = 0x97+ private const val FIELD_DATE = 0x85+ private const val FIELD_SUBJECT = 0x96+ private const val FIELD_CONTENT_TYPE = 0x84++ private const val MESSAGE_TYPE_SEND_REQ = 0x80+ private const val MMS_VERSION_1_2 = 0x92 // short-integer for version 1.2+ private const val INSERT_ADDRESS_TOKEN = 0x81+ private const val FROM_ADDRESS_PRESENT = 0x80++ private const val CT_MULTIPART_MIXED = "application/vnd.wap.multipart.mixed"++ data class Part(val contentType: String, val data: ByteArray, val name: String? = null)++ /**+ * Compose an M-Send.req PDU.+ * @param recipients E.164 / phone numbers of every group member.+ * @param text optional text body (added as a text/plain part).+ * @param mediaParts image/video parts.+ */+ fun composeSendReq(+ transactionId: String,+ recipients: List<String>,+ text: String?,+ mediaParts: List<Part> = emptyList(),+ ): ByteArray {+ val out = ByteArrayOutputStream()++ // --- Headers ---+ out.write(FIELD_MESSAGE_TYPE); out.write(MESSAGE_TYPE_SEND_REQ)+ out.write(FIELD_TRANSACTION_ID); writeTextString(out, transactionId)+ out.write(FIELD_MMS_VERSION); out.write(MMS_VERSION_1_2)+ // From: insert-address-token (the MMSC fills in our number).+ out.write(FIELD_FROM); out.write(1); out.write(INSERT_ADDRESS_TOKEN)+ // One To: header per recipient (PLMN-typed phone numbers).+ for (r in recipients) {+ out.write(FIELD_TO)+ writeEncodedString(out, "$r/TYPE=PLMN")+ }++ // --- Body: Content-Type = multipart.mixed, then the multipart entries ---+ out.write(FIELD_CONTENT_TYPE)+ writeTextString(out, CT_MULTIPART_MIXED)++ val parts = ArrayList<Part>()+ if (!text.isNullOrEmpty()) parts.add(Part("text/plain", text.toByteArray(Charsets.UTF_8)))+ parts.addAll(mediaParts)++ writeUintvar(out, parts.size.toLong())+ for ((i, p) in parts.withIndex()) {+ val headers = ByteArrayOutputStream()+ // Part content-type (part of HeadersLen).+ writeTextString(headers, p.contentType)+ // Content-Location / name so the receiver can reference the part.+ val name = p.name ?: defaultPartName(p.contentType, i)+ headers.write(0x8E) // Content-Location well-known field+ writeTextString(headers, name)+ val headerBytes = headers.toByteArray()+ writeUintvar(out, headerBytes.size.toLong())+ writeUintvar(out, p.data.size.toLong())+ out.write(headerBytes)+ out.write(p.data)+ }+ return out.toByteArray()+ }++ private fun defaultPartName(ct: String, index: Int): String = when {+ ct.startsWith("image/") -> "image_$index.${ct.substringAfter('/')}"+ ct.startsWith("video/") -> "video_$index.${ct.substringAfter('/')}"+ ct == "text/plain" -> "text_$index.txt"+ else -> "part_$index"+ }++ /** Text-string = [Quote] *TEXT End-of-string(0x00). Quote (0x7F) prefix if first byte >= 0x80. */+ private fun writeTextString(out: ByteArrayOutputStream, value: String) {+ val bytes = value.toByteArray(Charsets.UTF_8)+ if (bytes.isNotEmpty() && (bytes[0].toInt() and 0xFF) >= 0x80) out.write(0x7F)+ out.write(bytes)+ out.write(0x00)+ }++ /**+ * Encoded-string-value = Text-string | Value-length Char-set Text-string. We use the UTF-8+ * form: Value-length, charset (UTF-8 = 106 = 0x6A, as short-integer 0xEA), then the text-string.+ */+ private fun writeEncodedString(out: ByteArrayOutputStream, value: String) {+ val text = ByteArrayOutputStream()+ text.write(0xEA) // charset UTF-8 (106) as short-integer+ writeTextString(text, value)+ val body = text.toByteArray()+ writeValueLength(out, body.size.toLong())+ out.write(body)+ }++ /** Value-length = Short-length (0..30) | (0x1F Length-uintvar). */+ private fun writeValueLength(out: ByteArrayOutputStream, length: Long) {+ if (length < 31) {+ out.write(length.toInt())+ } else {+ out.write(0x1F)+ writeUintvar(out, length)+ }+ }++ /** Variable-length unsigned integer (uintvar), 7 bits per byte, MSB = continuation. */+ private fun writeUintvar(out: ByteArrayOutputStream, value: Long) {+ if (value < 0x80) {+ out.write(value.toInt())+ return+ }+ val bytes = ArrayList<Int>()+ var v = value+ bytes.add((v and 0x7F).toInt())+ v = v shr 7+ while (v > 0) {+ bytes.add(((v and 0x7F) or 0x80).toInt())+ v = v shr 7+ }+ for (i in bytes.indices.reversed()) out.write(bytes[i])+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPduReader.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPduReader.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPduReader.ktnew file mode 100644index 0000000000..56e24eb1a0--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/MmsPduReader.kt@@ -0,0 +1,220 @@+package com.vayunmathur.communicate.telephony++/**+ * Minimal reader for inbound MMS PDUs: the WAP-push `M-Notification.ind` (to extract the+ * content-location we must download from) and the downloaded `M-Retrieve.conf` (headers ++ * multipart body → sender + text + media parts). Dependency-free; every entry point is defensive+ * and returns partial results rather than throwing. Best-effort / carrier-dependent.+ */+object MmsPduReader {+ // Field ids (with the 0x80 "well-known short field" bit set).+ private const val F_MESSAGE_TYPE = 0x8C+ private const val F_TRANSACTION_ID = 0x98+ private const val F_MMS_VERSION = 0x8D+ private const val F_FROM = 0x89+ private const val F_SUBJECT = 0x96+ private const val F_MESSAGE_CLASS = 0x8A+ private const val F_MESSAGE_SIZE = 0x8E+ private const val F_EXPIRY = 0x88+ private const val F_CONTENT_LOCATION = 0x83+ private const val F_CONTENT_TYPE = 0x84+ private const val F_DATE = 0x85+ private const val F_MESSAGE_ID = 0x8B+ private const val F_PRIORITY = 0x8F+ private const val F_DELIVERY_REPORT = 0x86+ private const val F_READ_REPORT = 0x90++ data class Notification(val contentLocation: String?, val transactionId: String?)++ data class RetrievedPart(val contentType: String, val data: ByteArray, val text: String?)+ data class Retrieved(+ val from: String?,+ val subject: String?,+ val text: String?,+ val parts: List<RetrievedPart>,+ val dateSeconds: Long,+ )++ /** Parse an M-Notification.ind to get the content-location URL to download. */+ fun parseNotification(pdu: ByteArray): Notification {+ val r = Reader(pdu)+ var contentLocation: String? = null+ var transactionId: String? = null+ while (r.hasRemaining()) {+ val field = r.readByte() and 0xFF+ when (field) {+ F_MESSAGE_TYPE, F_MMS_VERSION, F_MESSAGE_CLASS, F_PRIORITY,+ F_DELIVERY_REPORT, F_READ_REPORT -> r.readByte()+ F_TRANSACTION_ID -> transactionId = r.readTextString()+ F_MESSAGE_ID -> r.readTextString()+ F_SUBJECT -> r.readEncodedString()+ F_FROM -> r.skipValueLength()+ F_MESSAGE_SIZE, F_DATE -> r.skipLongInteger()+ F_EXPIRY -> r.skipValueLength()+ F_CONTENT_LOCATION -> contentLocation = r.readTextString()+ else -> {+ // Unknown field: we can't know its length; stop parsing gracefully.+ break+ }+ }+ }+ return Notification(contentLocation, transactionId)+ }++ /** Parse a downloaded M-Retrieve.conf into sender + text + media parts. */+ fun parseRetrieved(pdu: ByteArray): Retrieved {+ val r = Reader(pdu)+ var from: String? = null+ var subject: String? = null+ var dateSeconds = System.currentTimeMillis() / 1000L+ // Header loop — stops when we reach Content-Type (immediately followed by the body).+ loop@ while (r.hasRemaining()) {+ val field = r.readByte() and 0xFF+ when (field) {+ F_MESSAGE_TYPE, F_MMS_VERSION, F_MESSAGE_CLASS, F_PRIORITY,+ F_DELIVERY_REPORT, F_READ_REPORT -> r.readByte()+ F_TRANSACTION_ID, F_MESSAGE_ID -> r.readTextString()+ F_SUBJECT -> subject = r.readEncodedString()+ F_FROM -> from = r.readFromAddress()+ F_DATE -> dateSeconds = r.readLongInteger()+ F_MESSAGE_SIZE -> r.skipLongInteger()+ F_EXPIRY -> r.skipValueLength()+ F_CONTENT_LOCATION -> r.readTextString()+ F_CONTENT_TYPE -> { r.readContentType(); break@loop }+ else -> break@loop+ }+ }+ val parts = runCatching { r.readMultipart() }.getOrDefault(emptyList())+ val text = parts.firstOrNull { it.contentType == "text/plain" }?.text+ return Retrieved(from, subject, text, parts, dateSeconds)+ }++ private class Reader(val buf: ByteArray) {+ var pos = 0+ fun hasRemaining() = pos < buf.size+ fun readByte(): Int = buf[pos++].toInt()++ fun readTextString(): String {+ if (pos < buf.size && (buf[pos].toInt() and 0xFF) == 0x7F) pos++ // Quote+ val start = pos+ while (pos < buf.size && buf[pos].toInt() != 0) pos+++ val s = String(buf, start, pos - start, Charsets.UTF_8)+ if (pos < buf.size) pos++ // consume null+ return s+ }++ /** Encoded-string-value: either a plain text-string or Value-length Charset Text-string. */+ fun readEncodedString(): String {+ val first = buf[pos].toInt() and 0xFF+ if (first in 0x20..0x7F || first == 0x7F) return readTextString()+ val len = readValueLength()+ val end = pos + len+ // Optional charset short-integer.+ if (pos < end && (buf[pos].toInt() and 0x80) != 0) pos+++ val s = readTextString()+ pos = end.coerceAtMost(buf.size)+ return s+ }++ /** From-value: Value-length (Address-present-token Encoded-string | Insert-address-token). */+ fun readFromAddress(): String? {+ val len = readValueLength()+ val end = (pos + len).coerceAtMost(buf.size)+ if (pos < end) {+ val token = buf[pos++].toInt() and 0xFF+ if (token == 0x80) { // address-present+ val s = readEncodedString()+ pos = end+ return s.substringBefore("/TYPE=")+ }+ }+ pos = end+ return null+ }++ fun readValueLength(): Int {+ val first = buf[pos++].toInt() and 0xFF+ return if (first < 31) first else readUintvar()+ }++ fun skipValueLength() {+ val len = readValueLength()+ pos = (pos + len).coerceAtMost(buf.size)+ }++ fun readLongInteger(): Long {+ val len = buf[pos++].toInt() and 0xFF+ if (len > 30) return 0 // not a short-length; bail+ var v = 0L+ repeat(len) { v = (v shl 8) or (buf[pos++].toLong() and 0xFF) }+ return v+ }++ fun skipLongInteger() { readLongInteger() }++ fun readUintvar(): Int {+ var result = 0+ while (pos < buf.size) {+ val b = buf[pos++].toInt() and 0xFF+ result = (result shl 7) or (b and 0x7F)+ if (b and 0x80 == 0) break+ }+ return result+ }++ /** Content-Type value: constrained-media (text/short-int) or general-form (length-prefixed). */+ fun readContentType(): String {+ val first = buf[pos].toInt() and 0xFF+ return when {+ first >= 0x80 -> { pos++; wellKnownContentType(first and 0x7F) } // short-integer+ first in 0x20..0x7E -> readTextString() // text media type+ else -> {+ // General form: value-length, then media type (short-int or text), then params.+ val len = readValueLength()+ val end = (pos + len).coerceAtMost(buf.size)+ val ct = if ((buf[pos].toInt() and 0x80) != 0) {+ wellKnownContentType((buf[pos++].toInt() and 0x7F))+ } else {+ readTextString()+ }+ pos = end+ ct+ }+ }+ }++ /** Multipart body: nEntries then each entry = HeadersLen DataLen ContentType *Header Data. */+ fun readMultipart(): List<RetrievedPart> {+ val out = ArrayList<RetrievedPart>()+ if (!hasRemaining()) return out+ val nEntries = readUintvar()+ repeat(nEntries) {+ if (!hasRemaining()) return out+ val headersLen = readUintvar()+ val dataLen = readUintvar()+ val headerEnd = pos + headersLen+ val ct = readContentType()+ // Skip the rest of the part headers (content-location/id/etc.).+ pos = headerEnd.coerceAtMost(buf.size)+ val dataEnd = (pos + dataLen).coerceAtMost(buf.size)+ val data = buf.copyOfRange(pos, dataEnd)+ pos = dataEnd+ val text = if (ct == "text/plain") String(data, Charsets.UTF_8) else null+ out.add(RetrievedPart(ct, data, text))+ }+ return out+ }+ }++ /** A tiny subset of WSP content-type assigned numbers we may encounter. */+ private fun wellKnownContentType(code: Int): String = when (code) {+ 0x03 -> "text/plain"+ 0x1D -> "image/gif"+ 0x1E -> "image/jpeg"+ 0x1F -> "image/tiff"+ 0x20 -> "image/png"+ 0x21 -> "application/vnd.wap.multipart.mixed"+ 0x22 -> "application/vnd.wap.multipart.related"+ else -> "application/octet-stream"+ }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/WhatsAppSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/WhatsAppSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/WhatsAppSyncService.ktindex 3ae0d0d2ac..eb5c10428b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/WhatsAppSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/WhatsAppSyncService.kt@@ -50,6 +50,12 @@ class WhatsAppSyncService : Service() { ensureChannels() startForegroundCompat(buildSyncNotification()) + // Dev-only feature: if ever started in a release build, immediately stand down.+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ shutdown()+ return START_NOT_STICKY+ }+ if (intent?.action == ACTION_STOP) { shutdown() return START_NOT_STICKY@@ -188,6 +194,8 @@ class WhatsAppSyncService : Service() { const val EXTRA_OPEN_WHATSAPP_THREAD = "open_whatsapp_thread" fun start(context: Context) {+ // Dev-only feature: never start the WhatsApp sync service in the release variant.+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return ContextCompat.startForegroundService(context, Intent(context, WhatsAppSyncService::class.java)) }
communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.ktindex a26821b7af..cbf5ac04d8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/AccountsScreen.kt@@ -134,37 +134,39 @@ fun AccountsScreen( ) } - // WhatsApp primary line.- Card(modifier = Modifier.fillMaxWidth()) {- Column(modifier = Modifier.padding(bottom = 8.dp)) {- ListItem(- leadingContent = { IconPerson() },- content = { Text("WhatsApp", fontWeight = FontWeight.SemiBold) },- supportingContent = {- Text(if (waSignedIn) (waNumber ?: "Registered") else "Not registered")- },- )- Column(- modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),- verticalArrangement = Arrangement.spacedBy(8.dp),- ) {- if (waSignedIn) {- OutlinedButton(- onClick = {- scope.launch {- waSession.signOut(context)- AppMessages.show("Signed out of WhatsApp")- }- },- modifier = Modifier.fillMaxWidth(),- ) { Text("Sign out") }- } else {- Button(onClick = onRegisterWhatsApp, modifier = Modifier.fillMaxWidth()) {- Text("Register")+ // WhatsApp primary line (dev-only; hidden in the release variant).+ if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(modifier = Modifier.padding(bottom = 8.dp)) {+ ListItem(+ leadingContent = { IconPerson() },+ content = { Text("WhatsApp", fontWeight = FontWeight.SemiBold) },+ supportingContent = {+ Text(if (waSignedIn) (waNumber ?: "Registered") else "Not registered")+ },+ )+ Column(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (waSignedIn) {+ OutlinedButton(+ onClick = {+ scope.launch {+ waSession.signOut(context)+ AppMessages.show("Signed out of WhatsApp")+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("Sign out") }+ } else {+ Button(onClick = onRegisterWhatsApp, modifier = Modifier.fillMaxWidth()) {+ Text("Register")+ }+ }+ OutlinedButton(onClick = onImportBackup, modifier = Modifier.fillMaxWidth()) {+ Text("Import backup (.crypt15)") }- }- OutlinedButton(onClick = onImportBackup, modifier = Modifier.fillMaxWidth()) {- Text("Import backup (.crypt15)") } } }
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.ktindex f4306daeb2..6c9c7c6635 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt@@ -223,10 +223,13 @@ fun rememberLineChoices(): List<LineChoice> { val gv by session.signedInFlow.collectAsState(initial = false) val waSession = remember { com.vayunmathur.communicate.data.whatsapp.WhatsAppLineSession.get(context) } val wa by waSession.signedInFlow.collectAsState(initial = false)- return remember(gv, wa) {+ // WhatsApp is a dev-only feature (unofficial primary client, ToS/ban risk) — never offer it in+ // the release variant.+ val waEnabled = wa && com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled+ return remember(gv, waEnabled) { SimManager.simLineChoices(context) + (if (gv) listOf(LineChoice.GoogleVoice) else emptyList()) +- (if (wa) listOf(LineChoice.WhatsApp) else emptyList())+ (if (waEnabled) listOf(LineChoice.WhatsApp) else emptyList()) } }
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 f033f4d7ae..97789cbe9d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -32,6 +32,7 @@ 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.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource@@ -62,6 +63,7 @@ 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.MessageStatus import com.vayunmathur.communicate.data.SmsMessage import com.vayunmathur.communicate.data.SmsThread import com.vayunmathur.library.util.AppMessages@@ -76,6 +78,9 @@ fun ConversationScreen( line: CommunicateLine, remoteId: String?, subscriptionId: Int? = null,+ isGroup: Boolean = false,+ participants: List<String> = emptyList(),+ groupTitle: String? = null, onBack: () -> Unit, ) { val context = LocalContext.current@@ -116,6 +121,9 @@ fun ConversationScreen( unreadCount = 0, line = line, remoteId = remoteId,+ isGroup = isGroup,+ participants = participants,+ groupTitle = groupTitle, ) } val title = produceState(initialValue = address.ifBlank { context.getString(R.string.conversation_title) }, address) {@@ -124,6 +132,21 @@ fun ConversationScreen( ?: address.ifBlank { context.getString(R.string.conversation_title) } } }+ // For groups, resolve a "Alice, Bob +N" subtitle from the participant addresses (contact names+ // where available). Cheap: runs once off the main thread.+ val groupSubtitle = produceState<String?>(initialValue = null, isGroup, participants) {+ if (!isGroup || participants.isEmpty()) {+ value = null+ } else {+ value = withContext(Dispatchers.IO) {+ val names = participants.take(3).map { p ->+ CommunicateRepository.findContactName(context, p) ?: p+ }+ val extra = participants.size - names.size+ if (extra > 0) names.joinToString(", ") + " +$extra" else names.joinToString(", ")+ }+ }+ } // Opening a Google Voice thread marks it read server-side via batchupdateattributes. androidx.compose.runtime.LaunchedEffect(remoteId, line) {@@ -165,17 +188,28 @@ fun ConversationScreen( topBar = { TopAppBar( title = {+ val displayTitle = if (isGroup) (groupTitle ?: title.value) else title.value Column { Row(verticalAlignment = Alignment.CenterVertically) { Text(- title.value,+ displayTitle, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.SemiBold, ) LineBadge(line, modifier = Modifier.padding(start = 8.dp)) }- if (address.isNotBlank() && title.value != address) {+ if (isGroup) {+ groupSubtitle.value?.let { subtitle ->+ Text(+ subtitle,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ } else if (address.isNotBlank() && title.value != address) { Text( address, maxLines = 1,@@ -215,10 +249,6 @@ fun ConversationScreen( val text = draft.trim() 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 {@@ -229,6 +259,7 @@ fun ConversationScreen( text, if (fixedLineChoice is LineChoice.Sim) null else remoteId, attachments,+ participants = if (isGroup) participants else emptyList(), ) if (ok) refresh++ else AppMessages.show(context.getString(R.string.gv_send_failed)) }@@ -511,10 +542,21 @@ private fun MessageBubble(message: SmsMessage) { modifier = Modifier.fillMaxWidth(), horizontalAlignment = alignment, ) {- // Group sender name (incoming group messages).- if (!message.outgoing && sd?.senderName != null) {+ // Group sender name (incoming group messages). WhatsApp carries it in serviceData;+ // other lines (SIM/GV groups) resolve it from the per-message sender address.+ val senderLabel = produceState<String?>(initialValue = null, message.id, sd?.senderName, message.senderAddress) {+ value = when {+ message.outgoing -> null+ sd?.senderName != null -> sd.senderName+ message.senderAddress != null -> withContext(Dispatchers.IO) {+ CommunicateRepository.findContactName(context, message.senderAddress) ?: message.senderAddress+ }+ else -> null+ }+ }+ senderLabel.value?.let { label -> Text(- sd.senderName,+ label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(horizontal = 14.dp),@@ -602,12 +644,40 @@ private fun MessageBubble(message: SmsMessage) { ) if (message.outgoing) { Spacer(Modifier.size(4.dp))- Text(- stringResource(R.string.send),- style = MaterialTheme.typography.labelSmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ MessageStatusTicks(message.status)+ }+ }+ }+}++/**+ * Renders WhatsApp-style delivery ticks for an outgoing message:+ * grey ✓ (Sent), grey ✓✓ (Delivered), blue ✓✓ (Read). [MessageStatus.Failed] shows a red "!".+ * [MessageStatus.None] renders nothing (lines without receipts).+ */+@Composable+private fun MessageStatusTicks(status: MessageStatus) {+ when (status) {+ MessageStatus.None -> Unit+ MessageStatus.Failed -> Text(+ "!",+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.error,+ fontWeight = FontWeight.Bold,+ )+ else -> {+ val glyph = if (status == MessageStatus.Sent) "✓" else "✓✓"+ val color = if (status == MessageStatus.Read) {+ // WhatsApp's read-receipt blue (not theme-tinted).+ Color(0xFF34B7F1)+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant }+ Text(+ glyph,+ style = MaterialTheme.typography.labelSmall,+ color = color,+ ) } } }
communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.ktindex c5ece39f9d..7b32aaf943 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape@@ -34,6 +35,8 @@ import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconGroup import com.vayunmathur.library.ui.IconPerson import com.vayunmathur.library.ui.IconSms import com.vayunmathur.library.ui.ListItem@@ -49,13 +52,19 @@ import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.SmsThread import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Checkbox+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.AppMessages import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue+import kotlinx.coroutines.launch import android.content.Context import android.telephony.TelephonyManager import androidx.compose.foundation.layout.heightIn@@ -68,6 +77,7 @@ import kotlinx.coroutines.withContext fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit) { val context = LocalContext.current val lineChoices = rememberLineChoices()+ val scope = rememberCoroutineScope() var showPicker by remember { mutableStateOf(false) } if (showPicker) {@@ -97,6 +107,68 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit ), ) },+ onCreateGroup = { choice, subject, contacts ->+ showPicker = false+ scope.launch {+ when (choice.category) {+ CommunicateLine.WhatsApp -> {+ if (!CommunicateRepository.isWhatsAppConnected()) {+ AppMessages.show("WhatsApp isn't connected — the number may be logged out or banned. Re-register in Accounts.")+ return@launch+ }+ val groupJid = withContext(Dispatchers.IO) {+ CommunicateRepository.createWhatsAppGroup(context, subject, contacts)+ }+ if (groupJid == null) {+ AppMessages.show("Couldn't create the group (server rejected it)")+ } else {+ onOpenThread(+ SmsThread(+ threadId = CommunicateRepository.stableThreadId(groupJid),+ address = groupJid,+ displayName = subject.ifBlank { null },+ snippet = "",+ timestampMillis = System.currentTimeMillis(),+ unreadCount = 0,+ line = CommunicateLine.WhatsApp,+ remoteId = groupJid,+ isGroup = true,+ participants = contacts,+ groupTitle = subject.ifBlank { null },+ ),+ )+ }+ }+ CommunicateLine.Sim -> {+ val sim = choice as? com.vayunmathur.communicate.data.LineChoice.Sim+ val groupThreadId = withContext(Dispatchers.IO) {+ CommunicateRepository.getOrCreateSmsGroupThreadId(context, contacts)+ }+ if (groupThreadId == null) {+ AppMessages.show("Couldn't create the group thread")+ } else {+ onOpenThread(+ SmsThread(+ threadId = groupThreadId,+ address = contacts.joinToString(", "),+ displayName = subject.ifBlank { null },+ snippet = "",+ timestampMillis = System.currentTimeMillis(),+ unreadCount = 0,+ line = CommunicateLine.Sim,+ remoteId = null,+ subscriptionId = sim?.subscriptionId,+ isGroup = true,+ participants = contacts,+ groupTitle = subject.ifBlank { null },+ ),+ )+ }+ }+ else -> AppMessages.show("Groups aren't supported on this line")+ }+ }+ }, ) } @@ -165,7 +237,13 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit @Composable private fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit) { val context = LocalContext.current- val title = thread.displayName ?: thread.address.ifBlank { stringResource(R.string.conversation_title) }+ val title = when {+ thread.isGroup -> thread.groupTitle+ ?: thread.displayName+ ?: groupTitleFromParticipants(thread.participants)+ ?: thread.address.ifBlank { stringResource(R.string.conversation_title) }+ else -> thread.displayName ?: thread.address.ifBlank { stringResource(R.string.conversation_title) }+ } ListItem( content = { Row(verticalAlignment = Alignment.CenterVertically) {@@ -194,7 +272,7 @@ private fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit) { fontWeight = if (thread.unreadCount > 0) FontWeight.SemiBold else FontWeight.Normal, ) },- leadingContent = { ThreadAvatar(title = title) },+ leadingContent = { ThreadAvatar(title = title, isGroup = thread.isGroup) }, trailingContent = { if (thread.unreadCount > 0) UnreadBadge(thread.unreadCount) },@@ -203,8 +281,16 @@ private fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit) { ) } +/** "Alice, Bob +N" from a group's participant addresses; null if there are none. */+private fun groupTitleFromParticipants(participants: List<String>): String? {+ if (participants.isEmpty()) return null+ val shown = participants.take(2)+ val extra = participants.size - shown.size+ return if (extra > 0) shown.joinToString(", ") + " +$extra" else shown.joinToString(", ")+}+ @Composable-private fun ThreadAvatar(title: String) {+private fun ThreadAvatar(title: String, isGroup: Boolean = false) { Box( modifier = Modifier .size(44.dp)@@ -212,11 +298,15 @@ private fun ThreadAvatar(title: String) { .background(MaterialTheme.colorScheme.primaryContainer), contentAlignment = Alignment.Center, ) {- Text(- initialsFor(title),- color = MaterialTheme.colorScheme.onPrimaryContainer,- fontWeight = FontWeight.SemiBold,- )+ if (isGroup) {+ IconGroup(tint = MaterialTheme.colorScheme.onPrimaryContainer)+ } else {+ Text(+ initialsFor(title),+ color = MaterialTheme.colorScheme.onPrimaryContainer,+ fontWeight = FontWeight.SemiBold,+ )+ } } } @@ -237,27 +327,64 @@ private fun UnreadBadge(count: Int) { } /**- * FAB flow when more than one line is available: enter a recipient number and pick which line- * (SIM or Google Voice) to compose from, then open that conversation.+ * FAB flow: pick a line + recipient to start a 1:1 conversation, or flip the "Group" switch to+ * multi-select recipients (chips) + an optional name and create a group (WhatsApp, or SIM MMS). */ @Composable private fun NewMessagePicker( choices: List<com.vayunmathur.communicate.data.LineChoice>, onDismiss: () -> Unit, onCompose: (com.vayunmathur.communicate.data.LineChoice, String) -> Unit,+ onCreateGroup: (com.vayunmathur.communicate.data.LineChoice, String, List<String>) -> Unit, ) { val context = LocalContext.current val region = remember { deviceRegion(context) } var query by remember { mutableStateOf("") }+ var groupMode by remember { mutableStateOf(false) }+ var groupName by remember { mutableStateOf("") }+ // Selected recipients for group mode, keyed by phone number (value = display label).+ val selectedContacts = remember { mutableStateListOf<Pair<String, String>>() }+ // Lines that support group chats: WhatsApp and SIM (MMS). GV is 1:1 only.+ val groupChoices = remember(choices) {+ choices.filter {+ it.category == CommunicateLine.WhatsApp || it.category == CommunicateLine.Sim+ }+ } var selected by remember(choices) { mutableStateOf(choices.firstOrNull()) }+ val activeChoices = if (groupMode) groupChoices else choices++ // Keep the selected line valid when toggling into group mode.+ androidx.compose.runtime.LaunchedEffect(groupMode) {+ if (groupMode && (selected == null || selected !in groupChoices)) {+ selected = groupChoices.firstOrNull()+ }+ }++ fun toggleContact(phone: String, label: String) {+ val idx = selectedContacts.indexOfFirst { it.first == phone }+ if (idx >= 0) selectedContacts.removeAt(idx) else selectedContacts.add(phone to label)+ } AlertDialog( onDismissRequest = onDismiss,- title = { Text(stringResource(R.string.new_message)) },+ title = { Text(if (groupMode) "New group" else stringResource(R.string.new_message)) }, text = { Column {+ if (groupChoices.isNotEmpty()) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp),+ ) {+ Text("Group", style = MaterialTheme.typography.labelLarge)+ Spacer(Modifier.weight(1f))+ com.vayunmathur.library.ui.Switch(+ checked = groupMode,+ onCheckedChange = { groupMode = it },+ )+ }+ } val sel = selected- if (sel != null && choices.size > 1) {+ if (sel != null && activeChoices.size > 1) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(bottom = 8.dp),@@ -267,7 +394,33 @@ private fun NewMessagePicker( style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(end = 8.dp), )- LineSelector(choices = choices, selected = sel, onSelect = { selected = it })+ LineSelector(choices = activeChoices, selected = sel, onSelect = { selected = it })+ }+ }+ if (groupMode) {+ androidx.compose.material3.OutlinedTextField(+ value = groupName,+ onValueChange = { groupName = it },+ modifier = Modifier.fillMaxWidth(),+ placeholder = { Text("Group name (optional)") },+ singleLine = true,+ )+ Spacer(Modifier.size(6.dp))+ if (selectedContacts.isNotEmpty()) {+ LazyRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp),+ ) {+ items(selectedContacts.toList(), key = { it.first }) { (phone, label) ->+ FilterChip(+ selected = true,+ onClick = { toggleContact(phone, label) },+ label = { Text(label, maxLines = 1) },+ trailingIcon = { IconClose(Modifier.size(16.dp)) },+ )+ }+ }+ Spacer(Modifier.size(6.dp)) } } androidx.compose.material3.OutlinedTextField(@@ -297,43 +450,71 @@ private fun NewMessagePicker( } val exactExists = qDigits.isNotEmpty() && contacts.any { it.phoneNumber.filter { c -> c.isDigit() }.endsWith(qDigits) }- LazyColumn(modifier = Modifier.fillMaxWidth().heightIn(max = 340.dp)) {- // Fallback: message a raw number that isn't in contacts (shown formatted).+ LazyColumn(modifier = Modifier.fillMaxWidth().heightIn(max = 300.dp)) {+ // Fallback: a raw number not in contacts (shown formatted). if (qDigits.length >= 4 && !exactExists) { item {- ContactPickRow(title = "Send to ${formatNumber(q, region)}", subtitle = null) {- selected?.let { onCompose(it, q) }+ val label = formatNumber(q, region)+ ContactPickRow(title = "Send to $label", subtitle = null, selected = null) {+ if (groupMode) toggleContact(q, label) else selected?.let { onCompose(it, q) } } } } items(filtered, key = { it.id }) { c ->- ContactPickRow(title = c.name, subtitle = c.phoneNumber) {- selected?.let { onCompose(it, c.phoneNumber) }+ val isSel = if (groupMode) selectedContacts.any { it.first == c.phoneNumber } else null+ ContactPickRow(title = c.name, subtitle = c.phoneNumber, selected = isSel) {+ if (groupMode) toggleContact(c.phoneNumber, c.name) else selected?.let { onCompose(it, c.phoneNumber) } } } } } } },- confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.clear)) } },+ confirmButton = {+ if (groupMode) {+ TextButton(+ onClick = {+ val choice = selected+ if (choice != null && selectedContacts.isNotEmpty()) {+ onCreateGroup(choice, groupName.trim(), selectedContacts.map { it.first })+ }+ },+ enabled = selected != null && selectedContacts.size >= 1,+ ) { Text("Create") }+ } else {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.clear)) }+ }+ },+ dismissButton = if (groupMode) {+ { TextButton(onClick = onDismiss) { Text("Cancel") } }+ } else {+ null+ }, ) } @Composable-private fun ContactPickRow(title: String, subtitle: String?, onClick: () -> Unit) {- Column(+private fun ContactPickRow(title: String, subtitle: String?, selected: Boolean? = null, onClick: () -> Unit) {+ Row( modifier = Modifier .fillMaxWidth() .clickable(onClick = onClick) .padding(vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically, ) {- Text(title, fontWeight = FontWeight.Medium)- if (subtitle != null) {- Text(- subtitle,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ if (selected != null) {+ Checkbox(checked = selected, onCheckedChange = { onClick() })+ Spacer(Modifier.size(8.dp))+ }+ Column(modifier = Modifier.weight(1f)) {+ Text(title, fontWeight = FontWeight.Medium)+ if (subtitle != null) {+ Text(+ subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } } } }
communicate/src/main/res/xml/mms_file_paths.xml
diff --git a/communicate/src/main/res/xml/mms_file_paths.xml b/communicate/src/main/res/xml/mms_file_paths.xmlnew file mode 100644index 0000000000..8001ddecbf--- /dev/null+++ b/communicate/src/main/res/xml/mms_file_paths.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<paths xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- Temporary outgoing MMS PDU files handed to the system MMS service. -->+ <cache-path name="mms_out" path="mms/" />+</paths>