communicate: detekt clean (1390 tests)
- Commit
6ce51753d7e6985d94d8ea004d4ebb7cd3c1740b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 23:38 UTC (21 days ago)
- Parents
a1157be
Fix all 307 detekt findings (93 files): real KDoc for 264 undocumented public classes across Room entities/DAOs, Signal/WhatsApp event types, protocol models, registration result types and service companions; MagicNumber constants ERROR_BODY_MAX_CHARS/LOG_BODY_MAX_CHARS and HEX_PAIR/HEX_RADIX reuse; complexity refactors extracting buildRegistrationBody/persistRegisteredAuth, a Cursor.toVoicemailEntry mapper, RcsE2E SIP-transport helpers to RcsE2ETransport, and WhatsAppMexOps pure build*Variables builders to new WhatsAppMexVariables (two test files updated to the new qualifier); ThrowsCount fixed by building one failure exception in requestVerificationCode; MaxLineLength wrapped. Two UnusedParameter findings were real bugs, fixed by wiring: Google Voice voicemail audioHeaders now reach VoicemailPlayer via DefaultHttpDataSource default request properties and the row onPlayed (mark-read) callback is forwarded instead of an empty lambda; a genuinely dead context parameter was removed from GvVoicemail.toVoicemailEntry. Three narrow @Suppress with comments: RegistrationHttpClient.checkExists UnusedParameter (no Signal existence endpoint exists; CDSIv2 is the authority and post-auth whoami identifies by credentials, so the number documents caller intent only), and framework-signature-mirroring Robolectric fake/shadow parameters in HiddenApiRcsPass3Test and RcsSlice3Pass2ProvisioningShadow. Verified: ./gradlew :communicate:detekt :communicate:testDevUnitTest :communicate:lint --max-workers=32 — detekt 0 findings, lint passes; 1390 unit tests with exactly the 11 pre-existing failures from /tmp/inventory.json (MlsLifecycleRcsPass3Test 4, RustSignalCryptoSignalPass3Test 4, WelcomeJoinRcsPass3Test 3, native-lib/host related), nothing new or worsened.
Diff
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 8f2e63747f..362a6b03ac 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -64,22 +64,33 @@ import com.vayunmathur.communicate.ui.signal.SignalRegistrationScreen import androidx.compose.ui.platform.LocalContext import kotlinx.serialization.Serializable +/** Navigation routes for the communicate app (type-safe back stack keys). */ sealed interface Route : NavKey {+ /** The conversation list (home) route. */ @Serializable data object Main : Route+ /** The accounts / line management route. */ @Serializable data object Accounts : Route+ /** The Google Voice sign-in route. */ @Serializable data object GoogleVoiceSignIn : Route+ /** The WhatsApp phone-number registration route. */ @Serializable data object WhatsAppRegistration : Route+ /** The WhatsApp backup import route. */ @Serializable data object WhatsAppBackupImport : Route+ /** The Signal phone-number registration route. */ @Serializable data object SignalRegistration : Route + /** The RCS status / provisioning route. */ @Serializable data object RcsStatus : Route + /** The RCS safety-number verification route for one peer. */ @Serializable data class RcsVerify(val peerE164: String) : Route + /** The RCS group member list route. */ @Serializable data class RcsGroupMembers(val conversationId: String) : Route + /** One open conversation: its thread, peer address and line. */ @Serializable data class Conversation( val threadId: Long,@@ -94,6 +105,7 @@ sealed interface Route : NavKey { ) : Route } +/** The single activity hosting the communicate UI: navigation, deep links and line setup. */ class MainActivity : MaActivity() { /** The deep link the app was opened with, or the most recent one delivered to a running instance. */ private var pendingDeepLink by mutableStateOf<DeepLink?>(null)@@ -142,6 +154,7 @@ class MainActivity : MaActivity() { } } + /** Notification-permission request code and splash aspect-ratio constants. */ companion object { private const val REQUEST_POST_NOTIFICATIONS = 1001 private const val PORTRAIT_WIDTH = 9
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 4dc6c1b032..c1dd9d6514 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -21,31 +21,37 @@ sealed interface LineChoice { val label: String val category: CommunicateLine + /** The physical SIM line identified by subscription id. */ data class Sim(val subscriptionId: Int, override val label: String) : LineChoice { override val category get() = CommunicateLine.Sim } + /** The Google Voice line. */ data object GoogleVoice : LineChoice { override val label = "Google Voice" override val category get() = CommunicateLine.GoogleVoice } + /** The WhatsApp line. */ data object WhatsApp : LineChoice { override val label = "WhatsApp" override val category get() = CommunicateLine.WhatsApp } + /** The Signal line. */ data object Signal : LineChoice { override val label = "Signal" override val category get() = CommunicateLine.Signal } + /** The carrier RCS line. */ data object Rcs : LineChoice { override val label = "RCS" override val category get() = CommunicateLine.Rcs } } +/** A contact as shown across lines: name, number and photo. */ data class CommunicateContact( val id: Long, val name: String,@@ -53,6 +59,7 @@ data class CommunicateContact( val label: String, ) +/** The direction/outcome kind of a call-log entry. */ enum class CommunicateCallType { Incoming, Outgoing,@@ -63,6 +70,7 @@ enum class CommunicateCallType { Unknown, } +/** One unified call-log entry across SIM, Google Voice, WhatsApp, Signal and RCS lines. */ data class CommunicateCallLogEntry( val id: Long, val displayName: String?,@@ -118,6 +126,7 @@ data class CommunicateAttachment( val fileName: String? = null, ) +/** One SMS/MMS thread in the system telephony provider. */ data class SmsThread( val threadId: Long, val address: String,@@ -158,6 +167,7 @@ enum class MessageStatus { Failed, } +/** One SMS/MMS message in the system telephony provider. */ data class SmsMessage( val id: Long, val threadId: Long,
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 39e9100155..a044475433 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -5,6 +5,7 @@ import android.content.pm.PackageManager import android.provider.CallLog import androidx.core.content.ContextCompat +/** The unified repository facade: routes SMS/MMS, Google Voice, WhatsApp, Signal and RCS traffic per line. */ object CommunicateRepository { // SIM/SMS+MMS, send dispatch, Google Voice, WhatsApp, Signal, delete routing, // polls and shared-contact dispatch live in the CommunicateRepository*.kt
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.ktindex c9dd374558..7e853f95ca 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt@@ -64,7 +64,7 @@ internal suspend fun CommunicateRepository.loadGoogleVoiceVoicemails(context: Co return runCatching { val cookie = session.cookieHeader().orEmpty() val headers = if (cookie.isNotBlank()) mapOf("Cookie" to cookie) else emptyMap()- GoogleVoiceClient.get(context).listVoicemails().map { it.toVoicemailEntry(context, headers) }+ GoogleVoiceClient.get(context).listVoicemails().map { it.toVoicemailEntry(headers) } }.getOrDefault(emptyList()) } @@ -330,7 +330,7 @@ internal fun GvCall.toCallLogEntry(context: Context): CommunicateCallLogEntry = line = CommunicateLine.GoogleVoice, ) -internal fun GvVoicemail.toVoicemailEntry(context: Context, audioHeaders: Map<String, String>): VoicemailEntry =+internal fun GvVoicemail.toVoicemailEntry(audioHeaders: Map<String, String>): VoicemailEntry = VoicemailEntry( id = CommunicateRepository.stableThreadId(id), phoneNumber = phoneNumber,
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.ktindex b90b10a318..e3e0d17b0f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt@@ -502,38 +502,58 @@ fun CommunicateRepository.loadCarrierVoicemails(context: Context): List<Voicemai val activeSubs = SimManager.activeSims(context).map { it.subscriptionId }.toSet() while (cursor.moveToNext()) {- val rowId = cursor.getLong(id)- // PHONE_ACCOUNT_ID tagging mirrors the call log: keep it only when it- // maps to an active SIM so the row can be labeled by SIM.- val subId = account.takeIf { it >= 0 }- ?.let { cursor.getString(it) }- ?.toIntOrNull()- ?.takeIf { it in activeSubs }- add(- VoicemailEntry(- id = rowId,- phoneNumber = cursor.getString(number).orEmpty().ifBlank { "Unknown" },- timestampMillis = cursor.getLong(date),- durationSeconds = cursor.getLong(duration),- contentUri = Uri.withAppendedPath(- VoicemailContract.Voicemails.CONTENT_URI,- rowId.toString(),- ).toString(),- mimeType = mimeType.takeIf { it >= 0 }?.let { cursor.getString(it) },- hasAudio = hasContent.takeIf { it >= 0 }- ?.let { cursor.getInt(it) != 0 } ?: false,- transcript = transcription.takeIf { it >= 0 }- ?.let { cursor.getString(it)?.takeIf { it.isNotBlank() } },- isRead = cursor.getInt(isRead) != 0,- subscriptionId = subId,- )- )+ val columns = VoicemailColumns(+ id, number, date, duration, hasContent, mimeType, transcription, isRead, account)+ add(cursor.toVoicemailEntry(columns, activeSubs)) } } }.orEmpty() }.getOrDefault(emptyList()) } +/** Column indices into a VoicemailContract cursor row. */+private data class VoicemailColumns(+ val id: Int,+ val number: Int,+ val date: Int,+ val duration: Int,+ val hasContent: Int,+ val mimeType: Int,+ val transcription: Int,+ val isRead: Int,+ val account: Int,+)++/** Map the current cursor row to a [VoicemailEntry]; the SIM tag is kept only for active SIMs. */+private fun android.database.Cursor.toVoicemailEntry(+ cols: VoicemailColumns,+ activeSubs: Set<Int>,+): VoicemailEntry {+ val rowId = getLong(cols.id)+ // PHONE_ACCOUNT_ID tagging mirrors the call log: keep it only when it+ // maps to an active SIM so the row can be labeled by SIM.+ val subId = cols.account.takeIf { it >= 0 }+ ?.let { getString(it) }+ ?.toIntOrNull()+ ?.takeIf { it in activeSubs }+ return VoicemailEntry(+ id = rowId,+ phoneNumber = getString(cols.number).orEmpty().ifBlank { "Unknown" },+ timestampMillis = getLong(cols.date),+ durationSeconds = getLong(cols.duration),+ contentUri = Uri.withAppendedPath(+ VoicemailContract.Voicemails.CONTENT_URI,+ rowId.toString(),+ ).toString(),+ mimeType = cols.mimeType.takeIf { it >= 0 }?.let { getString(it) },+ hasAudio = cols.hasContent.takeIf { it >= 0 }?.let { getInt(it) != 0 } ?: false,+ transcript = cols.transcription.takeIf { it >= 0 }+ ?.let { getString(it)?.takeIf { text -> text.isNotBlank() } },+ isRead = getInt(cols.isRead) != 0,+ subscriptionId = subId,+ )+}+ /** Mark a carrier voicemail read/unread. Needs WRITE_CALL_LOG. */ fun CommunicateRepository.markVoicemailRead( context: Context,
communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.ktindex 33378a2e0d..997967cb19 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt@@ -21,6 +21,7 @@ data class CallCapabilities( val screenShare: Boolean = false, val hold: Boolean = false, ) {+ /** Prebuilt capability sets for audio-only and audio+video calls. */ companion object { val AudioOnly = CallCapabilities() val AudioAndVideo = CallCapabilities(video = true, screenShare = true)
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.ktindex 43faf5205b..f151d89910 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt@@ -132,6 +132,7 @@ class GoogleVoiceClient(private val session: GoogleVoiceSession) { } } + /** HTTP constants and logging tag for the Google Voice client. */ companion object { private const val TAG = "GoogleVoiceRaw" private const val HTTP_UNAUTHORIZED = 401
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 1f57aeb2af..3078b20298 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@@ -19,6 +19,7 @@ private const val FOLDER_CALLS = 3 private const val FOLDER_VOICEMAIL = 4 private const val FOLDER_SPAM = 5 +/** A Google Voice mailbox folder (All, Inbox, Spam, Trash, …) by its api2thread folder id. */ enum class GvFolder(val id: Int) { All(FOLDER_ALL), Inbox(FOLDER_INBOX),@@ -29,6 +30,7 @@ enum class GvFolder(val id: Int) { Spam(FOLDER_SPAM), } +/** One Google Voice message in a thread. */ data class GvMessage( val id: String, val threadId: String,@@ -41,6 +43,7 @@ data class GvMessage( val hasMedia: Boolean = mediaUrls.isNotEmpty(), ) +/** One Google Voice conversation thread. */ data class GvThread( val id: String, val phoneNumber: String,@@ -51,8 +54,10 @@ data class GvThread( val messages: List<GvMessage> = emptyList(), ) +/** The direction/kind of a Google Voice call-log entry. */ enum class GvCallType { Incoming, Outgoing, Missed, Voicemail, Unknown } +/** One Google Voice call-log entry. */ data class GvCall( val id: String, val phoneNumber: String,
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.ktindex d289212b6f..0f5810392a 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@@ -31,9 +31,13 @@ object GoogleVoiceParser { /** Thread attribute mutations for `thread/batchupdateattributes`. */ sealed interface ThreadAction {+ /** Mark the thread read. */ data object MarkRead : ThreadAction+ /** Mark the thread unread. */ data object MarkUnread : ThreadAction+ /** Archive the thread. */ data object Archive : ThreadAction+ /** Unarchive the thread. */ data object Unarchive : ThreadAction }
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 ba070e3773..7748c98a36 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@@ -86,6 +86,7 @@ class GoogleVoiceSession private constructor(private val store: DataStoreUtils) val phoneNumberFlow: Flow<String?> get() = store.stringFlow(KEY_PHONE_NUMBER).map { it } + /** Preference keys for the Google Voice session (cookie, SAPISID, phone number). */ companion object { private const val KEY_COOKIE = "gv_cookie" private const val KEY_SAPISID = "gv_sapisid"
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 600c88ea09..4b0ee49c9a 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@@ -17,6 +17,7 @@ import kotlinx.coroutines.launch /** Coarse call lifecycle exposed to the UI + Telecom bridge. */ enum class CallPhase { Idle, Dialing, Ringing, Active, Incoming, Ended } +/** An immutable snapshot of the current Google Voice call for the UI. */ data class CallState( val phase: CallPhase = CallPhase.Idle, val remoteNumber: String = "",
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 730ef29096..b8ddc16776 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@@ -35,6 +35,7 @@ class SipClient( private val scope: CoroutineScope, private val listener: Listener, ) {+ /** Callbacks for SIP registration, provisional responses and remote SDP on the Google Voice call leg. */ interface Listener { fun onRegistered() fun onProvisional(code: Int)@@ -348,6 +349,7 @@ class SipClient( + /** Registrar endpoint and logging constants for [SipClient]. */ companion object { private const val TAG = "SipClient" private const val WS_URL = "wss://web.voice.telephony.goog/websocket"
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktindex 847eead5d1..155deb19a6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -41,6 +41,7 @@ abstract class RcsDatabase : RoomDatabase() { abstract fun mlsGroupDao(): RcsMlsGroupDao abstract fun outboxDao(): RcsOutboxDao + /** Schema migrations and the singleton accessor for [RcsDatabase]. */ companion object : DatabaseMigrations { /** * v1 → v2: MLS E2EE tables (identity + group state). New tables only,@@ -118,6 +119,7 @@ class RcsRepository private constructor(context: Context) : /** Direct database access; prefer suspend wrappers for new code. */ fun database(): RcsDatabase = db + /** The singleton [RcsRepository] instance holder. */ companion object { @Volatile private var instance: RcsRepository? = null@@ -129,6 +131,7 @@ class RcsRepository private constructor(context: Context) : } } +/** Room column converters for RCS entities; string lists are stored as CSV. */ class RcsTypeConverters { @ColumnTypeConverter fun fromStringList(value: List<String>): String = value.joinToString(",")@@ -140,6 +143,7 @@ class RcsTypeConverters { // -- Conversation -- +/** An RCS conversation row: a 1:1 peer (E.164) or a group conference URI. */ @Entity(tableName = "rcs_conversation") data class RcsConversation( /** E.164 for 1:1, conference URI for groups. */@@ -153,6 +157,7 @@ data class RcsConversation( val lastMessageTimestamp: Long = 0L, ) +/** Queries for RCS conversations. */ @Dao interface RcsConversationDao { @Query("SELECT * FROM rcs_conversation WHERE remoteId = :remoteId")@@ -172,6 +177,7 @@ interface RcsConversationDao { } // -- Cached messages --+/** A cached RCS message row, including file-transfer and delivery state. */ @Entity(tableName = "rcs_cached_message") data class RcsCachedMessage( @PrimaryKey val messageId: String,@@ -194,6 +200,7 @@ data class RcsCachedMessage( val imdnId: String = "", ) +/** Queries for cached RCS messages. */ @Dao interface RcsCachedMessageDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -262,6 +269,7 @@ data class RcsMlsGroup( val members: String = "", ) +/** Queries for our RCS MLS identity (credential and key package state). */ @Dao interface RcsMlsIdentityDao { @Query("SELECT * FROM rcs_mls_identity WHERE e164 = :e164 LIMIT 1")@@ -274,6 +282,7 @@ interface RcsMlsIdentityDao { suspend fun delete(e164: String) } +/** Queries for RCS MLS group state. */ @Dao interface RcsMlsGroupDao { @Query("SELECT * FROM rcs_mls_group WHERE groupIdHex = :groupIdHex LIMIT 1")@@ -313,6 +322,7 @@ data class RcsOutboxMessage( val createdAt: Long = 0L, ) +/** Queries for the RCS outbox (messages queued while offline/unregistered). */ @Dao interface RcsOutboxDao { @Insert(onConflict = OnConflictStrategy.REPLACE)
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.ktindex f29f94bb26..a666028bcd 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt@@ -39,10 +39,15 @@ enum class RcsUnavailableReason { * this doubles as the line session: `Available` means signed-in. */ sealed interface RcsRegistrationState {+ /** Registration state not yet determined. */ data object Unknown : RcsRegistrationState+ /** Carrier RCS provisioning is in progress. */ data object Provisioning : RcsRegistrationState+ /** RCS is provisioned and available. */ data object Available : RcsRegistrationState+ /** RCS is unavailable, with the reason. */ data class Unavailable(val reason: RcsUnavailableReason) : RcsRegistrationState+ /** RCS is disabled (release builds / gate off). */ data object Disabled : RcsRegistrationState }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktindex 87adac91ca..4da0facf36 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -260,7 +260,7 @@ object RcsE2E { members = pruneMembers(group.members, droppedIdx), ), )- sendMlsEnvelope(conversationId, commit, CT_COMMIT)+ RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT) } } @@ -443,21 +443,9 @@ object RcsE2E { identityFor(context, localE164) ?: return false // Publish ours alongside the request so one round trip suffices. RcsKeyDirectory.publishTo(context, localE164, peerE164)- return sendKeyRequest(peerE164)+ return RcsE2ETransport.sendKeyRequest(peerE164) } - private suspend fun sendKeyRequest(peerE164: String): Boolean {- if (!RcsSipTransport.canSend()) return false- val body = "Content-Type: $CT_KEY_REQUEST\r\n\r\nrequest"- val (startLine, headers, content) = RcsSipTransport.buildChatMessage(- fromUri = "sip:me@rcs",- toUri = "sip:$peerE164@rcs",- callId = "${UUID.randomUUID()}@rcs-kreq",- body = body,- )- return runCatching { RcsSipTransport.sendSipMessage(startLine, headers, content) }- .getOrDefault(false)- } /** * Request one peer's key package (public; the peer auto-publishes).@@ -465,7 +453,7 @@ object RcsE2E { */ suspend fun requestKeyPackage(peerE164: String): Boolean { if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false- return sendKeyRequest(peerE164)+ return RcsE2ETransport.sendKeyRequest(peerE164) } /**@@ -485,15 +473,15 @@ object RcsE2E { context, localE164, conversationId, peerPackages.values.toList(), ) ?: return false // Track leaf indices for later removal (§5.2).- trackGroupMembers(context, conversationId, peerPackages.keys.toList())- var ok = sendMlsEnvelope(conversationId, commit, CT_COMMIT)+ RcsE2ETransport.trackGroupMembers(context, conversationId, peerPackages.keys.toList())+ var ok = RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT) for ((peer, _) in peerPackages) {- ok = sendMlsEnvelope(peer, welcome, CT_WELCOME) && ok+ ok = RcsE2ETransport.sendMlsEnvelope(peer, welcome, CT_WELCOME) && ok } // Rotate our key package now that the previous one may be consumed. freshKeyPackage(context, localE164) // Replenish the published pool (§5.1).- replenishKeyPackages(context, peerPackages.keys.toList(), localE164)+ RcsE2ETransport.replenishKeyPackages(context, peerPackages.keys.toList(), localE164) return ok } @@ -513,65 +501,16 @@ object RcsE2E { if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false val (commit, welcome) = createEncryptedGroup(context, localE164, conversationId, listOf(peerKeyPackage)) ?: return false- trackGroupMembers(context, conversationId, listOf(peerE164))+ RcsE2ETransport.trackGroupMembers(context, conversationId, listOf(peerE164)) // Commit → the (new) group thread; Welcome → the peer 1:1.- val commitOk = sendMlsEnvelope(conversationId, commit, CT_COMMIT)- val welcomeOk = sendMlsEnvelope(peerE164, welcome, CT_WELCOME)+ val commitOk = RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT)+ val welcomeOk = RcsE2ETransport.sendMlsEnvelope(peerE164, welcome, CT_WELCOME) // Rotate our key package now that the previous one may be consumed. freshKeyPackage(context, localE164)- replenishKeyPackages(context, listOf(peerE164), localE164)+ RcsE2ETransport.replenishKeyPackages(context, listOf(peerE164), localE164) return commitOk && welcomeOk } - /**- * Merge [peers] into the tracked member map for [conversationId]'s group- * (§5.2). Best-effort; never throws.- */- private suspend fun trackGroupMembers(context: Context, conversationId: String, peers: List<String>) {- if (!RcsFeature.enabled || peers.isEmpty()) return- runCatching {- val db = RcsDatabase.getDatabase(context)- val group = db.mlsGroupDao().getByConversation(conversationId) ?: return- db.mlsGroupDao().upsert(- group.copy(- members = trackAddedMembers(group.members, peers),- updatedAt = System.currentTimeMillis(),- ),- )- }- }-- /**- * Key-package replenishment (§5.1): after consuming our published package- * in a setup, immediately publish a fresh one to the same peers so their- * cached pool stays warm and the next add doesn't stall on a round trip.- */- private suspend fun replenishKeyPackages(context: Context, peers: List<String>, localE164: String) {- if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peers.isEmpty()) return- for (peer in peers) {- runCatching { RcsKeyDirectory.publishTo(context, localE164, peer) }- }- }-- private suspend fun sendMlsEnvelope(- recipient: String,- framed: ByteArray,- contentType: String,- ): Boolean {- if (!RcsSipTransport.canSend()) return false- val b64 = android.util.Base64.encodeToString(framed, android.util.Base64.NO_WRAP)- val body = "Content-Type: $contentType\r\n\r\n$b64"- val (startLine, headers, content) = RcsSipTransport.buildChatMessage(- fromUri = "sip:me@rcs",- toUri = "sip:$recipient@rcs",- callId = "${UUID.randomUUID()}@rcs-env",- body = body,- )- val typedHeaders = headers.replace("Content-Type: message/cpim", "Content-Type: $contentType")- return runCatching { RcsSipTransport.sendSipMessage(startLine, typedHeaders, content) }- .getOrDefault(false)- }- /** Group id for [conversationId], or null when no E2EE group exists. */ suspend fun groupIdFor(context: Context, conversationId: String): ByteArray? = withContext(Dispatchers.IO) {@@ -579,7 +518,7 @@ object RcsE2E { val group = RcsDatabase.getDatabase(context).mlsGroupDao().getByConversation(conversationId) ?: return@withContext null if (group.groupIdHex.startsWith("pending:")) return@withContext null- group.groupIdHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+ group.groupIdHex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray() } /**@@ -620,3 +559,70 @@ object RcsE2E { }++/**+ * SIP transport legs for [RcsE2E]: key-package requests, MLS envelope fan-out,+ * member tracking and key-package replenishment.+ */+internal object RcsE2ETransport {+ suspend fun sendKeyRequest(peerE164: String): Boolean {+ if (!RcsSipTransport.canSend()) return false+ val body = "Content-Type: ${RcsE2E.CT_KEY_REQUEST}\r\n\r\nrequest"+ val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$peerE164@rcs",+ callId = "${UUID.randomUUID()}@rcs-kreq",+ body = body,+ )+ return runCatching { RcsSipTransport.sendSipMessage(startLine, headers, content) }+ .getOrDefault(false)+ }+ /**+ * Merge [peers] into the tracked member map for [conversationId]'s group+ * (§5.2). Best-effort; never throws.+ */+ suspend fun trackGroupMembers(context: Context, conversationId: String, peers: List<String>) {+ if (!RcsFeature.enabled || peers.isEmpty()) return+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ val group = db.mlsGroupDao().getByConversation(conversationId) ?: return+ db.mlsGroupDao().upsert(+ group.copy(+ members = RcsE2E.trackAddedMembers(group.members, peers),+ updatedAt = System.currentTimeMillis(),+ ),+ )+ }+ }++ /**+ * Key-package replenishment (§5.1): after consuming our published package+ * in a setup, immediately publish a fresh one to the same peers so their+ * cached pool stays warm and the next add doesn't stall on a round trip.+ */+ suspend fun replenishKeyPackages(context: Context, peers: List<String>, localE164: String) {+ if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peers.isEmpty()) return+ for (peer in peers) {+ runCatching { RcsKeyDirectory.publishTo(context, localE164, peer) }+ }+ }++ suspend fun sendMlsEnvelope(+ recipient: String,+ framed: ByteArray,+ contentType: String,+ ): Boolean {+ if (!RcsSipTransport.canSend()) return false+ val b64 = android.util.Base64.encodeToString(framed, android.util.Base64.NO_WRAP)+ val body = "Content-Type: $contentType\r\n\r\n$b64"+ val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$recipient@rcs",+ callId = "${UUID.randomUUID()}@rcs-env",+ body = body,+ )+ val typedHeaders = headers.replace("Content-Type: message/cpim", "Content-Type: $contentType")+ return runCatching { RcsSipTransport.sendSipMessage(startLine, typedHeaders, content) }+ .getOrDefault(false)+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAttachmentCipher.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAttachmentCipher.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAttachmentCipher.ktindex c24f2c7dc0..5a2e7ef7e7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAttachmentCipher.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAttachmentCipher.kt@@ -21,9 +21,12 @@ object SignalAttachmentCipher { private const val IV_SIZE = 16 private const val MAC_SIZE = 32 + /** Thrown when an attachment blob MAC does not verify (tampered or wrong key). */ class MacMismatchException : Exception("attachment MAC did not verify")+ /** Thrown when an attachment blob digest does not match its pointer. */ class DigestMismatchException : Exception("attachment digest did not verify") + /** An encrypted attachment blob plus the key and digest for its AttachmentPointer. */ data class Encrypted( /** The 64-byte combined key for `AttachmentPointer.key`. */ val key: ByteArray,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.ktindex 69911cf2d0..a09846c59e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalAuthData.kt@@ -81,6 +81,7 @@ data class SignalAuthData( fun effectiveAciPqSec(): String = aciPqLastResortSecret.ifEmpty { pqLastResortSecret } fun effectiveAciPqSig(): String = aciPqLastResortSignature.ifEmpty { pqLastResortSignature } + /** Preference keys and factories for [SignalAuthData]. */ companion object { private const val PREFS_NAME = "communicate_signal_auth" private const val KEY_AUTH_DATA = "auth_data"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex 5ef21dd1e5..9f67ff3158 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -99,11 +99,17 @@ object SignalClient { /** Wire prefix distinguishing a phone-number identity from an ACI, which is a bare UUID. */ internal const val PNI_PREFIX = "PNI:" + /** Lifecycle state of the Signal line. */ sealed interface State {+ /** Not yet connected. */ data object Idle : State+ /** The line has no registered account yet. */ data object NeedsSetup : State+ /** The socket is connecting / logging in. */ data object Connecting : State+ /** Connected and logged in. */ data object Connected : State+ /** Disconnected, with the reason. */ data class Disconnected(val reason: String) : State }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.ktindex 5e4f1fe29d..497b2972d4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalContactSync.kt@@ -29,6 +29,7 @@ object SignalContactSync { private const val TAG = "SignalContactSync" private const val LONG_BYTES = 8 + /** The outcome of a Signal contact sync: how many numbers were checked and discovered. */ data class SyncResult( val deviceCount: Int, val e164Count: Int,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.ktindex fe916b64a7..d5a95b99b1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDatabase.kt@@ -64,6 +64,7 @@ abstract class SignalDatabase : RoomDatabase() { abstract fun profileKeyDao(): SignalProfileKeyDao abstract fun callLogDao(): SignalCallLogDao + /** Schema migrations and the singleton accessor for [SignalDatabase]. */ companion object : DatabaseMigrations { /** * v1 → v2: Kyber pre-key storage. The protocol store needs somewhere to keep our own Kyber@@ -148,6 +149,7 @@ abstract class SignalDatabase : RoomDatabase() { } } +/** Room column converters for Signal entities; string lists are stored as CSV. */ class SignalTypeConverters { @ColumnTypeConverter fun fromStringList(value: List<String>): String = value.joinToString(",")@@ -159,6 +161,7 @@ class SignalTypeConverters { // -- Device / session (transport) -- +/** A linked Signal device: its device id, phone number, platform and last-seen time. */ @Entity(tableName = "signal_devices") data class SignalDevice( @PrimaryKey val deviceId: String,@@ -171,6 +174,7 @@ data class SignalDevice( val loggedInAt: Long = 0L, ) +/** A stored Signal protocol session record for one peer address (legacy transport table). */ @Entity(tableName = "signal_sessions") data class SignalSession( @PrimaryKey val jid: String,@@ -192,6 +196,7 @@ data class SignalSession( } } +/** Queries for linked Signal devices. */ @Dao interface SignalDeviceDao { @Query("SELECT * FROM signal_devices WHERE deviceId = :deviceId")@@ -204,6 +209,7 @@ interface SignalDeviceDao { suspend fun deleteDevice(deviceId: String) } +/** Queries for stored Signal protocol sessions. */ @Dao interface SignalSessionDao { @Query("SELECT * FROM signal_sessions WHERE jid = :jid")@@ -227,6 +233,7 @@ interface SignalSessionDao { // -- Conversation -- +/** A Signal conversation row: a 1:1 chat keyed by address or a group keyed by its derived group id. */ @Entity(tableName = "signal_conversation") data class SignalConversation( @PrimaryKey val chatId: String,@@ -249,6 +256,7 @@ data class SignalConversation( @ColumnInfo(defaultValue = "0") val groupRevision: Int = 0, ) +/** Queries for Signal conversations. */ @Dao interface SignalConversationDao { @Query("SELECT * FROM signal_conversation WHERE chatId = :chatId")@@ -275,6 +283,7 @@ interface SignalConversationDao { // -- Cached messages -- +/** A cached Signal message row, including edit/revoke state, media pointer and delivery status. */ @Entity(tableName = "signal_cached_message") data class SignalCachedMessage( @PrimaryKey val messageId: String,@@ -292,6 +301,7 @@ data class SignalCachedMessage( val status: Int = 0, ) +/** Queries for cached Signal messages. */ @Dao interface SignalCachedMessageDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -352,6 +362,7 @@ interface SignalCachedMessageDao { // -- Reactions -- +/** One emoji reaction on a cached Signal message, keyed by message and sender. */ @Entity(tableName = "signal_cached_reaction", primaryKeys = ["messageId", "senderId"]) data class SignalCachedReaction( val messageId: String,@@ -360,6 +371,7 @@ data class SignalCachedReaction( val timestamp: Long, ) +/** Queries for cached Signal message reactions. */ @Dao interface SignalCachedReactionDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -377,6 +389,7 @@ interface SignalCachedReactionDao { // -- Contacts -- +/** A Signal contact discovered via CDSi, keyed by ACI with its phone number and PNI. */ @Entity(tableName = "signal_contact") data class SignalContact( @PrimaryKey val aci: String,@@ -392,6 +405,7 @@ data class SignalContact( @ColumnInfo(defaultValue = "''") val pni: String = "", ) +/** Queries for Signal contacts. */ @Dao interface SignalContactDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -424,6 +438,7 @@ interface SignalContactDao { // -- E2E stores -- +/** A Signal protocol (double-ratchet) session record for one peer device. */ @Entity(tableName = "signal_e2e_sessions", primaryKeys = ["address", "deviceId"]) data class SignalE2ESession( val address: String,@@ -431,12 +446,14 @@ data class SignalE2ESession( val record: ByteArray, ) +/** A peer identity key for one Signal address, used for trust-on-first-use checks. */ @Entity(tableName = "signal_e2e_identities") data class SignalE2EIdentity( @PrimaryKey val address: String, val identityKey: ByteArray, ) +/** One of our one-time EC pre-keys, with whether it has been uploaded to the service. */ @Entity(tableName = "signal_e2e_pre_keys") data class SignalE2EPreKey( @PrimaryKey val id: Int,@@ -444,12 +461,14 @@ data class SignalE2EPreKey( val uploaded: Boolean = false, ) +/** One of our signed EC pre-keys (the serialized protocol record). */ @Entity(tableName = "signal_e2e_signed_pre_keys") data class SignalE2ESignedPreKey( @PrimaryKey val id: Int, val record: ByteArray, ) +/** One of our Kyber (post-quantum) pre-keys; the last-resort key is the reusable fallback. */ @Entity(tableName = "signal_e2e_kyber_pre_keys") data class SignalE2EKyberPreKey( @PrimaryKey val id: Int,@@ -472,6 +491,7 @@ data class SignalE2EKyberUsedBaseKey( val baseKeyB64: String, ) +/** A group sender-key record for one (address, device, distribution) triple. */ @Entity(tableName = "signal_e2e_sender_keys", primaryKeys = ["address", "deviceId", "distributionId"]) data class SignalE2ESenderKey( val address: String,@@ -480,6 +500,7 @@ data class SignalE2ESenderKey( val record: ByteArray, ) +/** Queries for Signal protocol session records. */ @Dao interface SignalE2ESessionDao { @Query("SELECT * FROM signal_e2e_sessions WHERE address = :address AND deviceId = :deviceId LIMIT 1")@@ -501,6 +522,7 @@ interface SignalE2ESessionDao { suspend fun deleteAll(address: String) } +/** Queries for peer identity keys. */ @Dao interface SignalE2EIdentityDao { @Query("SELECT * FROM signal_e2e_identities WHERE address = :address LIMIT 1")@@ -513,6 +535,7 @@ interface SignalE2EIdentityDao { suspend fun delete(address: String) } +/** Queries for our one-time EC pre-keys. */ @Dao interface SignalE2EPreKeyDao { @Query("SELECT * FROM signal_e2e_pre_keys WHERE id = :id LIMIT 1")@@ -546,6 +569,7 @@ interface SignalE2EPreKeyDao { suspend fun getMaxId(): Int } +/** Queries for our signed EC pre-keys. */ @Dao interface SignalE2ESignedPreKeyDao { @Query("SELECT * FROM signal_e2e_signed_pre_keys WHERE id = :id LIMIT 1")@@ -564,6 +588,7 @@ interface SignalE2ESignedPreKeyDao { suspend fun delete(id: Int) } +/** Queries for our Kyber pre-keys. */ @Dao interface SignalE2EKyberPreKeyDao { @Query("SELECT * FROM signal_e2e_kyber_pre_keys WHERE id = :id LIMIT 1")@@ -582,6 +607,7 @@ interface SignalE2EKyberPreKeyDao { suspend fun delete(id: Int) } +/** Queries for used last-resort Kyber base keys (replay detection). */ @Dao interface SignalE2EKyberUsedBaseKeyDao { @Query(@@ -597,6 +623,7 @@ interface SignalE2EKyberUsedBaseKeyDao { suspend fun deleteForKyberPreKey(kyberPreKeyId: Int) } +/** Queries for group sender-key records. */ @Dao interface SignalE2ESenderKeyDao { @Query("SELECT * FROM signal_e2e_sender_keys WHERE address = :address AND " +@@ -635,6 +662,7 @@ data class SignalProfileKey( val profileKey: ByteArray, ) +/** Queries for the sealed-sender delivery certificate row. */ @Dao interface SignalSenderCertificateDao { @Query("SELECT * FROM signal_sender_certificate WHERE id = 0 LIMIT 1")@@ -647,6 +675,7 @@ interface SignalSenderCertificateDao { suspend fun clear() } +/** Queries for recipient profile keys. */ @Dao interface SignalProfileKeyDao { @Query("SELECT * FROM signal_profile_keys WHERE address = :address LIMIT 1")@@ -658,6 +687,7 @@ interface SignalProfileKeyDao { // -- Call log -- +/** One Signal voice/video call in the call log, with peer, direction and outcome. */ @Entity(tableName = "signal_call_log") data class SignalCallLog( @PrimaryKey val callId: String,@@ -670,6 +700,7 @@ data class SignalCallLog( val outcome: String = "", ) +/** Queries for the Signal call log. */ @Dao interface SignalCallLogDao { @Insert(onConflict = OnConflictStrategy.REPLACE)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDeviceMismatch.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDeviceMismatch.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDeviceMismatch.ktindex a1f5cb9fb2..9dcaa0ad2c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDeviceMismatch.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalDeviceMismatch.kt@@ -19,6 +19,7 @@ data class SignalDeviceMismatch( /** Devices whose session should be archived. */ val archive: Set<Int>, ) {+ /** Factories and the 409-mismatch parser for [SignalDeviceMismatch]. */ companion object { private val json = Json { ignoreUnknownKeys = true } private const val HTTP_MISMATCH = 409
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEvent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEvent.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEvent.ktindex 24c6148e2f..32d80c4855 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEvent.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEvent.kt@@ -14,6 +14,7 @@ sealed interface SignalEvent { val detail: String? = null, ) : SignalEvent + /** A conversation-list row changed: latest preview, unread count and peer metadata. */ data class ConversationUpdate( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -31,6 +32,7 @@ sealed interface SignalEvent { val isMessageRequest: Boolean = false, ) : SignalEvent + /** A message row changed (new, edited or status-updated) in a conversation. */ data class MessageUpdate( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -74,6 +76,7 @@ sealed interface SignalEvent { val timestamp: Long = 0L, ) : SignalEvent + /** A message was edited; the row now shows the replacement body. */ data class MessageEdited( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String? = null,@@ -82,6 +85,7 @@ sealed interface SignalEvent { val timestamp: Long = 0L, ) : SignalEvent + /** A delivery or read receipt for one of our sent messages. */ data class ReadReceipt( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -92,6 +96,7 @@ sealed interface SignalEvent { val isDelivery: Boolean = false, ) : SignalEvent + /** A conversation was deleted. */ data class ConversationDeleted( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -105,6 +110,7 @@ sealed interface SignalEvent { val isTyping: Boolean, ) : SignalEvent + /** An emoji reaction was added to a message. */ data class ReactionReceived( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -113,6 +119,7 @@ sealed interface SignalEvent { val emoji: String, ) : SignalEvent + /** An emoji reaction was removed from a message. */ data class ReactionRemoved( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -120,6 +127,7 @@ sealed interface SignalEvent { val senderId: String, ) : SignalEvent + /** A vote was cast on a poll message. */ data class PollVote( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -128,41 +136,48 @@ sealed interface SignalEvent { val optionNames: List<String>, ) : SignalEvent + /** A conversation (group) was renamed. */ data class ConversationNameChanged( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, val newName: String, ) : SignalEvent + /** A conversation avatar changed. */ data class ConversationAvatarChanged( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, val avatarUrl: String?, ) : SignalEvent + /** A participant joined a group conversation. */ data class ParticipantAdded( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, val participantId: String, ) : SignalEvent + /** A participant left or was removed from a group conversation. */ data class ParticipantRemoved( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, val participantId: String, ) : SignalEvent + /** A conversation mute setting changed; muteExpireTimeMs is when the mute lapses. */ data class MuteSettingChanged( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, val muteExpireTimeMs: Long, ) : SignalEvent + /** A message request arrived from an unknown sender. */ data class MessageRequestReceived( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String, ) : SignalEvent + /** Sending a message failed. */ data class SendFailed( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -171,6 +186,7 @@ sealed interface SignalEvent { val errorMessage: String, ) : SignalEvent + /** An inbound message could not be decrypted (session or identity problem). */ data class DecryptionError( override val source: SignalSource = SignalSource.SIGNAL, val conversationId: String,@@ -255,6 +271,7 @@ enum class SignalState { Ready, } +/** Which Signal line an event came from. */ enum class SignalSource { SIGNAL } /** A media/share attachment carried on a Signal message. Mirrors WhatsApp's MessageAttachment. */@@ -279,6 +296,7 @@ data class SignalHistoryConversation( val messages: List<SignalHistoryMessage>, ) +/** One message inside a history-sync conversation payload. */ data class SignalHistoryMessage( val messageId: String, val body: String,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.ktindex 8732299ccb..e4b134b2ac 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalEventProcessor.kt@@ -254,5 +254,6 @@ class SignalEventProcessor(private val db: SignalDatabase) { messages.updateServiceData(messageId, transform(current).serialize()) } + /** Logging tag for [SignalEventProcessor]. */ companion object { private const val TAG = "SignalEventProcessor" } }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalGroups.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalGroups.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalGroups.ktindex e9ffeb1d2d..70a584cc4a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalGroups.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalGroups.kt@@ -40,6 +40,7 @@ object SignalGroups { const val GROUPSV2_TOKEN_PATH = "/v1/certificate/auth/group" const val HIGHEST_KNOWN_EPOCH = 7 + /** The result of creating a Signal group: its master key and initial revision. */ data class GroupCreateResult( val masterKey: ByteArray, val revision: Int,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalInbound.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalInbound.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalInbound.ktindex f6c96df433..94ba06c903 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalInbound.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalInbound.kt@@ -214,7 +214,8 @@ private suspend fun SignalClient.sendRetryReceipt(env: SignalProtocol.SignalEnve urgent = false, ) when (val outcome = putMessages(sender, json, accessKey = null)) {- is SignalClient.SendOutcome.Success -> Log.status(TAG, "sent a retry receipt to $sender:${env.sourceDevice}")+ is SignalClient.SendOutcome.Success ->+ Log.status(TAG, "sent a retry receipt to $sender:${env.sourceDevice}") else -> Log.status(TAG, "could not send a retry receipt to $sender: $outcome") } } catch (expected: Throwable) {
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalLineSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalLineSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalLineSession.ktindex a0162132f4..96a2c0f698 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalLineSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalLineSession.kt@@ -67,6 +67,7 @@ class SignalLineSession private constructor( store.setBoolean(KEY_SIGNED_IN, false) } + /** Preference keys for the Signal line session (signed-in flag, phone number). */ companion object { private const val KEY_SIGNED_IN = "sig_signed_in" private const val KEY_PHONE_NUMBER = "sig_phone_number"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.ktindex 31e1938396..4e5eee99e0 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalProtocol.kt@@ -35,6 +35,7 @@ object SignalProtocol { private const val BYTE_MASK = 0xFFL private const val BYTE_BITS = 8 + /** A decrypted Signal service envelope: sender ACI/device, timestamp and plaintext content bytes. */ data class SignalEnvelope( val type: SignalServiceProtos.Envelope.Type, val sourceAci: String,@@ -52,19 +53,30 @@ object SignalProtocol { val rawEnvelope: SignalServiceProtos.Envelope? = null, ) + /** The decoded payload of a Signal envelope, split by Signal protocol message kind. */ sealed interface ParsedContent {+ /** A normal data message (text, attachments, group traffic). */ data class Data( val dataMessage: SignalServiceProtos.DataMessage, val raw: SignalServiceProtos.Content, ) : ParsedContent+ /** A delivery/read receipt. */ data class Receipt(val receiptMessage: SignalServiceProtos.ReceiptMessage) : ParsedContent+ /** A typing indicator. */ data class Typing(val typingMessage: SignalServiceProtos.TypingMessage) : ParsedContent+ /** An edit of a previously sent message. */ data class Edit(val editMessage: SignalServiceProtos.EditMessage) : ParsedContent+ /** A call signalling message. */ data class Call(val callMessage: SignalServiceProtos.CallMessage) : ParsedContent+ /** A null/padding message, used to keep sealed-sender traffic sizes uniform. */ data class Null(val nullMessage: SignalServiceProtos.NullMessage) : ParsedContent+ /** A sync message from our own other device. */ data class Sync(val syncMessage: SignalServiceProtos.SyncMessage) : ParsedContent+ /** A story message. */ data class Story(val storyMessage: SignalServiceProtos.StoryMessage) : ParsedContent+ /** Content that failed to decrypt; carries the raw bytes for diagnostics. */ data class DecryptionError(val bytes: ByteArray) : ParsedContent+ /** A content kind this client does not model yet; carries the raw proto. */ data class Unknown(val raw: SignalServiceProtos.Content) : ParsedContent } @@ -296,6 +308,7 @@ object SignalProtocol { return v } + /** Legacy text WebSocket frame; superseded by the binary WebSocket message helpers. */ @Deprecated("Use binary WebSocketMessage helpers") data class WsFrame( val type: String,
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalRepository.ktindex 88c03d88af..bacbbe973e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalRepository.kt@@ -17,6 +17,7 @@ class SignalRepository private constructor(context: Context) : /** Direct database access for legacy `runBlocking` bridges; prefer suspend wrappers for new code. */ fun database(): SignalDatabase = db + /** The singleton [SignalRepository] instance holder. */ companion object { @Volatile private var instance: SignalRepository? = null
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalServiceData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalServiceData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalServiceData.ktindex d5a05b65aa..aee18ab962 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalServiceData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalServiceData.kt@@ -35,6 +35,7 @@ data class SignalServiceData( ) { fun serialize(): String = JSON.encodeToString(this) + /** The JSON codec and parser entry point for [SignalServiceData]. */ companion object { private val JSON = Json { ignoreUnknownKeys = true; encodeDefaults = true } @@ -45,6 +46,7 @@ data class SignalServiceData( } } +/** One option of a Signal poll, with its running vote tally. */ @Serializable data class SignalPollOptionData( val name: String,@@ -52,5 +54,6 @@ data class SignalPollOptionData( val voters: List<String> = emptyList(), ) +/** One emoji reaction tally on a Signal message. */ @Serializable data class SignalReaction(val emoji: String, val count: Int)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.ktindex 119720802e..79f9955ae2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallManager.kt@@ -45,6 +45,7 @@ class SignalCallManager( private val sslSocketFactory: () -> SSLSocketFactory?, ) : CallManager.Observer { + /** The lifecycle phase of the current Signal call. */ enum class CallState { Ringing, Connecting, Connected, Ended } internal val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallMessage.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallMessage.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallMessage.ktindex a2a915fb53..7427e95661 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallMessage.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/call/SignalCallMessage.kt@@ -14,14 +14,19 @@ import org.whispersystems.signalservice.internal.push.SignalServiceProtos sealed interface SignalCallMessage { val callId: Long + /** A call offer: opaque SDP blob and whether video is offered. */ data class Offer(override val callId: Long, val opaque: ByteArray, val video: Boolean) : SignalCallMessage+ /** A call answer: opaque SDP blob. */ data class Answer(override val callId: Long, val opaque: ByteArray) : SignalCallMessage+ /** ICE candidates for a call, as opaque blobs. */ data class Ice(override val callId: Long, val candidates: List<ByteArray>) : SignalCallMessage+ /** A call hangup, with the hangup kind. */ data class Hangup( override val callId: Long, val type: CallManager.HangupType, val deviceId: Int, ) : SignalCallMessage+ /** The callee is busy. */ data class Busy(override val callId: Long) : SignalCallMessage }
communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/RustSignalCrypto.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/RustSignalCrypto.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/RustSignalCrypto.ktindex 93253fb024..767abc5bf8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/RustSignalCrypto.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/RustSignalCrypto.kt@@ -131,6 +131,7 @@ object RustSignalCrypto { // -- Convenience helpers -- + /** An E2E key pair from the Rust crypto core (Curve25519, split private/public). */ data class KeyPair(val privateKey: ByteArray, val publicKey: ByteArray) fun generateKeyPairSplit(): KeyPair {@@ -143,6 +144,7 @@ object RustSignalCrypto { blob.copyOfRange(PRIVATE_KEY_SIZE, KEYPAIR_SIZE)) } + /** The result of a Rust 1:1 encrypt: whether a pre-key message and the updated session record. */ data class EncryptResult(val isPreKey: Boolean, val body: ByteArray, val newSession: ByteArray) fun encryptSplit(sessionBytes: ByteArray, plaintext: ByteArray): EncryptResult { val out = encrypt(sessionBytes, plaintext) ?: throw IllegalStateException("Rust encrypt returned null")@@ -150,6 +152,7 @@ object RustSignalCrypto { return EncryptResult(out[0].isNotEmpty() && out[0][0].toInt() != 0, out[1], out[2]) } + /** The result of a Rust 1:1 decrypt: plaintext and the updated session record. */ data class DecryptResult(val plaintext: ByteArray, val newSession: ByteArray) fun decryptMessageSplit(sessionBytes: ByteArray, ciphertext: ByteArray): DecryptResult { val out = decryptMessage(sessionBytes, ciphertext) ?: throw IllegalStateException("Rust decryptMessage null")
communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.ktindex 4e3477ee47..eec4bd45e6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2E.kt@@ -213,6 +213,7 @@ class SignalE2E( fun decryptDM(aci: String, deviceId: Int, ciphertext: ByteArray): ByteArray = decryptDM(aci, deviceId, false, ciphertext) + /** A peers pre-key bundle parsed off the wire: registration id, pre-keys and identity key. */ data class ParsedPreKeyBundle( val registrationId: Int, val preKeyId: Int?,@@ -349,6 +350,7 @@ class SignalE2E( val lastResortKyber: KeyEntity?, val oneTimeEcPreKeys: List<KeyEntity>, ) {+ /** One pre-key to upload: id, public key and signature (signed/Kyber keys only). */ data class KeyEntity(val id: Int, val publicKey: ByteArray, val signature: ByteArray? = null) val isEmpty: Boolean@@ -382,6 +384,7 @@ class SignalE2E( return locals } + /** Pre-key replenishment thresholds and logging tag for [SignalE2E]. */ companion object { internal const val TAG = "SignalE2E"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2EPreKeys.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2EPreKeys.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2EPreKeys.ktindex 0fc26465f8..95d35cfbee 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2EPreKeys.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/e2e/SignalE2EPreKeys.kt@@ -71,7 +71,9 @@ internal fun SignalE2E.seedStoredSignedPreKey(id: Int): Boolean { val identityOk = signature.isNotEmpty() && ECPublicKey(ownIdentityPublicKey).verifySignature(pub, signature) if (!identityOk) {- Log.status(SignalE2E.TAG, "stored signed pre-key $id signature does not verify under our identity key; rotating")+ Log.status(+ SignalE2E.TAG,+ "stored signed pre-key $id signature does not verify under our identity key; rotating") return false } protocolStore.storeSignedPreKey(
communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.ktindex 17905ab6a4..3408e2ece1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt@@ -44,12 +44,14 @@ class RegistrationHttpClient(private val context: Context) { var baseUrl: String = "https://chat.signal.org" var cdnUrl: String = "https://cdn.signal.org" + /** The result of requesting an SMS/voice verification code from the Signal service. */ data class CodeResult(val status: String, val reason: String?, val raw: String) { val ok: Boolean get() = status == "sent" || status == "ok" || status == "200" /** Server asked for an hCaptcha token (requestedInformation contains "captcha"). */ val needsCaptcha: Boolean get() = status == "captcha" }+ /** The result of submitting a Signal registration; carries the new ACI/PNI on success. */ data class RegisterResult( val status: String, val aci: String?,@@ -58,7 +60,9 @@ class RegistrationHttpClient(private val context: Context) { val auth: SignalAuthData?, val raw: String, ) { val ok: Boolean get() = status == "ok" }+ /** Whether a number is registered on Signal (whoami probe), plus the raw response. */ data class ExistResult(val exists: Boolean, val reason: String?, val raw: String)+ /** A Signal registration session: what the service still needs before a code can be sent. */ data class SessionInfo( val id: String, val allowedToRequestCode: Boolean,@@ -238,6 +242,9 @@ class RegistrationHttpClient(private val context: Context) { // Real Signal has no GET /v1/accounts/exists/{e164}; CDSIv2 is authority for number->ACI. // Post-auth use GET /v1/accounts/whoami.+ // The number is not probed directly: post-auth whoami identifies by credentials, and pre-registration+ // has no existence endpoint (CDSIv2 is the authority), so e164 only documents the caller's intent.+ @Suppress("UnusedParameter") suspend fun checkExists(e164: String): ExistResult { val auth = SignalAuthData.load(context) // If authenticated (registered), probe real endpoint GET /v1/accounts/whoami with Basic e164:password@@ -289,7 +296,7 @@ class RegistrationHttpClient(private val context: Context) { ) if (resp.status == HTTP_LOCKED) throw IllegalStateException("423 RegistrationLock (live-only: needs" + "svr2Credentials/recoveryPassword)")- if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(500)}")+ if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}") return parseSession(resp.body) } @@ -318,7 +325,7 @@ class RegistrationHttpClient(private val context: Context) { body = body, sslSocketFactory = SignalTrust.sslSocketFactory(context), )- if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(500)}")+ if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}") return parseSession(resp.body) } @@ -337,9 +344,16 @@ class RegistrationHttpClient(private val context: Context) { body = body, sslSocketFactory = SignalTrust.sslSocketFactory(context), )- if (resp.status == HTTP_LOCKED) throw IllegalStateException("423 RegistrationLock (live-only)")- if (resp.status == HTTP_RATE_LIMITED) throw IllegalStateException("429 rate limited: ${resp.body.take(500)}")- if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(500)}")+ val failure = when {+ resp.status == HTTP_LOCKED ->+ IllegalStateException("423 RegistrationLock (live-only)")+ resp.status == HTTP_RATE_LIMITED ->+ IllegalStateException("429 rate limited: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")+ !resp.isSuccess ->+ IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")+ else -> null+ }+ if (failure != null) throw failure return parseSession(resp.body) } @@ -361,7 +375,7 @@ class RegistrationHttpClient(private val context: Context) { if (resp.isSuccess || session.verified) { return session }- throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(500)}")+ throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}") } private suspend fun submitRegistration(sessionId: String, auth: SignalAuthData): RegisterResult {@@ -375,7 +389,39 @@ class RegistrationHttpClient(private val context: Context) { val e164 = auth.phoneNumber val basic = "Basic " + b64NoPad("$e164:$password".toByteArray(Charsets.UTF_8)) - val accountAttributes = buildAccountAttributesJson(auth)+ val bodyJson = buildRegistrationBody(sessionId, auth)++ val resp = NetworkClient.performRequest(+ "$baseUrl$REGISTRATION_PATH",+ method = "POST",+ headers = mapOf(+ "Content-Type" to "application/json",+ "Authorization" to basic,+ ),+ body = bodyJson,+ sslSocketFactory = SignalTrust.sslSocketFactory(context),+ )+ // 423 RegistrationLock — live-only: server returns {timeRemaining, svr2Credentials:{username,password},+ // svr3Credentials} + recoveryPassword path+ if (resp.status == HTTP_LOCKED) {+ return RegisterResult(+ "error",+ null,+ null,+ "423 RegistrationLock (live-only: needs svr2Credentials/recoveryPassword via SVR2/SVR3)",+ null,+ resp.body)+ }+ if (!resp.isSuccess) {+ // Log the full server body so a 422/400 names the rejected field in logcat on the next retest.+ Log.error(TAG, "submitRegistration HTTP ${resp.status}: ${resp.body.take(LOG_BODY_MAX_CHARS)}")+ return RegisterResult("error", null, null, "HTTP ${resp.status}", null, resp.body)+ }+ return finalizeRegister(resp.body, auth)+ }++ /** The POST /v1/registration body: session, account attributes and ACI/PNI key material. */+ private fun buildRegistrationBody(sessionId: String, auth: SignalAuthData): String { // Identity keys: Base64-nopad(IdentityKey.serialize() 33B = 0x05||32) val aciIdKey = auth.effectiveAciPublic().ifEmpty { auth.aciIdentityPublicKey } val pniIdKey = auth.pniIdentityPublicKey.ifEmpty { auth.effectiveAciPublic() }@@ -395,11 +441,11 @@ class RegistrationHttpClient(private val context: Context) { put("signature", sigB64.trimEnd('=')) } - val bodyJson = JSONObject().apply {+ return JSONObject().apply { put("sessionId", sessionId) // recoveryPassword is xor with sessionId — null here; live-only SVR re-registration uses recoveryPassword // instead- put("accountAttributes", accountAttributes)+ put("accountAttributes", buildAccountAttributesJson(auth)) put("aciIdentityKey", aciIdKey.trimEnd('=')) put("pniIdentityKey", pniIdentityWire.trimEnd('=')) put(@@ -421,34 +467,6 @@ class RegistrationHttpClient(private val context: Context) { put("skipDeviceTransfer", true) put("requireAtomic", true) }.toString()-- val resp = NetworkClient.performRequest(- "$baseUrl$REGISTRATION_PATH",- method = "POST",- headers = mapOf(- "Content-Type" to "application/json",- "Authorization" to basic,- ),- body = bodyJson,- sslSocketFactory = SignalTrust.sslSocketFactory(context),- )- // 423 RegistrationLock — live-only: server returns {timeRemaining, svr2Credentials:{username,password},- // svr3Credentials} + recoveryPassword path- if (resp.status == HTTP_LOCKED) {- return RegisterResult(- "error",- null,- null,- "423 RegistrationLock (live-only: needs svr2Credentials/recoveryPassword via SVR2/SVR3)",- null,- resp.body)- }- if (!resp.isSuccess) {- // Log the full server body so a 422/400 names the rejected field in logcat on the next retest.- Log.error(TAG, "submitRegistration HTTP ${resp.status}: ${resp.body.take(1000)}")- return RegisterResult("error", null, null, "HTTP ${resp.status}", null, resp.body)- }- return finalizeRegister(resp.body, auth) } private fun buildAccountAttributesJson(auth: SignalAuthData): JSONObject {@@ -501,18 +519,28 @@ class RegistrationHttpClient(private val context: Context) { val status = j.optString("status", if (body.contains("\"uuid\"") || body.contains("\"aci\"")) "ok" else "error") val aci = j.optStringOrNull("uuid") ?: j.optStringOrNull("aci") ?: j.optStringOrNull("number") val pni = j.optStringOrNull("pni")+ val updated = persistRegisteredAuth(j, body, auth, status, aci, pni)+ val finalStatus = if (updated != null) "ok" else status+ return RegisterResult(finalStatus, aci, pni, j.optStringOrNull("reason"), updated, body)+ }++ /** Persist the registered ACI/PNI onto [auth] when the response carries an account id. */+ private fun persistRegisteredAuth(+ j: JSONObject,+ body: String,+ auth: SignalAuthData,+ status: String,+ aci: String?,+ pni: String?,+ ): SignalAuthData? { // VerifyAccountResponse fields: uuid/aci, pni, storageCapable, number, reregistration val aciVal = j.optStringOrNull("uuid") ?: j.optStringOrNull("aci") ?: auth.aci- val pniVal = pni ?: auth.pni val ok = status == "ok" || (aciVal.isNotEmpty() && body.contains("\"uuid\""))- val updated = if (ok || j.has("uuid") || j.has("aci")) {- auth.copy(- aci = aciVal.ifEmpty { aci ?: auth.aci },- pni = pniVal,- registered = true).also { SignalAuthData.save(context, it) }- } else null- val finalStatus = if (updated != null) "ok" else status- return RegisterResult(finalStatus, aci, pni, j.optStringOrNull("reason"), updated, body)+ if (!ok && !j.has("uuid") && !j.has("aci")) return null+ return auth.copy(+ aci = aciVal.ifEmpty { aci ?: auth.aci },+ pni = pni ?: auth.pni,+ registered = true).also { SignalAuthData.save(context, it) } } private fun parseSession(body: String): SessionInfo {@@ -542,11 +570,16 @@ class RegistrationHttpClient(private val context: Context) { return bytes.size == UUID_SIZE } + /** HTTP status constants and logging tag for the Signal registration client. */ companion object { private const val TAG = "SignalRegHttp" private const val HTTP_OK = 200 private const val HTTP_LOCKED = 423 private const val HTTP_RATE_LIMITED = 429+ /** How much of an error response body is quoted in an exception message. */+ private const val ERROR_BODY_MAX_CHARS = 500+ /** How much of an error response body is written to the log for diagnosis. */+ private const val LOG_BODY_MAX_CHARS = 1000 private const val UUID_SIZE = 16 private const val VERIFICATION_SESSION_PATH = "/v1/verification/session" private const val VERIFICATION_CODE_PATH = "/v1/verification/session/%s/code"
communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalPqPreKey.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalPqPreKey.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalPqPreKey.ktindex 847f5de1d2..ca7bf28af4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalPqPreKey.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalPqPreKey.kt@@ -22,6 +22,7 @@ object SignalPqPreKey { private const val KYBER1024_PUB_SIZE = 1569 + /** A generated post-quantum (Kyber1024) pre-key for Signal registration. */ data class Generated( val keyId: Int, val publicKey: ByteArray, // 1569B = 0x08 || 1568 raw Kyber1024 pub (tag INTACT for wire)
communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalRegistrationKeys.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalRegistrationKeys.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalRegistrationKeys.ktindex db35ba79e2..1cdbd6ad4d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalRegistrationKeys.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/SignalRegistrationKeys.kt@@ -26,6 +26,7 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair * Secret key (3168B raw + tag) is persisted locally only, never uploaded. */ class SignalRegistrationKeys private constructor(val authScaffold: SignalAuthData) {+ /** Registration-id bounds and factories for [SignalRegistrationKeys]. */ companion object { private const val MAX_REGISTRATION_ID = 0x3FFF
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalAttachmentUpload.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalAttachmentUpload.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalAttachmentUpload.ktindex 359319d8e1..07608916a8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalAttachmentUpload.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalAttachmentUpload.kt@@ -24,6 +24,7 @@ object SignalAttachmentUpload { private val json = Json { ignoreUnknownKeys = true } + /** The signed upload form for a Signal attachment: CDN, key and headers. */ data class UploadForm( val cdn: Int, /** Becomes `AttachmentPointer.cdnKey`. */
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCdsi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCdsi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCdsi.ktindex 3ef911253a..e225d58cfb 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCdsi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalCdsi.kt@@ -29,11 +29,13 @@ object SignalCdsi { private val json = Json { ignoreUnknownKeys = true } + /** Short-lived CDSi credentials (username/password) for one contact-discovery lookup. */ data class Credentials(val username: String, val password: String) /** One discovered account. [aci] is null when the number is registered but its ACI is withheld. */ data class Discovered(val e164: String, val aci: String?, val pni: String?) + /** The result of a CDSi lookup: discovered accounts plus a rate-limit continuation token. */ data class LookupResult( val discovered: List<Discovered>, /** Continuation token to reuse next time, reducing rate-limit cost. */
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.ktindex 73bd673cb8..20aa69c530 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalKeysApi.kt@@ -34,8 +34,10 @@ object SignalKeysApi { private val json = Json { ignoreUnknownKeys = true } + /** Thrown when the service has no pre-key bundle for an account (not registered). */ class UnregisteredUserException(aci: String) : Exception("$aci is not registered") + /** A pre-key bundle fetched for one device of an account. */ data class DeviceBundle(val deviceId: Int, val bundle: SignalE2E.ParsedPreKeyBundle) /**
communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.ktindex b7cff45822..c5dacedad4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/transport/SignalSocket.kt@@ -53,6 +53,7 @@ class SignalSocket( private val passwordOverride: String? = null, private val authenticated: Boolean = true, ) {+ /** Server endpoint and logging constants for [SignalSocket]. */ companion object { private const val TAG = "SignalSocket" private const val ACI_PREFIX_LENGTH = 8@@ -86,9 +87,13 @@ class SignalSocket( private val _connectionState = MutableSharedFlow<ConnectionState>(extraBufferCapacity = 16) val connectionState: SharedFlow<ConnectionState> = _connectionState.asSharedFlow() + /** WebSocket connection lifecycle state. */ sealed interface ConnectionState {+ /** The socket is connecting. */ data object Connecting : ConnectionState+ /** The socket is connected. */ data object Connected : ConnectionState+ /** The socket disconnected, with the reason. */ data class Disconnected(val reason: String) : ConnectionState }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.ktindex cca3517666..13e3b62bbc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt@@ -61,6 +61,7 @@ data class WhatsAppAuthData( // Profile name sent to /v2/* for new clients (profile_name, w2.md §2.2). val profileName: String = "", ) {+ /** Preference keys and factories for [WhatsAppAuthData]. */ companion object { // Distinct from the companion's "whatsapp_auth" in the messages module. private const val PREFS_NAME = "communicate_whatsapp_auth"
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 13ea238aa5..7fb43dc42f 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@@ -35,6 +35,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull +/** The WhatsApp primary client: owns the socket, E2E stores and event stream for the WhatsApp line. */ @OptIn(ExperimentalAtomicApi::class) object WhatsAppClient { @@ -56,11 +57,17 @@ object WhatsAppClient { @Volatile var fullHistorySync: Boolean = true + /** Lifecycle state of the WhatsApp line. */ sealed interface State {+ /** Not yet connected. */ data object Idle : State+ /** The line has no registered account yet. */ data object NeedsSetup : State+ /** The socket is connecting / logging in. */ data object Connecting : State+ /** Connected and logged in. */ data object Connected : State+ /** Disconnected, with the reason. */ data class Disconnected(val reason: String) : State }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.ktindex ac90eef971..137d2e7856 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt@@ -31,8 +31,10 @@ object WhatsAppContactSync { private const val TAG = "WAContactSync" private const val PAGE_SIZE = 500 + /** One device address-book contact to check against WhatsApp. */ data class DeviceContact(val e164: String, val name: String) + /** The outcome of a contact sync: how many numbers were checked and how many are on WhatsApp. */ data class SyncResult( val deviceCount: Int, val e164Count: Int,
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 aefddf06f2..947bf414a5 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@@ -73,6 +73,7 @@ abstract class WhatsAppDatabase : RoomDatabase() { abstract fun contactDao(): WhatsAppContactDao abstract fun callLogDao(): WhatsAppCallLogDao + /** Schema migrations and the singleton accessor for [WhatsAppDatabase]. */ companion object : DatabaseMigrations { /** * v1 → v2: message delivery status (ticks) + group metadata on conversations. All new@@ -133,6 +134,7 @@ abstract class WhatsAppDatabase : RoomDatabase() { } } +/** Room column converters for WhatsApp entities; string lists are stored as CSV. */ class WhatsAppTypeConverters { @ColumnTypeConverter fun fromStringList(value: List<String>): String {@@ -170,6 +172,7 @@ data class WhatsAppConversation( val participants: String = "", ) +/** Queries for WhatsApp conversations. */ @Dao interface WhatsAppConversationDao { @Query("SELECT * FROM whatsapp_history_sync_conversation WHERE chatJid = :chatJid")@@ -224,6 +227,7 @@ data class WhatsAppMediaRequest( override fun hashCode(): Int = messageId.hashCode() } +/** Queries for pending WhatsApp media backfill requests. */ @Dao interface WhatsAppMediaRequestDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -248,6 +252,7 @@ data class WhatsAppAvatarCache( val gone: Boolean = false, ) +/** Queries for the WhatsApp avatar cache. */ @Dao interface WhatsAppAvatarCacheDao { @Query("SELECT * FROM whatsapp_avatar_cache WHERE entityJid = :entityJid AND avatarId = :avatarId")@@ -268,6 +273,7 @@ data class WhatsAppPollOption( val optionName: String, ) +/** Queries for WhatsApp poll options. */ @Dao interface WhatsAppPollOptionDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -297,6 +303,7 @@ data class WhatsAppPollSecret( val secret: String, ) +/** Queries for WhatsApp poll vote secrets. */ @Dao interface WhatsAppPollSecretDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -347,6 +354,7 @@ data class WhatsAppE2ESenderKey( val record: ByteArray, ) +/** Queries for WhatsApp E2E (Signal protocol) session records. */ @Dao interface WhatsAppE2ESessionDao { @Query("SELECT * FROM whatsapp_e2e_sessions WHERE address = :address AND deviceId = :deviceId LIMIT 1")@@ -368,6 +376,7 @@ interface WhatsAppE2ESessionDao { suspend fun deleteAll(address: String) } +/** Queries for WhatsApp peer identity keys. */ @Dao interface WhatsAppE2EIdentityDao { @Query("SELECT * FROM whatsapp_e2e_identities WHERE address = :address LIMIT 1")@@ -380,6 +389,7 @@ interface WhatsAppE2EIdentityDao { suspend fun delete(address: String) } +/** Queries for our WhatsApp one-time EC pre-keys. */ @Dao interface WhatsAppE2EPreKeyDao { @Query("SELECT * FROM whatsapp_e2e_pre_keys WHERE id = :id LIMIT 1")@@ -413,6 +423,7 @@ interface WhatsAppE2EPreKeyDao { suspend fun getMaxId(): Int } +/** Queries for our WhatsApp signed EC pre-keys. */ @Dao interface WhatsAppE2ESignedPreKeyDao { @Query("SELECT * FROM whatsapp_e2e_signed_pre_keys WHERE id = :id LIMIT 1")@@ -431,6 +442,7 @@ interface WhatsAppE2ESignedPreKeyDao { suspend fun delete(id: Int) } +/** Queries for WhatsApp group sender-key records. */ @Dao interface WhatsAppE2ESenderKeyDao { @Query("SELECT * FROM whatsapp_e2e_sender_keys WHERE address = :address AND " +@@ -474,6 +486,7 @@ data class WhatsAppCachedMessage( val status: Int = 0, ) +/** Queries for cached WhatsApp messages. */ @Dao interface WhatsAppCachedMessageDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -529,6 +542,7 @@ data class WhatsAppCachedReaction( val timestamp: Long, ) +/** Queries for cached WhatsApp message reactions. */ @Dao interface WhatsAppCachedReactionDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -560,6 +574,7 @@ data class WhatsAppContact( val updatedAt: Long = 0L, ) +/** Queries for WhatsApp contacts. */ @Dao interface WhatsAppContactDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -600,6 +615,7 @@ data class WhatsAppCallLog( val outcome: String = "", ) +/** Queries for the WhatsApp call log. */ @Dao interface WhatsAppCallLogDao { @Insert(onConflict = OnConflictStrategy.REPLACE)
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDevice.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDevice.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDevice.ktindex 5e6c4856c9..9c551f1f49 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDevice.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDevice.kt@@ -58,6 +58,7 @@ data class WhatsAppSession( } } +/** Queries for linked WhatsApp devices. */ @Dao interface WhatsAppDeviceDao { @Query("SELECT * FROM whatsapp_devices WHERE deviceId = :deviceId")@@ -70,6 +71,7 @@ interface WhatsAppDeviceDao { suspend fun deleteDevice(deviceId: String) } +/** Queries for stored WhatsApp protocol sessions. */ @Dao interface WhatsAppSessionDao { @Query("SELECT * FROM whatsapp_sessions WHERE jid = :jid")@@ -103,6 +105,7 @@ data class MessageMetadata( val edits: List<String> = emptyList(), ) +/** Why a WhatsApp message could not be processed (decryption, media, …). */ enum class MessageErrorType { NO_ERROR, DECRYPTION_FAILED,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.ktindex a282c5afc8..c0f6ef439d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt@@ -17,6 +17,7 @@ sealed interface WhatsAppEvent { val detail: String? = null, ) : WhatsAppEvent + /** A conversation-list row changed: latest preview, unread count and peer metadata. */ data class ConversationUpdate( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -34,6 +35,7 @@ sealed interface WhatsAppEvent { val isMessageRequest: Boolean = false, ) : WhatsAppEvent + /** A message row changed (new, edited or status-updated) in a conversation. */ data class MessageUpdate( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -77,6 +79,7 @@ sealed interface WhatsAppEvent { val timestamp: Long = 0L, ) : WhatsAppEvent + /** A message was edited; the row now shows the replacement body. */ data class MessageEdited( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String? = null,@@ -85,6 +88,7 @@ sealed interface WhatsAppEvent { val timestamp: Long = 0L, ) : WhatsAppEvent + /** A delivery or read receipt for one of our sent messages. */ data class ReadReceipt( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -95,6 +99,7 @@ sealed interface WhatsAppEvent { val isDelivery: Boolean = false, ) : WhatsAppEvent + /** A conversation was deleted. */ data class ConversationDeleted( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -108,6 +113,7 @@ sealed interface WhatsAppEvent { val isTyping: Boolean, ) : WhatsAppEvent + /** An emoji reaction was added to a message. */ data class ReactionReceived( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -116,6 +122,7 @@ sealed interface WhatsAppEvent { val emoji: String, ) : WhatsAppEvent + /** An emoji reaction was removed from a message. */ data class ReactionRemoved( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -123,6 +130,7 @@ sealed interface WhatsAppEvent { val senderId: String, ) : WhatsAppEvent + /** A vote was cast on a poll message. */ data class PollVote( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -131,41 +139,48 @@ sealed interface WhatsAppEvent { val optionNames: List<String>, ) : WhatsAppEvent + /** A conversation (group) was renamed. */ data class ConversationNameChanged( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, val newName: String, ) : WhatsAppEvent + /** A conversation avatar changed. */ data class ConversationAvatarChanged( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, val avatarUrl: String?, ) : WhatsAppEvent + /** A participant joined a group conversation. */ data class ParticipantAdded( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, val participantId: String, ) : WhatsAppEvent + /** A participant left or was removed from a group conversation. */ data class ParticipantRemoved( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, val participantId: String, ) : WhatsAppEvent + /** A conversation mute setting changed; muteExpireTimeMs is when the mute lapses. */ data class MuteSettingChanged( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, val muteExpireTimeMs: Long, ) : WhatsAppEvent + /** A message request arrived from an unknown sender. */ data class MessageRequestReceived( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String, ) : WhatsAppEvent + /** Sending a message failed. */ data class SendFailed( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -174,6 +189,7 @@ sealed interface WhatsAppEvent { val errorMessage: String, ) : WhatsAppEvent + /** An inbound message could not be decrypted (session or identity problem). */ data class DecryptionError( override val source: MessageSource = MessageSource.WHATSAPP, val conversationId: String,@@ -264,6 +280,7 @@ data class WhatsAppHistoryConversation( val messages: List<WhatsAppHistoryMessage>, ) +/** One message inside a history-sync conversation payload. */ data class WhatsAppHistoryMessage( val messageId: String, val body: String,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.ktindex 314aa7ce93..1ffe36b3c5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppLineSession.kt@@ -68,6 +68,7 @@ class WhatsAppLineSession private constructor( store.setBoolean(KEY_SIGNED_IN, false) } + /** Preference keys for the WhatsApp line session (signed-in flag, phone number). */ companion object { private const val KEY_SIGNED_IN = "wa_signed_in" private const val KEY_PHONE_NUMBER = "wa_phone_number"
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 7dafc55bc9..900a5d7c65 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@@ -65,6 +65,7 @@ object WhatsAppProtocol { 0xe1.toByte(), 0xf7.toByte(), 0xf9.toByte(), 0x54, 0x5d, 0xa8.toByte(), 0xee.toByte(), 0x6b ) + /** One node of the WhatsApp binary XML (binary stanza) tree: tag, attributes and children. */ data class Node( val tag: String, val attrs: Map<String, String> = emptyMap(),@@ -103,6 +104,7 @@ object WhatsAppProtocol { * Implements Noise_XX_25519_AESGCM_SHA256 as per whatsmeow/socket/noisehandshake.go */ class NoiseHandshake {+ /** Noise handshake constants (hash and AEAD sizes) for [WhatsAppProtocol.NoiseHandshake]. */ companion object { private const val HASH_SIZE = 32 private const val EXPANDED_SIZE = 64@@ -239,6 +241,7 @@ object WhatsAppProtocol { return mac.doFinal(data) } + /** The key material split out of a media key: IV, cipher key and MAC key. */ data class MediaKeys( val iv: ByteArray, val cipherKey: ByteArray,@@ -246,6 +249,7 @@ object WhatsAppProtocol { val refKey: ByteArray, ) + /** The result of encrypting media for upload: media key, ciphertext and hashes. */ data class MediaEncryptResult( val mediaKey: ByteArray, val encryptedData: ByteArray,@@ -329,6 +333,7 @@ object WhatsAppProtocol { // -- Message node builders live in WhatsAppProtocolBuilders.kt / // WhatsAppProtocolBuilders2.kt (same package, extension functions). -- + /** One fan-out copy of a group message, encrypted for a single device. */ data class ParticipantEnc(val deviceJid: String, val encType: String, val ciphertext: ByteArray) // (buildFanOutMessageNode, retry receipts, queries, reactions — see Builders files.)@@ -368,6 +373,7 @@ object WhatsAppProtocol { } +/** A parsed incoming WhatsApp message stanza, flattened for the repository. */ data class WhatsAppMessage( val id: String, val from: String,@@ -402,6 +408,7 @@ data class WhatsAppMessage( val e2eMessage: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message? = null, ) +/** A shared location: coordinates plus optional place name/address. */ data class LocationData( val latitude: Double = 0.0, val longitude: Double = 0.0,@@ -414,11 +421,13 @@ data class LocationData( fun toMapsUrl(): String = "https://maps.google.com/?q=%.5f,%.5f".format(latitude, longitude) } +/** A shared contact card: display name and vCard payload. */ data class ContactData( val displayName: String = "", val vcard: String = "", ) +/** A poll: question, options and how many options may be picked. */ data class PollData( val question: String = "", val options: List<String> = emptyList(),@@ -427,9 +436,11 @@ data class PollData( val pollCreationMessageKey: String? = null, val encPayload: List<ByteArray>? = null, ) {+ /** Factories for WhatsApp protocol values. */ companion object } +/** The context info extracted from a message: forwarding, reply and mention metadata. */ data class ContextInfoResult( val isForwarded: Boolean = false, val forwardingScore: Int = 0,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppRepository.ktindex 173a5869d6..1b05c25ce2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppRepository.kt@@ -17,6 +17,7 @@ class WhatsAppRepository private constructor(context: Context) : /** Direct database access for legacy `runBlocking` bridges; prefer suspend wrappers for new code. */ fun database(): WhatsAppDatabase = db + /** The singleton [WhatsAppRepository] instance holder. */ companion object { @Volatile private var instance: WhatsAppRepository? = null
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppServiceData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppServiceData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppServiceData.ktindex 7012765be4..ecf400dc6a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppServiceData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppServiceData.kt@@ -34,6 +34,7 @@ data class WhatsAppServiceData( ) { fun serialize(): String = JSON.encodeToString(this) + /** The JSON codec and parser entry point for [WhatsAppServiceData]. */ companion object { private val JSON = Json { ignoreUnknownKeys = true; encodeDefaults = true } @@ -44,6 +45,7 @@ data class WhatsAppServiceData( } } +/** One option of a WhatsApp poll, with its running vote tally. */ @Serializable data class PollOptionData( val name: String,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/BackupImporter.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/BackupImporter.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/BackupImporter.ktindex 67a122f78a..a177e53053 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/BackupImporter.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/BackupImporter.kt@@ -23,6 +23,7 @@ object BackupImporter { private const val TAG = "WABackupImporter" private const val BATCH = 500 + /** The outcome of a WhatsApp backup import: conversations and messages imported. */ data class ImportResult( val conversationCount: Int, val messageCount: Int,
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/Crypt15Decryptor.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/Crypt15Decryptor.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/Crypt15Decryptor.ktindex ffc47ae7f2..b9460ed65f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/Crypt15Decryptor.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/backup/Crypt15Decryptor.kt@@ -41,6 +41,7 @@ object Crypt15Decryptor { private const val VARINT_CONT = 0x80 private const val VARINT_BITS = 7 + /** Thrown when a crypt15 WhatsApp backup cannot be decrypted. */ class DecryptException(message: String, cause: Throwable? = null) : Exception(message, cause) /** @return the decrypted plaintext SQLite file in [cacheDir]. */
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.ktindex 7aa590a947..6f07389635 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt@@ -16,6 +16,7 @@ import kotlinx.coroutines.launch /** Coarse call lifecycle exposed to the UI. */ enum class WhatsAppCallPhase { Idle, Outgoing, Incoming, Connecting, Active, Ended } +/** An immutable snapshot of the current WhatsApp call for the UI. */ data class WhatsAppCallState( val phase: WhatsAppCallPhase = WhatsAppCallPhase.Idle, val callId: String = "",
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.ktindex 1de0e3fe2e..deae57b9a9 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt@@ -37,6 +37,7 @@ object WhatsAppCallSignaling { val candidates: List<String> = emptyList(), val stanzaId: String = "", ) {+ /** The kind of a WhatsApp call signalling stanza. */ enum class Kind { OFFER, PREACCEPT, ACCEPT, REJECT, TERMINATE, RELAY, UNKNOWN } }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/RustWhatsAppCrypto.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/RustWhatsAppCrypto.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/RustWhatsAppCrypto.ktindex 778e436b46..ab313a68e4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/RustWhatsAppCrypto.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/RustWhatsAppCrypto.kt@@ -116,6 +116,7 @@ object RustWhatsAppCrypto { // -- Convenience helpers used by callers -- + /** An E2E key pair from the Rust crypto core (Curve25519, split private/public). */ data class KeyPair(val privateKey: ByteArray, val publicKey: ByteArray) fun generateKeyPairSplit(): KeyPair {@@ -129,6 +130,7 @@ object RustWhatsAppCrypto { ) } + /** The result of a Rust 1:1 encrypt: whether a pre-key message and the updated session record. */ data class EncryptResult(val isPreKey: Boolean, val body: ByteArray, val newSession: ByteArray) fun encryptSplit(sessionBytes: ByteArray, plaintext: ByteArray): EncryptResult { val out = encrypt(sessionBytes, plaintext) ?: throw IllegalStateException("Rust encrypt returned null")@@ -140,6 +142,7 @@ object RustWhatsAppCrypto { ) } + /** The result of a Rust 1:1 decrypt: plaintext and the updated session record. */ data class DecryptResult(val plaintext: ByteArray, val newSession: ByteArray) fun decryptMessageSplit(sessionBytes: ByteArray, ciphertext: ByteArray): DecryptResult { val out = decryptMessage(sessionBytes, ciphertext) ?: throw IllegalStateException("Rust decryptMessage null")@@ -162,6 +165,7 @@ object RustWhatsAppCrypto { return DecryptResult(out[0], out[1]) } + /** A new group sender-key state plus its distribution message (SKDM). */ data class SenderKeyCreateResult(val state: ByteArray, val skdm: ByteArray) fun createSenderKeySplit(): SenderKeyCreateResult { val out = createSenderKey() ?: throw IllegalStateException("Rust createSenderKey null")@@ -169,6 +173,7 @@ object RustWhatsAppCrypto { return SenderKeyCreateResult(out[0], out[1]) } + /** A group ciphertext plus the updated sender-key state. */ data class GroupCipherResult(val data: ByteArray, val newState: ByteArray) fun encryptGroupSplit(stateBytes: ByteArray, plaintext: ByteArray): GroupCipherResult { val out = encryptGroup(stateBytes, plaintext) ?: throw IllegalStateException("Rust encryptGroup null")
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/WhatsAppE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/WhatsAppE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/WhatsAppE2E.ktindex 49a97a7d16..80f129826f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/WhatsAppE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/e2e/WhatsAppE2E.kt@@ -59,6 +59,7 @@ class WhatsAppE2E( // -- 1:1 encrypt / decrypt ------------------------------------------------ + /** An encrypted 1:1 message: wire type (pkmsg/msg) and ciphertext. */ data class EncResult(val type: String, val data: ByteArray) fun encryptDM(jid: String, paddedPlaintext: ByteArray): EncResult {@@ -116,6 +117,7 @@ class WhatsAppE2E( // -- Parsed bundle -------------------------------------------------------- + /** A peers pre-key bundle parsed off the wire: registration id, pre-keys and identity key. */ data class ParsedPreKeyBundle( val registrationId: Int, val preKeyId: Int?, // null if absent@@ -365,6 +367,7 @@ class WhatsAppE2E( (idBytes[2].toInt() and BYTE_MASK) } + /** Crypto size constants and logging tag for [WhatsAppE2E]. */ companion object { private const val TAG = "WhatsAppE2E" private const val IDENTITY_KEY_SIZE = 32
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.ktindex 9452a94e84..b35eb31581 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/MexModels.kt@@ -28,6 +28,7 @@ data class MexResult( ) { val isSuccess: Boolean get() = transportError == null && errors.isEmpty() + /** Factories for [MexResult] (transport failures). */ companion object { /** Build a transport-level failure result (no GraphQL round-trip completed). */ fun transport(reason: String): MexResult = MexResult(null, emptyList(), reason)
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.ktindex 0d2d04c177..77e89d47e8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexOps.kt@@ -15,7 +15,6 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject-import java.util.Base64 as JavaBase64 /** * Typed, bounded catalog of `xwa2_*` MEX operations (w2.md §8). Each entry pairs a **GraphQL@@ -34,9 +33,6 @@ import java.util.Base64 as JavaBase64 object WhatsAppMexOps { private const val TAG = "WAMex"- private const val PREKEY_VERSION_BYTE = 0x05- private const val SHIFT_BYTE2 = 16- private const val SHIFT_BYTE1 = 8 // -- GraphQL operation names (persist-ids JSON keys) --------------------------------------- @@ -80,56 +76,21 @@ object WhatsAppMexOps { /** `xwa2_group_query_by_id` — read a group's metadata/participants over MEX. */ suspend fun groupQueryById(context: Context, groupJid: String, queryContext: String = "INTERACTIVE"): MexResult =- WhatsAppMex.call(context, OP_GROUP_QUERY, buildGroupQueryByIdVariables(groupJid, queryContext), "get")+ WhatsAppMex.call(+ context, OP_GROUP_QUERY, WhatsAppMexVariables.buildGroupQueryByIdVariables(groupJid, queryContext), "get") /** `xwa2_group_query_participating_groups` — groups the (optional) user participates in. */ suspend fun groupParticipatingGroups(context: Context, userJid: String? = null): MexResult =- WhatsAppMex.call(context, OP_GROUP_PARTICIPATING, buildParticipatingGroupsVariables(userJid), "get")+ WhatsAppMex.call(+ context, OP_GROUP_PARTICIPATING, WhatsAppMexVariables.buildParticipatingGroupsVariables(userJid), "get") /** `xwa2_group_batch_query_by_id` — batch group metadata read. */ suspend fun groupBatchQueryById( context: Context, groupJids: List<String>, queryContext: String = "INTERACTIVE"): MexResult =- WhatsAppMex.call(context, OP_GROUP_BATCH, buildGroupBatchQueryVariables(groupJids, queryContext), "get")-- fun buildGroupQueryByIdVariables(groupJid: String, queryContext: String): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("group_input") {- put("group_jid", groupJid)- put("query_context", queryContext)- }- },- )-- fun buildParticipatingGroupsVariables(userJid: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("participating_groups_input") {- if (userJid != null) put("id", userJid)- }- },- )-- fun buildGroupBatchQueryVariables(groupJids: List<String>, queryContext: String): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("batch_query_input") {- putJsonArray("groups") {- groupJids.forEach { jid ->- addJsonObject {- put("group_jid", jid)- put("query_context", queryContext)- }- }- }- }- },- )+ WhatsAppMex.call(+ context, OP_GROUP_BATCH, WhatsAppMexVariables.buildGroupBatchQueryVariables(groupJids, queryContext), "get") // ============================================================ Contacts (§8.3) @@ -141,7 +102,7 @@ object WhatsAppMexOps { WhatsAppMex.call( context, OP_CONTACT_DISCOVERY,- buildContactDiscoveryVariables(rawPhoneNumbers, discoveryContext),+ WhatsAppMexVariables.buildContactDiscoveryVariables(rawPhoneNumbers, discoveryContext), "get") /** `xwa2_primary_contacts_full_sync` — single/multi-page primary-contact sync. */@@ -155,50 +116,11 @@ object WhatsAppMexOps { ): MexResult = WhatsAppMex.call( context, OP_PRIMARY_CONTACTS_FULL_SYNC,- buildPrimaryContactsFullSyncVariables(rawPhoneNumbers, sessionId, pageIndex, last, syncContext),+ WhatsAppMexVariables.buildPrimaryContactsFullSyncVariables(+ rawPhoneNumbers, sessionId, pageIndex, last, syncContext), "set", ) - fun buildContactDiscoveryVariables(rawPhoneNumbers: List<String>, discoveryContext: String): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("input") {- putJsonArray("contacts") {- rawPhoneNumbers.forEach { pn ->- addJsonObject { putJsonObject("phone") { put("raw_pn", pn) } }- }- }- put("context", discoveryContext)- }- },- )-- fun buildPrimaryContactsFullSyncVariables(- rawPhoneNumbers: List<String>,- sessionId: String,- pageIndex: Int,- last: Boolean,- syncContext: String,- ): String = json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("input") {- putJsonArray("primary_contacts") {- rawPhoneNumbers.forEach { pn ->- addJsonObject { putJsonObject("phone") { put("raw_pn", pn) } }- }- }- putJsonObject("cursor") {- put("session_id", sessionId)- put("page_index", pageIndex)- put("last", last)- }- put("context", syncContext)- }- },- )- // ============================================================ Username (§8.11) /** `xwa2_username_get` — the account's current username (no args). */@@ -215,7 +137,7 @@ object WhatsAppMexOps { ): MexResult = WhatsAppMex.call( context, OP_USERNAME_CHECK,- buildUsernameCheckVariables(username, includeSuggestions, source, sessionId),+ WhatsAppMexVariables.buildUsernameCheckVariables(username, includeSuggestions, source, sessionId), "get", ) @@ -229,41 +151,15 @@ object WhatsAppMexOps { ): MexResult = WhatsAppMex.call( context, OP_USERNAME_SET,- buildUsernameSetVariables(username, pin, source, sessionId),+ WhatsAppMexVariables.buildUsernameSetVariables(username, pin, source, sessionId), "set", ) - fun buildUsernameCheckVariables(- username: String,- includeSuggestions: Boolean,- source: String,- sessionId: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- put("username", username)- put("include_suggestions", includeSuggestions)- put("source", source)- if (sessionId != null) put("session_id", sessionId)- },- )-- fun buildUsernameSetVariables(username: String, pin: String?, source: String, sessionId: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- put("username", username)- put("source", source)- if (pin != null) put("pin", pin)- if (sessionId != null) put("session_id", sessionId)- },- )- // ============================================================ Blocklist (§8.8) /** `xwa2_blocklist_get` — the account blocklist; [dhash] is the previously-returned delta hash. */ suspend fun blocklistGet(context: Context, dhash: String? = null): MexResult =- WhatsAppMex.call(context, OP_BLOCKLIST_GET, buildBlocklistGetVariables(dhash), "get")+ WhatsAppMex.call(context, OP_BLOCKLIST_GET, WhatsAppMexVariables.buildBlocklistGetVariables(dhash), "get") /** * `xwa2_update_blocklist_lid` — block/unblock a LID user. [identifierKey] is exactly one of@@ -280,34 +176,10 @@ object WhatsAppMexOps { ): MexResult = WhatsAppMex.call( context, OP_BLOCKLIST_UPDATE_LID,- buildUpdateBlocklistLidVariables(userLid, identifierKey, identifierValue, action, dhash),+ WhatsAppMexVariables.buildUpdateBlocklistLidVariables(userLid, identifierKey, identifierValue, action, dhash), "set", ) - fun buildBlocklistGetVariables(dhash: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject { if (dhash != null) put("dhash", dhash) },- )-- fun buildUpdateBlocklistLidVariables(- userLid: String,- identifierKey: String,- identifierValue: String,- action: String,- dhash: String?,- ): String = json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("block_input") {- put("user", userLid)- putJsonObject("identifier") { put(identifierKey, identifierValue) }- put("action", action)- if (dhash != null) put("dhash", dhash)- }- },- )- // ============================================================ Presence (§8.6) /**@@ -321,22 +193,9 @@ object WhatsAppMexOps { WhatsAppMex.call( context, OP_PRESENCE_ONLINE_OR_LAST,- buildOnlineOrLastStatusVariables(lidJids, lastActiveFilter),+ WhatsAppMexVariables.buildOnlineOrLastStatusVariables(lidJids, lastActiveFilter), "get") - fun buildOnlineOrLastStatusVariables(lidJids: List<String>, lastActiveFilter: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("get_online_or_last_status_input") {- putJsonArray("online_or_last_status_input") {- lidJids.forEach { jid -> addJsonObject { put("jid", jid) } }- }- if (lastActiveFilter != null) put("last_active_filter", lastActiveFilter)- }- },- )- // ============================================================ Newsletters (§8.4) /** `xwa2_newsletter` — read a channel. [keyType] = JID|INVITE; [viewRole] = SUBSCRIBER|GUEST|ADMIN. */@@ -345,49 +204,25 @@ object WhatsAppMexOps { key: String, keyType: String = "JID", viewRole: String? = null): MexResult =- WhatsAppMex.call(context, OP_NEWSLETTER, buildNewsletterVariables(key, keyType, viewRole), "get")+ WhatsAppMex.call(+ context, OP_NEWSLETTER, WhatsAppMexVariables.buildNewsletterVariables(key, keyType, viewRole), "get") /** `xwa2_newsletter_join_v2`. */ suspend fun newsletterJoinV2(context: Context, newsletterId: String): MexResult =- WhatsAppMex.call(context, OP_NEWSLETTER_JOIN_V2, buildNewsletterIdVariables(newsletterId), "set")+ WhatsAppMex.call(+ context, OP_NEWSLETTER_JOIN_V2, WhatsAppMexVariables.buildNewsletterIdVariables(newsletterId), "set") /** `xwa2_newsletter_leave_v2`. */ suspend fun newsletterLeaveV2(context: Context, newsletterId: String): MexResult =- WhatsAppMex.call(context, OP_NEWSLETTER_LEAVE_V2, buildNewsletterIdVariables(newsletterId), "set")-- fun buildNewsletterVariables(key: String, keyType: String, viewRole: String?): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("input") {- put("key", key)- put("type", keyType)- if (viewRole != null) put("view_role", viewRole)- }- },- )-- fun buildNewsletterIdVariables(newsletterId: String): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject { put("newsletter_id", newsletterId) },- )+ WhatsAppMex.call(+ context, OP_NEWSLETTER_LEAVE_V2, WhatsAppMexVariables.buildNewsletterIdVariables(newsletterId), "set") // ============================================================ Messaging keys (§8.2) /** `xwa2_get_messaging_keys` — fetch Signal prekey bundles for the given interop user JIDs. */ suspend fun getMessagingKeys(context: Context, userJids: List<String>): MexResult =- WhatsAppMex.call(context, OP_GET_MESSAGING_KEYS, buildGetMessagingKeysVariables(userJids), "get")-- fun buildGetMessagingKeysVariables(userJids: List<String>): String =- json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("input") {- putJsonArray("users") { userJids.forEach { add(it) } }- }- },- )+ WhatsAppMex.call(+ context, OP_GET_MESSAGING_KEYS, WhatsAppMexVariables.buildGetMessagingKeysVariables(userJids), "get") /** * `xwa2_set_messaging_keys` — publish our identity + signed prekey + a batch of freshly-minted@@ -422,7 +257,7 @@ object WhatsAppMexOps { TAG, "setMessagingKeys: minted ${minted.size} one-time prekeys (ids ${maxId + 1}..${maxId + minted.size})") - val variables = buildSetMessagingKeysVariables(+ val variables = WhatsAppMexVariables.buildSetMessagingKeysVariables( identity = identity, skeyId = auth.signedPreKeyId, skeyValue = skeyValue,@@ -432,51 +267,8 @@ object WhatsAppMexOps { return WhatsAppMex.call(context, OP_SET_MESSAGING_KEYS, variables, "set") } - /**- * Pure builder for the `xwa2_set_messaging_keys` `variables` (§8.2). Binary fields are standard- * Base64; ids are 3-byte big-endian (skey/prekey id space), `type` is Base64 of `0x05`.- */- fun buildSetMessagingKeysVariables(- identity: ByteArray,- skeyId: Int,- skeyValue: ByteArray,- skeySignature: ByteArray,- prekeys: List<Pair<Int, ByteArray>>,- ): String = json.encodeToString(- JsonObject.serializer(),- buildJsonObject {- putJsonObject("input") {- put("type", b64(byteArrayOf(PREKEY_VERSION_BYTE.toByte())))- put("identity", b64(identity))- putJsonObject("skey") {- put("id", b64(int3BE(skeyId)))- put("value", b64(skeyValue))- put("signature", b64(skeySignature))- }- putJsonArray("prekeys") {- prekeys.forEach { (id, value) ->- addJsonObject {- put("id", b64(int3BE(id)))- put("value", b64(value))- }- }- }- }- },- )- // -- encoding helpers ------------------------------------------------------------------------ - /** Standard Base64 (with padding), JVM-pure so the builders are unit-testable off-device. */- private fun b64(bytes: ByteArray): String = JavaBase64.getEncoder().encodeToString(bytes)- /** Decode a STANDARD-base64 field stored in [WhatsAppAuthData] (android.util.Base64.NO_WRAP). */ private fun decodeStd(s: String): ByteArray = AndroidBase64.decode(s, AndroidBase64.NO_WRAP)-- /** 3-byte big-endian encoding of a prekey/skey id (matches the classic wire encoding). */- private fun int3BE(id: Int): ByteArray = byteArrayOf(- (id ushr SHIFT_BYTE2).toByte(),- (id ushr SHIFT_BYTE1).toByte(),- id.toByte(),- ) }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexVariables.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexVariables.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexVariables.ktnew file mode 100644index 0000000000..878ba60047--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/mex/WhatsAppMexVariables.kt@@ -0,0 +1,239 @@+package com.vayunmathur.communicate.data.whatsapp.mex++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.add+import kotlinx.serialization.json.addJsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import kotlinx.serialization.json.putJsonArray+import kotlinx.serialization.json.putJsonObject+import java.util.Base64 as JavaBase64++/**+ * JVM-pure `variables` builders for the MEX operations in [WhatsAppMexOps].+ *+ * Shapes follow the SDL argument names from w2.md §8.0 (a single `variables` map keyed by+ * argument name); JIDs and binary fields are standard Base64 (Argo BYTES over the JSON shim).+ * Kept separate from the operations so the builders are unit-testable off-device.+ */+object WhatsAppMexVariables {++ private const val PREKEY_VERSION_BYTE = 0x05+ private const val SHIFT_BYTE2 = 16+ private const val SHIFT_BYTE1 = 8++ private val json = Json { encodeDefaults = true }++fun buildGroupQueryByIdVariables(groupJid: String, queryContext: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("group_input") {+ put("group_jid", groupJid)+ put("query_context", queryContext)+ }+ },+ )++fun buildParticipatingGroupsVariables(userJid: String?): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("participating_groups_input") {+ if (userJid != null) put("id", userJid)+ }+ },+ )++fun buildGroupBatchQueryVariables(groupJids: List<String>, queryContext: String): String =+ json.encodeToString(+ JsonObject.serializer(),+ buildJsonObject {+ putJsonObject("batch_query_input") {+ putJsonArray("groups") {+ groupJids.forEach { jid ->+ addJsonObject {+ put("group_jid", jid)+
Diff truncated.