Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsDatabase.kt
RcsDatabase.kt376 lines · 14.2 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import androidx.room3.ColumnTypeConverter |
| 5 | import androidx.room3.ColumnTypeConverters |
| 6 | import androidx.room3.Dao |
| 7 | import androidx.room3.Database |
| 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.sqlite.SQLiteConnection |
| 16 | import androidx.sqlite.execSQL |
| 17 | import com.vayunmathur.library.room.RoomRepository |
| 18 | import com.vayunmathur.library.util.DatabaseMigrations |
| 19 | |
| 20 | /** |
| 21 | * Room database for RCS-specific data. Mirrors |
| 22 | * [com.vayunmathur.communicate.data.signal.SignalDatabase] but for the |
| 23 | * single-registration line: conversations + cached messages with file-transfer |
| 24 | * metadata. Version 1, no migrations. |
| 25 | */ |
| 26 | @Database( |
| 27 | entities = [ |
| 28 | RcsConversation::class, |
| 29 | RcsCachedMessage::class, |
| 30 | RcsMlsIdentity::class, |
| 31 | RcsMlsGroup::class, |
| 32 | RcsOutboxMessage::class, |
| 33 | ], |
| 34 | version = 4, |
| 35 | exportSchema = true, |
| 36 | ) |
| 37 | @ColumnTypeConverters(RcsTypeConverters::class) |
| 38 | abstract class RcsDatabase : RoomDatabase() { |
| 39 | abstract fun conversationDao(): RcsConversationDao |
| 40 | abstract fun cachedMessageDao(): RcsCachedMessageDao |
| 41 | abstract fun mlsIdentityDao(): RcsMlsIdentityDao |
| 42 | abstract fun mlsGroupDao(): RcsMlsGroupDao |
| 43 | abstract fun outboxDao(): RcsOutboxDao |
| 44 | |
| 45 | /** Schema migrations and the singleton accessor for [RcsDatabase]. */ |
| 46 | companion object : DatabaseMigrations { |
| 47 | /** |
| 48 | * v1 → v2: MLS E2EE tables (identity + group state). New tables only, |
| 49 | * nothing to backfill. |
| 50 | */ |
| 51 | private val MIGRATION_1_2 = object : androidx.room3.migration.Migration(1, 2) { |
| 52 | override suspend fun migrate(connection: androidx.sqlite.SQLiteConnection) { |
| 53 | connection.execSQL( |
| 54 | "CREATE TABLE IF NOT EXISTS `rcs_mls_identity` (" + |
| 55 | "`e164` TEXT NOT NULL, `identity` BLOB NOT NULL, " + |
| 56 | "`updatedAt` INTEGER NOT NULL, " + |
| 57 | "PRIMARY KEY(`e164`))", |
| 58 | ) |
| 59 | connection.execSQL( |
| 60 | "CREATE TABLE IF NOT EXISTS `rcs_mls_group` (" + |
| 61 | "`groupIdHex` TEXT NOT NULL, `conversationId` TEXT NOT NULL, " + |
| 62 | "`storage` BLOB NOT NULL, `updatedAt` INTEGER NOT NULL, " + |
| 63 | "PRIMARY KEY(`groupIdHex`))", |
| 64 | ) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * v2 → v3: display-receipt correlation (`imdnId` on cached rows), |
| 70 | * deferred-delivery outbox, identity verification flag, MLS member |
| 71 | * leaf-index tracking. Additive only; existing rows get defaults. |
| 72 | */ |
| 73 | private val MIGRATION_2_3 = object : androidx.room3.migration.Migration(2, 3) { |
| 74 | override suspend fun migrate(connection: androidx.sqlite.SQLiteConnection) { |
| 75 | connection.execSQL( |
| 76 | "ALTER TABLE `rcs_cached_message` ADD COLUMN `imdnId` TEXT NOT NULL DEFAULT ''", |
| 77 | ) |
| 78 | connection.execSQL( |
| 79 | "ALTER TABLE `rcs_mls_identity` ADD COLUMN `verified` INTEGER NOT NULL DEFAULT 0", |
| 80 | ) |
| 81 | connection.execSQL( |
| 82 | "ALTER TABLE `rcs_mls_group` ADD COLUMN `members` TEXT NOT NULL DEFAULT ''", |
| 83 | ) |
| 84 | connection.execSQL( |
| 85 | "CREATE TABLE IF NOT EXISTS `rcs_outbox` (" + |
| 86 | "`messageId` TEXT NOT NULL, `conversationId` TEXT NOT NULL, " + |
| 87 | "`kind` TEXT NOT NULL, `body` TEXT NOT NULL, " + |
| 88 | "`attachments` TEXT NOT NULL, `attempts` INTEGER NOT NULL, " + |
| 89 | "`nextRetryMs` INTEGER NOT NULL, `expiryMs` INTEGER NOT NULL, " + |
| 90 | "`createdAt` INTEGER NOT NULL, " + |
| 91 | "PRIMARY KEY(`messageId`))", |
| 92 | ) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /** v3 → v4: (conversationId, timestamp) index for keyset conversation windows. */ |
| 97 | private val MIGRATION_3_4 = object : androidx.room3.migration.Migration(3, 4) { |
| 98 | override suspend fun migrate(connection: androidx.sqlite.SQLiteConnection) { |
| 99 | connection.execSQL( |
| 100 | "CREATE INDEX IF NOT EXISTS `index_rcs_cached_message_conversationId_timestamp` " + |
| 101 | "ON `rcs_cached_message` (`conversationId`, `timestamp`)", |
| 102 | ) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | override val migrations = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) |
| 107 | |
| 108 | /** |
| 109 | * Test seam: when set, [getDatabase] returns this instance instead |
| 110 | * of the SQLCipher-backed singleton (whose native library cannot |
| 111 | * load on a JVM test host). Production code never sets it. |
| 112 | */ |
| 113 | @Volatile |
| 114 | var overrideForTest: RcsDatabase? = null |
| 115 | |
| 116 | fun getDatabase(context: Context): RcsDatabase = |
| 117 | overrideForTest ?: RcsRepository.get(context).database() |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Single owner of [RcsDatabase] (communicate_rcs.db). |
| 123 | * |
| 124 | * Mirrors [com.vayunmathur.communicate.data.signal.SignalRepository]: the |
| 125 | * single `buildDatabase` call site lives here (via [RoomRepository.db]). |
| 126 | */ |
| 127 | class RcsRepository private constructor(context: Context) : |
| 128 | RoomRepository<RcsDatabase>(context, RcsDatabase::class, "communicate_rcs.db") { |
| 129 | |
| 130 | /** Direct database access; prefer suspend wrappers for new code. */ |
| 131 | fun database(): RcsDatabase = db |
| 132 | |
| 133 | /** The singleton [RcsRepository] instance holder. */ |
| 134 | companion object { |
| 135 | @Volatile |
| 136 | private var instance: RcsRepository? = null |
| 137 | |
| 138 | fun get(context: Context): RcsRepository = |
| 139 | instance ?: synchronized(this) { |
| 140 | instance ?: RcsRepository(context).also { instance = it } |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /** Room column converters for RCS entities; string lists are stored as CSV. */ |
| 146 | class RcsTypeConverters { |
| 147 | @ColumnTypeConverter |
| 148 | fun fromStringList(value: List<String>): String = value.joinToString(",") |
| 149 | |
| 150 | @ColumnTypeConverter |
| 151 | fun toStringList(value: String): List<String> = |
| 152 | if (value.isEmpty()) emptyList() else value.split(",") |
| 153 | } |
| 154 | |
| 155 | // -- Conversation -- |
| 156 | |
| 157 | /** An RCS conversation row: a 1:1 peer (E.164) or a group conference URI. */ |
| 158 | @Entity(tableName = "rcs_conversation") |
| 159 | data class RcsConversation( |
| 160 | /** E.164 for 1:1, conference URI for groups. */ |
| 161 | @PrimaryKey val remoteId: String, |
| 162 | val isGroup: Boolean = false, |
| 163 | /** Group subject when known. */ |
| 164 | val name: String? = null, |
| 165 | /** CSV of participant addresses for groups. */ |
| 166 | val participants: String = "", |
| 167 | val unreadCount: Int = 0, |
| 168 | val lastMessageTimestamp: Long = 0L, |
| 169 | ) |
| 170 | |
| 171 | /** Queries for RCS conversations. */ |
| 172 | @Dao |
| 173 | interface RcsConversationDao { |
| 174 | @Query("SELECT * FROM rcs_conversation WHERE remoteId = :remoteId") |
| 175 | suspend fun getConversation(remoteId: String): RcsConversation? |
| 176 | |
| 177 | @Query("SELECT * FROM rcs_conversation ORDER BY lastMessageTimestamp DESC LIMIT :limit") |
| 178 | suspend fun getRecent(limit: Int): List<RcsConversation> |
| 179 | |
| 180 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 181 | suspend fun upsert(conversation: RcsConversation) |
| 182 | |
| 183 | @Query("DELETE FROM rcs_conversation WHERE remoteId = :remoteId") |
| 184 | suspend fun delete(remoteId: String) |
| 185 | |
| 186 | @Query("DELETE FROM rcs_conversation") |
| 187 | suspend fun deleteAll() |
| 188 | } |
| 189 | |
| 190 | // -- Cached messages -- |
| 191 | /** A cached RCS message row, including file-transfer and delivery state. */ |
| 192 | @Entity(tableName = "rcs_cached_message", indices = [Index(value = ["conversationId", "timestamp"])]) |
| 193 | data class RcsCachedMessage( |
| 194 | @PrimaryKey val messageId: String, |
| 195 | val conversationId: String, |
| 196 | val body: String, |
| 197 | val timestamp: Long, |
| 198 | val outgoing: Boolean, |
| 199 | /** Sender address for inbound group messages. */ |
| 200 | val senderId: String = "", |
| 201 | /** File-transfer metadata (populated by RcsFileTransfer). */ |
| 202 | val ftUrl: String? = null, |
| 203 | val ftMime: String? = null, |
| 204 | /** Outgoing delivery status ordinal (MessageStatus ordinal). */ |
| 205 | val status: Int = 0, |
| 206 | /** |
| 207 | * Inbound `imdn.Message-ID` for this row (outbound rows carry their own |
| 208 | * id in [messageId]; inbound rows store the sender's id here so |
| 209 | * display/read reports can reference it, §4.2). |
| 210 | */ |
| 211 | val imdnId: String = "", |
| 212 | ) |
| 213 | |
| 214 | /** Queries for cached RCS messages. */ |
| 215 | @Dao |
| 216 | interface RcsCachedMessageDao { |
| 217 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 218 | suspend fun upsert(message: RcsCachedMessage) |
| 219 | |
| 220 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 221 | suspend fun upsertAll(messages: List<RcsCachedMessage>) |
| 222 | |
| 223 | @Query("SELECT * FROM rcs_cached_message WHERE conversationId = :id ORDER BY timestamp ASC") |
| 224 | suspend fun getForConversation(id: String): List<RcsCachedMessage> |
| 225 | |
| 226 | /** Keyset window: newest [limit] before [before], newest first (reverse to render). */ |
| 227 | @Query( |
| 228 | "SELECT * FROM rcs_cached_message WHERE conversationId = :id AND timestamp < :before " + |
| 229 | "ORDER BY timestamp DESC LIMIT :limit", |
| 230 | ) |
| 231 | suspend fun getForConversationBefore( |
| 232 | id: String, |
| 233 | before: Long = Long.MAX_VALUE, |
| 234 | limit: Int = 100, |
| 235 | ): List<RcsCachedMessage> |
| 236 | |
| 237 | @Query("SELECT * FROM rcs_cached_message WHERE messageId = :messageId LIMIT 1") |
| 238 | suspend fun get(messageId: String): RcsCachedMessage? |
| 239 | |
| 240 | /** Most-recent message per conversation, newest first (for the thread list). */ |
| 241 | @Query( |
| 242 | "SELECT * FROM rcs_cached_message AS m WHERE m.messageId = " + |
| 243 | "(SELECT i.messageId FROM rcs_cached_message AS i " + |
| 244 | "WHERE i.conversationId = m.conversationId " + |
| 245 | "ORDER BY i.timestamp DESC, i.messageId DESC LIMIT 1) " + |
| 246 | "ORDER BY m.timestamp DESC, m.messageId DESC", |
| 247 | ) |
| 248 | suspend fun getLatestPerConversation(): List<RcsCachedMessage> |
| 249 | |
| 250 | /** Advance to Delivered (2) only from a lower state. */ |
| 251 | @Query("UPDATE rcs_cached_message SET status = 2 WHERE messageId = :messageId AND status < 2") |
| 252 | suspend fun markDelivered(messageId: String) |
| 253 | |
| 254 | /** Advance to Read (3) only from a lower state. */ |
| 255 | @Query("UPDATE rcs_cached_message SET status = 3 WHERE messageId = :messageId AND status < 3") |
| 256 | suspend fun markReadStatus(messageId: String) |
| 257 | |
| 258 | @Query("DELETE FROM rcs_cached_message WHERE conversationId = :id") |
| 259 | suspend fun deleteConversation(id: String) |
| 260 | |
| 261 | @Query("DELETE FROM rcs_cached_message") |
| 262 | suspend fun deleteAll() |
| 263 | } |
| 264 | |
| 265 | // -- MLS E2EE (closed-loop, our-app-to-our-app) -- |
| 266 | |
| 267 | /** |
| 268 | * Our MLS identity for one local E.164: serialized `IdentityState` |
| 269 | * (Ed25519 keypair + identity string) from the `communicate_mls` crate. |
| 270 | */ |
| 271 | @Entity(tableName = "rcs_mls_identity") |
| 272 | data class RcsMlsIdentity( |
| 273 | @PrimaryKey val e164: String, |
| 274 | val identity: ByteArray, |
| 275 | val updatedAt: Long = 0L, |
| 276 | /** User-verified safety number (§5.4). Unverified by default. */ |
| 277 | val verified: Boolean = false, |
| 278 | ) |
| 279 | |
| 280 | /** |
| 281 | * One MLS group, keyed by hex-encoded MLS group id bytes. [storage] is the |
| 282 | * opaque provider snapshot the crate needs on every call; [conversationId] |
| 283 | * maps back to the RCS thread. [members] tracks E.164 → leaf index |
| 284 | * (`e164=index` CSV) for member removal (§5.2). |
| 285 | */ |
| 286 | @Entity(tableName = "rcs_mls_group") |
| 287 | data class RcsMlsGroup( |
| 288 | /** Hex of the MLS group id (BLOB PKs are unreliable in Room). */ |
| 289 | @PrimaryKey val groupIdHex: String, |
| 290 | val conversationId: String, |
| 291 | val storage: ByteArray, |
| 292 | val updatedAt: Long = 0L, |
| 293 | val members: String = "", |
| 294 | ) |
| 295 | |
| 296 | /** Queries for our RCS MLS identity (credential and key package state). */ |
| 297 | @Dao |
| 298 | interface RcsMlsIdentityDao { |
| 299 | @Query("SELECT * FROM rcs_mls_identity WHERE e164 = :e164 LIMIT 1") |
| 300 | suspend fun get(e164: String): RcsMlsIdentity? |
| 301 | |
| 302 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 303 | suspend fun upsert(identity: RcsMlsIdentity) |
| 304 | |
| 305 | @Query("DELETE FROM rcs_mls_identity WHERE e164 = :e164") |
| 306 | suspend fun delete(e164: String) |
| 307 | } |
| 308 | |
| 309 | /** Queries for RCS MLS group state. */ |
| 310 | @Dao |
| 311 | interface RcsMlsGroupDao { |
| 312 | @Query("SELECT * FROM rcs_mls_group WHERE groupIdHex = :groupIdHex LIMIT 1") |
| 313 | suspend fun get(groupIdHex: String): RcsMlsGroup? |
| 314 | |
| 315 | @Query("SELECT * FROM rcs_mls_group WHERE conversationId = :conversationId LIMIT 1") |
| 316 | suspend fun getByConversation(conversationId: String): RcsMlsGroup? |
| 317 | |
| 318 | /** The pending key-package snapshot (see RcsE2E.freshKeyPackage). */ |
| 319 | @Query("SELECT * FROM rcs_mls_group WHERE groupIdHex LIKE 'pending:%' ORDER BY updatedAt DESC LIMIT 1") |
| 320 | suspend fun getPending(): RcsMlsGroup? |
| 321 | |
| 322 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 323 | suspend fun upsert(group: RcsMlsGroup) |
| 324 | |
| 325 | @Query("DELETE FROM rcs_mls_group WHERE groupIdHex = :groupIdHex") |
| 326 | suspend fun delete(groupIdHex: String) |
| 327 | |
| 328 | @Query("DELETE FROM rcs_mls_group WHERE conversationId = :conversationId") |
| 329 | suspend fun deleteByConversation(conversationId: String) |
| 330 | } |
| 331 | |
| 332 | // -- Deferred-delivery outbox (§4.3) -- |
| 333 | |
| 334 | /** |
| 335 | * A message that failed to send and waits for retry: pager text, FT |
| 336 | * reference, or group fan-out remainder. [kind] is `text` / `file` / `group`; |
| 337 | * [body] carries the text (or caption); [attachments] the content URIs CSV |
| 338 | * for files. Retried with backoff until [expiryMs], then marked failed. |
| 339 | */ |
| 340 | @Entity(tableName = "rcs_outbox") |
| 341 | data class RcsOutboxMessage( |
| 342 | @PrimaryKey val messageId: String, |
| 343 | val conversationId: String, |
| 344 | val kind: String, |
| 345 | val body: String, |
| 346 | val attachments: String = "", |
| 347 | val attempts: Int = 0, |
| 348 | val nextRetryMs: Long, |
| 349 | val expiryMs: Long, |
| 350 | val createdAt: Long = 0L, |
| 351 | ) |
| 352 | |
| 353 | /** Queries for the RCS outbox (messages queued while offline/unregistered). */ |
| 354 | @Dao |
| 355 | interface RcsOutboxDao { |
| 356 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 357 | suspend fun upsert(message: RcsOutboxMessage) |
| 358 | |
| 359 | @Query("SELECT * FROM rcs_outbox WHERE nextRetryMs <= :nowMs ORDER BY nextRetryMs ASC LIMIT :limit") |
| 360 | suspend fun dueForRetry(nowMs: Long, limit: Int = 20): List<RcsOutboxMessage> |
| 361 | |
| 362 | @Query("SELECT * FROM rcs_outbox WHERE messageId = :messageId LIMIT 1") |
| 363 | suspend fun get(messageId: String): RcsOutboxMessage? |
| 364 | |
| 365 | @Query("DELETE FROM rcs_outbox WHERE messageId = :messageId") |
| 366 | suspend fun delete(messageId: String) |
| 367 | |
| 368 | @Query("DELETE FROM rcs_outbox WHERE conversationId = :conversationId") |
| 369 | suspend fun deleteConversation(conversationId: String) |
| 370 | |
| 371 | @Query("DELETE FROM rcs_outbox") |
| 372 | suspend fun deleteAll() |
| 373 | |
| 374 | @Query("SELECT COUNT(*) FROM rcs_outbox") |
| 375 | suspend fun count(): Int |
| 376 | } |