Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppDatabase.kt
WhatsAppDatabase.kt664 lines · 25.5 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import android.content.Context |
| 4 | import androidx.room3.ColumnTypeConverter |
| 5 | import androidx.room3.ColumnTypeConverters |
| 6 | import androidx.room3.Database |
| 7 | import androidx.room3.Dao |
| 8 | import androidx.room3.Entity |
| 9 | import androidx.room3.Index |
| 10 | import androidx.room3.Insert |
| 11 | import androidx.room3.OnConflictStrategy |
| 12 | import androidx.room3.PrimaryKey |
| 13 | import androidx.room3.Query |
| 14 | import androidx.room3.RoomDatabase |
| 15 | import androidx.room3.migration.Migration |
| 16 | import androidx.sqlite.SQLiteConnection |
| 17 | import androidx.sqlite.execSQL |
| 18 | import com.vayunmathur.library.util.DatabaseMigrations |
| 19 | |
| 20 | /** |
| 21 | * Room database for WhatsApp-specific data. |
| 22 | * Stores device info, session keys, conversations, media requests, and avatar cache. |
| 23 | * Aligned with Go wadb.Database which has: Conversation, Message, PollOption, |
| 24 | * MediaRequest, HSNotif, AvatarCache queries. |
| 25 | * |
| 26 | * v7 (Rust migration): E2E tables now hold Rust's own versioned blobs (RECORD_VERSION=1) |
| 27 | * rather than Java SignalRecord. Old Java blobs are incompatible, so migration clears E2E tables. |
| 28 | * |
| 29 | * communicate v2: adds message delivery status (sent/delivered/read ticks) and group metadata |
| 30 | * (isGroup/name/participants) on conversations. |
| 31 | */ |
| 32 | @Database( |
| 33 | entities = [ |
| 34 | WhatsAppDevice::class, |
| 35 | WhatsAppSession::class, |
| 36 | WhatsAppConversation::class, |
| 37 | WhatsAppMediaRequest::class, |
| 38 | WhatsAppAvatarCache::class, |
| 39 | WhatsAppPollOption::class, |
| 40 | WhatsAppPollSecret::class, |
| 41 | // Rust-backed E2E protocol stores (was libsignal-backed) |
| 42 | WhatsAppE2ESession::class, |
| 43 | WhatsAppE2EIdentity::class, |
| 44 | WhatsAppE2EPreKey::class, |
| 45 | WhatsAppE2ESignedPreKey::class, |
| 46 | WhatsAppE2ESenderKey::class, |
| 47 | // communicate additions: message/reaction cache for the merged inbox. |
| 48 | WhatsAppCachedMessage::class, |
| 49 | WhatsAppCachedReaction::class, |
| 50 | // communicate v3: device-contact sync (address book → LID/phone mapping). |
| 51 | WhatsAppContact::class, |
| 52 | // communicate v4: call log. |
| 53 | WhatsAppCallLog::class, |
| 54 | ], |
| 55 | version = 5, |
| 56 | exportSchema = true |
| 57 | ) |
| 58 | @ColumnTypeConverters(WhatsAppTypeConverters::class) |
| 59 | abstract class WhatsAppDatabase : RoomDatabase() { |
| 60 | abstract fun deviceDao(): WhatsAppDeviceDao |
| 61 | abstract fun sessionDao(): WhatsAppSessionDao |
| 62 | abstract fun conversationDao(): WhatsAppConversationDao |
| 63 | abstract fun mediaRequestDao(): WhatsAppMediaRequestDao |
| 64 | abstract fun avatarCacheDao(): WhatsAppAvatarCacheDao |
| 65 | abstract fun pollOptionDao(): WhatsAppPollOptionDao |
| 66 | abstract fun pollSecretDao(): WhatsAppPollSecretDao |
| 67 | abstract fun e2eSessionDao(): WhatsAppE2ESessionDao |
| 68 | abstract fun e2eIdentityDao(): WhatsAppE2EIdentityDao |
| 69 | abstract fun e2ePreKeyDao(): WhatsAppE2EPreKeyDao |
| 70 | abstract fun e2eSignedPreKeyDao(): WhatsAppE2ESignedPreKeyDao |
| 71 | abstract fun e2eSenderKeyDao(): WhatsAppE2ESenderKeyDao |
| 72 | abstract fun cachedMessageDao(): WhatsAppCachedMessageDao |
| 73 | abstract fun cachedReactionDao(): WhatsAppCachedReactionDao |
| 74 | abstract fun contactDao(): WhatsAppContactDao |
| 75 | abstract fun callLogDao(): WhatsAppCallLogDao |
| 76 | |
| 77 | /** Schema migrations and the singleton accessor for [WhatsAppDatabase]. */ |
| 78 | companion object : DatabaseMigrations { |
| 79 | /** |
| 80 | * v1 → v2: message delivery status (ticks) + group metadata on conversations. All new |
| 81 | * columns are additive with defaults, so existing rows stay valid. |
| 82 | */ |
| 83 | private val MIGRATION_1_2 = object : Migration(1, 2) { |
| 84 | override suspend fun migrate(connection: SQLiteConnection) { |
| 85 | connection.execSQL( |
| 86 | "ALTER TABLE whatsapp_cached_message ADD COLUMN status INTEGER NOT NULL DEFAULT 0", |
| 87 | ) |
| 88 | connection.execSQL( |
| 89 | "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN isGroup INTEGER NOT NULL DEFAULT 0", |
| 90 | ) |
| 91 | connection.execSQL( |
| 92 | "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN name TEXT", |
| 93 | ) |
| 94 | connection.execSQL( |
| 95 | "ALTER TABLE whatsapp_history_sync_conversation ADD COLUMN participants TEXT NOT NULL DEFAULT ''", |
| 96 | ) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /** v2 → v3: device-contact sync table (address book → WhatsApp LID/phone mapping). */ |
| 101 | private val MIGRATION_2_3 = object : Migration(2, 3) { |
| 102 | override suspend fun migrate(connection: SQLiteConnection) { |
| 103 | connection.execSQL( |
| 104 | "CREATE TABLE IF NOT EXISTS whatsapp_contact (" + |
| 105 | "phoneE164 TEXT NOT NULL PRIMARY KEY, " + |
| 106 | "lid TEXT NOT NULL DEFAULT '', " + |
| 107 | "displayName TEXT NOT NULL DEFAULT '', " + |
| 108 | "onWhatsApp INTEGER NOT NULL DEFAULT 0, " + |
| 109 | "updatedAt INTEGER NOT NULL DEFAULT 0)", |
| 110 | ) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | /** v3 → v4: call-log table for the WhatsApp calling stack. */ |
| 115 | private val MIGRATION_3_4 = object : Migration(3, 4) { |
| 116 | override suspend fun migrate(connection: SQLiteConnection) { |
| 117 | connection.execSQL( |
| 118 | "CREATE TABLE IF NOT EXISTS whatsapp_call_log (" + |
| 119 | "callId TEXT NOT NULL PRIMARY KEY, " + |
| 120 | "peerJid TEXT NOT NULL DEFAULT '', " + |
| 121 | "peerName TEXT NOT NULL DEFAULT '', " + |
| 122 | "outgoing INTEGER NOT NULL DEFAULT 0, " + |
| 123 | "video INTEGER NOT NULL DEFAULT 0, " + |
| 124 | "startTime INTEGER NOT NULL DEFAULT 0, " + |
| 125 | "durationSeconds INTEGER NOT NULL DEFAULT 0, " + |
| 126 | "outcome TEXT NOT NULL DEFAULT '')", |
| 127 | ) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /** v4 → v5: (conversationJid, timestamp) index for keyset conversation windows. */ |
| 132 | private val MIGRATION_4_5 = object : Migration(4, 5) { |
| 133 | override suspend fun migrate(connection: SQLiteConnection) { |
| 134 | connection.execSQL( |
| 135 | "CREATE INDEX IF NOT EXISTS `index_whatsapp_cached_message_conversationJid_timestamp` " + |
| 136 | "ON `whatsapp_cached_message` (`conversationJid`, `timestamp`)", |
| 137 | ) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5) |
| 142 | |
| 143 | /** |
| 144 | * Test seam: when set, [getDatabase] returns this instance instead |
| 145 | * of the SQLCipher-backed singleton (whose native library cannot |
| 146 | * load on a JVM test host). Production code never sets it. |
| 147 | */ |
| 148 | @Volatile |
| 149 | var overrideForTest: WhatsAppDatabase? = null |
| 150 | |
| 151 | fun getDatabase(context: Context): WhatsAppDatabase = |
| 152 | overrideForTest ?: WhatsAppRepository.get(context).database() |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /** Room column converters for WhatsApp entities; string lists are stored as CSV. */ |
| 157 | class WhatsAppTypeConverters { |
| 158 | @ColumnTypeConverter |
| 159 | fun fromStringList(value: List<String>): String { |
| 160 | return value.joinToString(",") |
| 161 | } |
| 162 | |
| 163 | @ColumnTypeConverter |
| 164 | fun toStringList(value: String): List<String> { |
| 165 | return if (value.isEmpty()) emptyList() else value.split(",") |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * History sync conversation, matching Go wadb.Conversation. |
| 171 | */ |
| 172 | @Entity(tableName = "whatsapp_history_sync_conversation") |
| 173 | data class WhatsAppConversation( |
| 174 | @PrimaryKey |
| 175 | val chatJid: String, |
| 176 | val userLoginId: String = "", |
| 177 | val lastMessageTimestamp: Long = 0L, |
| 178 | val archived: Boolean = false, |
| 179 | val pinned: Boolean = false, |
| 180 | val muteEndTime: Long = 0L, |
| 181 | val endOfHistoryTransferType: Int = 0, |
| 182 | val ephemeralExpiration: Long = 0L, |
| 183 | val ephemeralSettingTimestamp: Long = 0L, |
| 184 | val markedAsUnread: Boolean = false, |
| 185 | val unreadCount: Int = 0, |
| 186 | /** communicate v2: true for group chats (@g.us). */ |
| 187 | val isGroup: Boolean = false, |
| 188 | /** communicate v2: group subject / display name when known. */ |
| 189 | val name: String? = null, |
| 190 | /** communicate v2: CSV of participant JIDs for groups (empty for 1:1). */ |
| 191 | val participants: String = "", |
| 192 | ) |
| 193 | |
| 194 | /** Queries for WhatsApp conversations. */ |
| 195 | @Dao |
| 196 | interface WhatsAppConversationDao { |
| 197 | @Query("SELECT * FROM whatsapp_history_sync_conversation WHERE chatJid = :chatJid") |
| 198 | suspend fun getConversation(chatJid: String): WhatsAppConversation? |
| 199 | |
| 200 | @Query("SELECT * FROM whatsapp_history_sync_conversation ORDER BY lastMessageTimestamp DESC LIMIT :limit") |
| 201 | suspend fun getRecent(limit: Int): List<WhatsAppConversation> |
| 202 | |
| 203 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 204 | suspend fun upsert(conversation: WhatsAppConversation) |
| 205 | |
| 206 | @Query("DELETE FROM whatsapp_history_sync_conversation WHERE chatJid = :chatJid") |
| 207 | suspend fun delete(chatJid: String) |
| 208 | |
| 209 | @Query("DELETE FROM whatsapp_history_sync_conversation") |
| 210 | suspend fun deleteAll() |
| 211 | |
| 212 | @Query("UPDATE whatsapp_history_sync_conversation SET muteEndTime = :muteEndTime WHERE chatJid = :chatJid") |
| 213 | suspend fun updateMuteEndTime(chatJid: String, muteEndTime: Long) |
| 214 | |
| 215 | @Query("UPDATE whatsapp_history_sync_conversation SET pinned = :pinned WHERE chatJid = :chatJid") |
| 216 | suspend fun updatePinned(chatJid: String, pinned: Boolean) |
| 217 | |
| 218 | @Query("UPDATE whatsapp_history_sync_conversation SET archived = :archived WHERE chatJid = :chatJid") |
| 219 | suspend fun updateArchived(chatJid: String, archived: Boolean) |
| 220 | |
| 221 | @Query("UPDATE whatsapp_history_sync_conversation SET markedAsUnread = :unread WHERE chatJid = :chatJid") |
| 222 | suspend fun updateMarkedAsUnread(chatJid: String, unread: Boolean) |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Media backfill request, matching Go wadb.MediaRequest. |
| 227 | */ |
| 228 | @Entity(tableName = "whatsapp_media_backfill_request") |
| 229 | data class WhatsAppMediaRequest( |
| 230 | @PrimaryKey |
| 231 | val messageId: String, |
| 232 | val userLoginId: String = "", |
| 233 | val portalId: String = "", |
| 234 | val portalReceiver: String = "", |
| 235 | val mediaKey: ByteArray = ByteArray(0), |
| 236 | val status: Int = 0, // 0=not_requested, 1=requested, 2=failed, 3=skipped |
| 237 | val error: String = "", |
| 238 | ) { |
| 239 | override fun equals(other: Any?): Boolean { |
| 240 | if (this === other) return true |
| 241 | if (javaClass != other?.javaClass) return false |
| 242 | other as WhatsAppMediaRequest |
| 243 | return messageId == other.messageId |
| 244 | } |
| 245 | |
| 246 | override fun hashCode(): Int = messageId.hashCode() |
| 247 | } |
| 248 | |
| 249 | /** Queries for pending WhatsApp media backfill requests. */ |
| 250 | @Dao |
| 251 | interface WhatsAppMediaRequestDao { |
| 252 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 253 | suspend fun upsert(request: WhatsAppMediaRequest) |
| 254 | |
| 255 | @Query("DELETE FROM whatsapp_media_backfill_request WHERE messageId = :messageId") |
| 256 | suspend fun delete(messageId: String) |
| 257 | |
| 258 | @Query("SELECT * FROM whatsapp_media_backfill_request WHERE status = 0") |
| 259 | suspend fun getUnrequested(): List<WhatsAppMediaRequest> |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * Avatar cache entry, matching Go wadb.AvatarCacheEntry. |
| 264 | */ |
| 265 | @Entity(tableName = "whatsapp_avatar_cache", primaryKeys = ["entityJid", "avatarId"]) |
| 266 | data class WhatsAppAvatarCache( |
| 267 | val entityJid: String, |
| 268 | val avatarId: String, |
| 269 | val directPath: String = "", |
| 270 | val expiry: Long = 0L, |
| 271 | val gone: Boolean = false, |
| 272 | ) |
| 273 | |
| 274 | /** Queries for the WhatsApp avatar cache. */ |
| 275 | @Dao |
| 276 | interface WhatsAppAvatarCacheDao { |
| 277 | @Query("SELECT * FROM whatsapp_avatar_cache WHERE entityJid = :entityJid AND avatarId = :avatarId") |
| 278 | suspend fun get(entityJid: String, avatarId: String): WhatsAppAvatarCache? |
| 279 | |
| 280 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 281 | suspend fun put(entry: WhatsAppAvatarCache) |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Poll option hash mapping, matching Go wadb.PollOption. |
| 286 | * Maps SHA256 option hashes to option string IDs for poll vote resolution. |
| 287 | */ |
| 288 | @Entity(tableName = "whatsapp_poll_option", primaryKeys = ["msgId", "optionHash"]) |
| 289 | data class WhatsAppPollOption( |
| 290 | val msgId: String, |
| 291 | val optionHash: String, |
| 292 | val optionName: String, |
| 293 | ) |
| 294 | |
| 295 | /** Queries for WhatsApp poll options. */ |
| 296 | @Dao |
| 297 | interface WhatsAppPollOptionDao { |
| 298 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 299 | suspend fun upsert(option: WhatsAppPollOption) |
| 300 | |
| 301 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 302 | suspend fun upsertAll(options: List<WhatsAppPollOption>) |
| 303 | |
| 304 | @Query("SELECT * FROM whatsapp_poll_option WHERE msgId = :msgId") |
| 305 | suspend fun getByMessageId(msgId: String): List<WhatsAppPollOption> |
| 306 | |
| 307 | @Query("SELECT * FROM whatsapp_poll_option WHERE msgId = :msgId AND optionHash = :hash") |
| 308 | suspend fun getByHash(msgId: String, hash: String): WhatsAppPollOption? |
| 309 | |
| 310 | @Query("DELETE FROM whatsapp_poll_option WHERE msgId = :msgId") |
| 311 | suspend fun deleteByMessageId(msgId: String) |
| 312 | } |
| 313 | |
| 314 | /** |
| 315 | * Per-poll shared secret (MessageContextInfo.messageSecret, hex-encoded), keyed by the poll |
| 316 | * creation message id. Needed to encrypt our votes and decrypt incoming votes; persisted so |
| 317 | * voting works after a restart, not just within the session. |
| 318 | */ |
| 319 | @Entity(tableName = "whatsapp_poll_secret") |
| 320 | data class WhatsAppPollSecret( |
| 321 | @PrimaryKey val msgId: String, |
| 322 | val secret: String, |
| 323 | ) |
| 324 | |
| 325 | /** Queries for WhatsApp poll vote secrets. */ |
| 326 | @Dao |
| 327 | interface WhatsAppPollSecretDao { |
| 328 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 329 | suspend fun upsert(secret: WhatsAppPollSecret) |
| 330 | |
| 331 | @Query("SELECT secret FROM whatsapp_poll_secret WHERE msgId = :msgId") |
| 332 | suspend fun get(msgId: String): String? |
| 333 | } |
| 334 | |
| 335 | // -- libsignal-backed E2E protocol stores (whatsmeow signal store equivalents) -- |
| 336 | |
| 337 | /** Signal session record keyed by (signalAddress, deviceId). */ |
| 338 | @Entity(tableName = "whatsapp_e2e_sessions", primaryKeys = ["address", "deviceId"]) |
| 339 | data class WhatsAppE2ESession( |
| 340 | val address: String, |
| 341 | val deviceId: Int, |
| 342 | val record: ByteArray, |
| 343 | ) |
| 344 | |
| 345 | /** Remote identity key keyed by signal address (user[:device] string). */ |
| 346 | @Entity(tableName = "whatsapp_e2e_identities") |
| 347 | data class WhatsAppE2EIdentity( |
| 348 | @PrimaryKey val address: String, |
| 349 | val identityKey: ByteArray, |
| 350 | ) |
| 351 | |
| 352 | /** One-time pre key record keyed by id. */ |
| 353 | @Entity(tableName = "whatsapp_e2e_pre_keys") |
| 354 | data class WhatsAppE2EPreKey( |
| 355 | @PrimaryKey val id: Int, |
| 356 | val record: ByteArray, |
| 357 | val uploaded: Boolean = false, |
| 358 | ) |
| 359 | |
| 360 | /** Signed pre key record keyed by id. */ |
| 361 | @Entity(tableName = "whatsapp_e2e_signed_pre_keys") |
| 362 | data class WhatsAppE2ESignedPreKey( |
| 363 | @PrimaryKey val id: Int, |
| 364 | val record: ByteArray, |
| 365 | ) |
| 366 | |
| 367 | /** Sender (group) key record keyed by (address, deviceId, distributionId). */ |
| 368 | @Entity(tableName = "whatsapp_e2e_sender_keys", primaryKeys = ["address", "deviceId", "distributionId"]) |
| 369 | data class WhatsAppE2ESenderKey( |
| 370 | val address: String, |
| 371 | val deviceId: Int, |
| 372 | val distributionId: String, |
| 373 | val record: ByteArray, |
| 374 | ) |
| 375 | |
| 376 | /** Queries for WhatsApp E2E (Signal protocol) session records. */ |
| 377 | @Dao |
| 378 | interface WhatsAppE2ESessionDao { |
| 379 | @Query("SELECT * FROM whatsapp_e2e_sessions WHERE address = :address AND deviceId = :deviceId LIMIT 1") |
| 380 | suspend fun get(address: String, deviceId: Int): WhatsAppE2ESession? |
| 381 | |
| 382 | @Query("SELECT deviceId FROM whatsapp_e2e_sessions WHERE address = :address") |
| 383 | suspend fun getSubDeviceIds(address: String): List<Int> |
| 384 | |
| 385 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 386 | suspend fun insert(entity: WhatsAppE2ESession) |
| 387 | |
| 388 | @Query("SELECT COUNT(*) > 0 FROM whatsapp_e2e_sessions WHERE address = :address AND deviceId = :deviceId") |
| 389 | suspend fun exists(address: String, deviceId: Int): Boolean |
| 390 | |
| 391 | @Query("DELETE FROM whatsapp_e2e_sessions WHERE address = :address AND deviceId = :deviceId") |
| 392 | suspend fun delete(address: String, deviceId: Int) |
| 393 | |
| 394 | @Query("DELETE FROM whatsapp_e2e_sessions WHERE address = :address") |
| 395 | suspend fun deleteAll(address: String) |
| 396 | } |
| 397 | |
| 398 | /** Queries for WhatsApp peer identity keys. */ |
| 399 | @Dao |
| 400 | interface WhatsAppE2EIdentityDao { |
| 401 | @Query("SELECT * FROM whatsapp_e2e_identities WHERE address = :address LIMIT 1") |
| 402 | suspend fun get(address: String): WhatsAppE2EIdentity? |
| 403 | |
| 404 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 405 | suspend fun insert(entity: WhatsAppE2EIdentity) |
| 406 | |
| 407 | @Query("DELETE FROM whatsapp_e2e_identities WHERE address = :address") |
| 408 | suspend fun delete(address: String) |
| 409 | } |
| 410 | |
| 411 | /** Queries for our WhatsApp one-time EC pre-keys. */ |
| 412 | @Dao |
| 413 | interface WhatsAppE2EPreKeyDao { |
| 414 | @Query("SELECT * FROM whatsapp_e2e_pre_keys WHERE id = :id LIMIT 1") |
| 415 | suspend fun get(id: Int): WhatsAppE2EPreKey? |
| 416 | |
| 417 | @Query("SELECT * FROM whatsapp_e2e_pre_keys") |
| 418 | suspend fun getAll(): List<WhatsAppE2EPreKey> |
| 419 | |
| 420 | @Query("SELECT * FROM whatsapp_e2e_pre_keys WHERE uploaded = 0") |
| 421 | suspend fun getUnuploaded(): List<WhatsAppE2EPreKey> |
| 422 | |
| 423 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 424 | suspend fun insert(entity: WhatsAppE2EPreKey) |
| 425 | |
| 426 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 427 | suspend fun insertAll(entities: List<WhatsAppE2EPreKey>) |
| 428 | |
| 429 | @Query("UPDATE whatsapp_e2e_pre_keys SET uploaded = 1 WHERE id <= :maxId") |
| 430 | suspend fun markUploadedUpTo(maxId: Int) |
| 431 | |
| 432 | @Query("SELECT COUNT(*) > 0 FROM whatsapp_e2e_pre_keys WHERE id = :id") |
| 433 | suspend fun exists(id: Int): Boolean |
| 434 | |
| 435 | @Query("DELETE FROM whatsapp_e2e_pre_keys WHERE id = :id") |
| 436 | suspend fun delete(id: Int) |
| 437 | |
| 438 | @Query("SELECT COUNT(*) FROM whatsapp_e2e_pre_keys") |
| 439 | suspend fun getCount(): Int |
| 440 | |
| 441 | @Query("SELECT COALESCE(MAX(id), 0) FROM whatsapp_e2e_pre_keys") |
| 442 | suspend fun getMaxId(): Int |
| 443 | } |
| 444 | |
| 445 | /** Queries for our WhatsApp signed EC pre-keys. */ |
| 446 | @Dao |
| 447 | interface WhatsAppE2ESignedPreKeyDao { |
| 448 | @Query("SELECT * FROM whatsapp_e2e_signed_pre_keys WHERE id = :id LIMIT 1") |
| 449 | suspend fun get(id: Int): WhatsAppE2ESignedPreKey? |
| 450 | |
| 451 | @Query("SELECT * FROM whatsapp_e2e_signed_pre_keys") |
| 452 | suspend fun getAll(): List<WhatsAppE2ESignedPreKey> |
| 453 | |
| 454 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 455 | suspend fun insert(entity: WhatsAppE2ESignedPreKey) |
| 456 | |
| 457 | @Query("SELECT COUNT(*) > 0 FROM whatsapp_e2e_signed_pre_keys WHERE id = :id") |
| 458 | suspend fun exists(id: Int): Boolean |
| 459 | |
| 460 | @Query("DELETE FROM whatsapp_e2e_signed_pre_keys WHERE id = :id") |
| 461 | suspend fun delete(id: Int) |
| 462 | } |
| 463 | |
| 464 | /** Queries for WhatsApp group sender-key records. */ |
| 465 | @Dao |
| 466 | interface WhatsAppE2ESenderKeyDao { |
| 467 | @Query("SELECT * FROM whatsapp_e2e_sender_keys WHERE address = :address AND " + |
| 468 | "deviceId = :deviceId AND distributionId = :distributionId LIMIT 1") |
| 469 | suspend fun get(address: String, deviceId: Int, distributionId: String): WhatsAppE2ESenderKey? |
| 470 | |
| 471 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 472 | suspend fun insert(entity: WhatsAppE2ESenderKey) |
| 473 | |
| 474 | @Query("DELETE FROM whatsapp_e2e_sender_keys WHERE address = :address " + |
| 475 | "AND deviceId = :deviceId AND distributionId = :distributionId") |
| 476 | suspend fun delete(address: String, deviceId: Int, distributionId: String) |
| 477 | } |
| 478 | |
| 479 | // -- communicate message/thread cache (merged inbox + restart persistence) -- |
| 480 | |
| 481 | /** |
| 482 | * Cached WhatsApp message for the merged inbox. `serviceData` carries the rich-feature JSON |
| 483 | * (reactions/poll/edited/revoked/quoted/group) that [WhatsAppServiceData] serializes. |
| 484 | */ |
| 485 | @Entity(tableName = "whatsapp_cached_message", indices = [Index(value = ["conversationJid", "timestamp"])]) |
| 486 | data class WhatsAppCachedMessage( |
| 487 | @PrimaryKey val messageId: String, |
| 488 | val conversationJid: String, |
| 489 | val body: String, |
| 490 | val timestamp: Long, |
| 491 | val outgoing: Boolean, |
| 492 | val senderJid: String = "", |
| 493 | val senderName: String = "", |
| 494 | val isEdited: Boolean = false, |
| 495 | val isRevoked: Boolean = false, |
| 496 | val quotedMessageId: String? = null, |
| 497 | val mediaUrl: String? = null, |
| 498 | val mediaMime: String? = null, |
| 499 | val mediaName: String? = null, |
| 500 | val serviceData: String? = null, |
| 501 | /** |
| 502 | * communicate v2: outgoing delivery status, encoded as the [com.vayunmathur.communicate.data.MessageStatus] |
| 503 | * ordinal (0=None, 1=Sent, 2=Delivered, 3=Read, 4=Failed). Inbound messages stay 0. |
| 504 | */ |
| 505 | val status: Int = 0, |
| 506 | ) |
| 507 | |
| 508 | /** Queries for cached WhatsApp messages. */ |
| 509 | @Dao |
| 510 | interface WhatsAppCachedMessageDao { |
| 511 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 512 | suspend fun upsert(message: WhatsAppCachedMessage) |
| 513 | |
| 514 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 515 | suspend fun upsertAll(messages: List<WhatsAppCachedMessage>) |
| 516 | |
| 517 | @Query("SELECT * FROM whatsapp_cached_message WHERE conversationJid = :jid ORDER BY timestamp ASC") |
| 518 | suspend fun getForConversation(jid: String): List<WhatsAppCachedMessage> |
| 519 | |
| 520 | /** Keyset window: newest [limit] before [before], newest first (reverse to render). */ |
| 521 | @Query( |
| 522 | "SELECT * FROM whatsapp_cached_message WHERE conversationJid = :jid AND timestamp < :before " + |
| 523 | "ORDER BY timestamp DESC LIMIT :limit", |
| 524 | ) |
| 525 | suspend fun getForConversationBefore( |
| 526 | jid: String, |
| 527 | before: Long = Long.MAX_VALUE, |
| 528 | limit: Int = 100, |
| 529 | ): List<WhatsAppCachedMessage> |
| 530 | |
| 531 | @Query("SELECT * FROM whatsapp_cached_message WHERE messageId = :messageId LIMIT 1") |
| 532 | suspend fun get(messageId: String): WhatsAppCachedMessage? |
| 533 | |
| 534 | /** Most-recent message per conversation, newest first (for the thread list). */ |
| 535 | @Query( |
| 536 | "SELECT * FROM whatsapp_cached_message AS m WHERE m.messageId = " + |
| 537 | "(SELECT i.messageId FROM whatsapp_cached_message AS i " + |
| 538 | "WHERE i.conversationJid = m.conversationJid " + |
| 539 | "ORDER BY i.timestamp DESC, i.messageId DESC LIMIT 1) " + |
| 540 | "ORDER BY m.timestamp DESC, m.messageId DESC", |
| 541 | ) |
| 542 | suspend fun getLatestPerConversation(): List<WhatsAppCachedMessage> |
| 543 | |
| 544 | @Query("UPDATE whatsapp_cached_message SET body = :body, isEdited = 1 WHERE messageId = :messageId") |
| 545 | suspend fun markEdited(messageId: String, body: String) |
| 546 | |
| 547 | @Query("UPDATE whatsapp_cached_message SET isRevoked = 1, body = '' WHERE messageId = :messageId") |
| 548 | suspend fun markRevoked(messageId: String) |
| 549 | |
| 550 | @Query("UPDATE whatsapp_cached_message SET serviceData = :serviceData WHERE messageId = :messageId") |
| 551 | suspend fun updateServiceData(messageId: String, serviceData: String?) |
| 552 | |
| 553 | /** Advance to Delivered (2) only from a lower state (won't downgrade a Read message). */ |
| 554 | @Query("UPDATE whatsapp_cached_message SET status = 2 WHERE messageId = :messageId AND status < 2") |
| 555 | suspend fun markDelivered(messageId: String) |
| 556 | |
| 557 | /** Advance to Read (3) only from a lower state. */ |
| 558 | @Query("UPDATE whatsapp_cached_message SET status = 3 WHERE messageId = :messageId AND status < 3") |
| 559 | suspend fun markReadStatus(messageId: String) |
| 560 | |
| 561 | @Query("DELETE FROM whatsapp_cached_message WHERE conversationJid = :jid") |
| 562 | suspend fun deleteConversation(jid: String) |
| 563 | |
| 564 | @Query("DELETE FROM whatsapp_cached_message") |
| 565 | suspend fun deleteAll() |
| 566 | } |
| 567 | |
| 568 | /** A single reaction on a cached message (one row per reactor). */ |
| 569 | @Entity(tableName = "whatsapp_cached_reaction", primaryKeys = ["messageId", "senderJid"]) |
| 570 | data class WhatsAppCachedReaction( |
| 571 | val messageId: String, |
| 572 | val emoji: String, |
| 573 | val senderJid: String, |
| 574 | val timestamp: Long, |
| 575 | ) |
| 576 | |
| 577 | /** Queries for cached WhatsApp message reactions. */ |
| 578 | @Dao |
| 579 | interface WhatsAppCachedReactionDao { |
| 580 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 581 | suspend fun upsert(reaction: WhatsAppCachedReaction) |
| 582 | |
| 583 | @Query("SELECT * FROM whatsapp_cached_reaction WHERE messageId = :messageId") |
| 584 | suspend fun getForMessage(messageId: String): List<WhatsAppCachedReaction> |
| 585 | |
| 586 | @Query("DELETE FROM whatsapp_cached_reaction WHERE messageId = :messageId AND senderJid = :senderJid") |
| 587 | suspend fun remove(messageId: String, senderJid: String) |
| 588 | |
| 589 | @Query("DELETE FROM whatsapp_cached_reaction WHERE messageId = :messageId") |
| 590 | suspend fun clearForMessage(messageId: String) |
| 591 | } |
| 592 | |
| 593 | // -- communicate device-contact sync (address book → WhatsApp LID/phone mapping, Phase C 2f) -- |
| 594 | |
| 595 | /** |
| 596 | * A device address-book contact synced to WhatsApp. Keyed by the E.164 phone number; [lid] and |
| 597 | * [onWhatsApp] are filled in from `xwa2_primary_contacts_full_sync` / `xwa2_contact_discovery` |
| 598 | * results, [displayName] from the device contact name. |
| 599 | */ |
| 600 | @Entity(tableName = "whatsapp_contact") |
| 601 | data class WhatsAppContact( |
| 602 | @PrimaryKey val phoneE164: String, |
| 603 | val lid: String = "", |
| 604 | val displayName: String = "", |
| 605 | val onWhatsApp: Boolean = false, |
| 606 | val updatedAt: Long = 0L, |
| 607 | ) |
| 608 | |
| 609 | /** Queries for WhatsApp contacts. */ |
| 610 | @Dao |
| 611 | interface WhatsAppContactDao { |
| 612 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 613 | suspend fun upsert(contact: WhatsAppContact) |
| 614 | |
| 615 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 616 | suspend fun upsertAll(contacts: List<WhatsAppContact>) |
| 617 | |
| 618 | @Query("SELECT * FROM whatsapp_contact WHERE phoneE164 = :phoneE164 LIMIT 1") |
| 619 | suspend fun get(phoneE164: String): WhatsAppContact? |
| 620 | |
| 621 | @Query("SELECT * FROM whatsapp_contact WHERE lid = :lid LIMIT 1") |
| 622 | suspend fun getByLid(lid: String): WhatsAppContact? |
| 623 | |
| 624 | @Query("SELECT * FROM whatsapp_contact WHERE onWhatsApp = 1 ORDER BY displayName COLLATE NOCASE ASC") |
| 625 | suspend fun getOnWhatsApp(): List<WhatsAppContact> |
| 626 | |
| 627 | @Query("SELECT * FROM whatsapp_contact") |
| 628 | suspend fun getAll(): List<WhatsAppContact> |
| 629 | |
| 630 | @Query("DELETE FROM whatsapp_contact") |
| 631 | suspend fun deleteAll() |
| 632 | } |
| 633 | |
| 634 | // -- communicate call log (Phase D 3e) -- |
| 635 | |
| 636 | /** A completed/attempted WhatsApp call, keyed by call id. */ |
| 637 | @Entity(tableName = "whatsapp_call_log") |
| 638 | data class WhatsAppCallLog( |
| 639 | @PrimaryKey val callId: String, |
| 640 | val peerJid: String = "", |
| 641 | val peerName: String = "", |
| 642 | val outgoing: Boolean = false, |
| 643 | val video: Boolean = false, |
| 644 | val startTime: Long = 0L, |
| 645 | val durationSeconds: Long = 0L, |
| 646 | /** "answered" | "missed" | "rejected" | "failed" | reason string. */ |
| 647 | val outcome: String = "", |
| 648 | ) |
| 649 | |
| 650 | /** Queries for the WhatsApp call log. */ |
| 651 | @Dao |
| 652 | interface WhatsAppCallLogDao { |
| 653 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 654 | suspend fun upsert(entry: WhatsAppCallLog) |
| 655 | |
| 656 | @Query("SELECT * FROM whatsapp_call_log ORDER BY startTime DESC LIMIT :limit") |
| 657 | suspend fun getRecent(limit: Int = 200): List<WhatsAppCallLog> |
| 658 | |
| 659 | @Query("SELECT * FROM whatsapp_call_log WHERE callId = :callId LIMIT 1") |
| 660 | suspend fun get(callId: String): WhatsAppCallLog? |
| 661 | |
| 662 | @Query("DELETE FROM whatsapp_call_log") |
| 663 | suspend fun deleteAll() |
| 664 | } |