Skip to main content

vector_core/db/
chats.rs

1//! Chat database operations — CRUD for the chats table.
2
3use serde::{Deserialize, Serialize};
4
5use crate::chat::{Chat, ChatType, ChatMetadata};
6use crate::compact::{encode_message_id, decode_message_id, NpubInterner};
7use rusqlite::OptionalExtension;
8
9/// Slim version of Chat for database storage.
10#[derive(Serialize, Deserialize, Clone, Debug)]
11pub struct SlimChatDB {
12    pub id: String,
13    pub chat_type: ChatType,
14    pub participants: Vec<String>,
15    pub last_read: String,
16    #[serde(default)]
17    pub unread_from: String,
18    pub created_at: u64,
19    pub metadata: ChatMetadata,
20    pub muted: bool,
21    #[serde(default)]
22    pub wallpaper_path: String,
23    #[serde(default)]
24    pub wallpaper_ts: u64,
25    #[serde(default)]
26    pub wallpaper_blur: u8,
27    #[serde(default = "default_wallpaper_dim_slim")]
28    pub wallpaper_dim: u8,
29    #[serde(default)]
30    pub wallpaper_url: String,
31    #[serde(default)]
32    pub wallpaper_uploader: String,
33    /// Read-only: derived from the events at load, never written by a save.
34    #[serde(default)]
35    pub replied: bool,
36}
37
38fn default_wallpaper_dim_slim() -> u8 { 50 }
39
40impl SlimChatDB {
41    /// Create from a Chat, resolving interned handles to strings for DB storage.
42    pub fn from_chat(chat: &Chat, interner: &NpubInterner) -> Self {
43        SlimChatDB {
44            id: chat.id().clone(),
45            chat_type: chat.chat_type().clone(),
46            participants: chat.participants().iter()
47                .filter_map(|&h| interner.resolve(h).map(|s| s.to_string()))
48                .collect(),
49            last_read: if *chat.last_read() == [0u8; 32] {
50                String::new()
51            } else {
52                decode_message_id(chat.last_read())
53            },
54            unread_from: if chat.unread_from == [0u8; 32] {
55                String::new()
56            } else {
57                decode_message_id(&chat.unread_from)
58            },
59            created_at: chat.created_at(),
60            metadata: chat.metadata().clone(),
61            muted: chat.muted(),
62            wallpaper_path: chat.wallpaper_path.clone(),
63            wallpaper_ts: chat.wallpaper_ts,
64            wallpaper_blur: chat.wallpaper_blur,
65            wallpaper_dim: chat.wallpaper_dim,
66            wallpaper_url: chat.wallpaper_url.clone(),
67            wallpaper_uploader: chat.wallpaper_uploader.clone(),
68            replied: chat.replied,
69        }
70    }
71
72    /// Convert back to full Chat (messages loaded separately).
73    pub fn to_chat(&self, interner: &mut NpubInterner) -> Chat {
74        let mut handles: Vec<u16> = self.participants.iter().map(|p| interner.intern(p)).collect();
75        // Self-heal DM rows persisted as bare stubs (participants '[]'): the id IS
76        // the counterparty, and participant-keyed lookups need it present.
77        if handles.is_empty()
78            && matches!(self.chat_type, ChatType::DirectMessage)
79            && self.id.starts_with("npub1")
80        {
81            handles.push(interner.intern(&self.id));
82        }
83        let mut chat = Chat::new(self.id.clone(), self.chat_type.clone(), handles);
84        chat.last_read = if self.last_read.is_empty() {
85            [0u8; 32]
86        } else {
87            encode_message_id(&self.last_read)
88        };
89        chat.unread_from = if self.unread_from.is_empty() {
90            [0u8; 32]
91        } else {
92            encode_message_id(&self.unread_from)
93        };
94        chat.created_at = self.created_at;
95        chat.metadata = self.metadata.clone();
96        chat.muted = self.muted;
97        chat.wallpaper_path = self.wallpaper_path.clone();
98        chat.wallpaper_ts = self.wallpaper_ts;
99        chat.wallpaper_blur = self.wallpaper_blur;
100        chat.wallpaper_dim = self.wallpaper_dim;
101        chat.wallpaper_url = self.wallpaper_url.clone();
102        chat.wallpaper_uploader = self.wallpaper_uploader.clone();
103        chat.replied = self.replied;
104        chat
105    }
106}
107
108/// Get all chats from the database.
109pub fn get_all_chats() -> Result<Vec<SlimChatDB>, String> {
110    let conn = super::get_db_connection_guard_static()?;
111
112    // chat_type 1 was the removed MLS group variant — legacy rows are dropped at load.
113    let mut stmt = conn.prepare(
114        "SELECT chat_identifier, chat_type, participants, last_read, created_at, metadata, muted, \
115                wallpaper_path, wallpaper_ts, wallpaper_blur, wallpaper_dim, \
116                wallpaper_url, wallpaper_uploader, unread_from, \
117                CASE WHEN chat_type = 0 THEN EXISTS( \
118                    SELECT 1 FROM events e WHERE e.chat_id = chats.id AND e.kind IN (?1, ?2, ?3) AND e.mine = 1 \
119                ) ELSE 0 END \
120         FROM chats WHERE chat_type != 1 ORDER BY created_at DESC"
121    ).map_err(|e| format!("Failed to prepare statement: {}", e))?;
122
123    let kinds = rusqlite::params![
124        crate::stored_event::event_kind::CHAT_MESSAGE as i32,
125        crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE as i32,
126        crate::stored_event::event_kind::FILE_ATTACHMENT as i32,
127    ];
128    let rows = stmt.query_map(kinds, |row| {
129        let participants_json: String = row.get(2)?;
130        let participants: Vec<String> = serde_json::from_str(&participants_json).unwrap_or_default();
131
132        let metadata_json: String = row.get(5)?;
133        let metadata: ChatMetadata = serde_json::from_str(&metadata_json).unwrap_or_default();
134
135        let chat_type_int: i32 = row.get(1)?;
136        let chat_type = ChatType::from_i32(chat_type_int);
137
138        Ok(SlimChatDB {
139            id: row.get(0)?,
140            chat_type,
141            participants,
142            last_read: row.get(3)?,
143            unread_from: row.get(13)?,
144            created_at: row.get::<_, i64>(4)? as u64,
145            metadata,
146            muted: row.get::<_, i32>(6)? != 0,
147            wallpaper_path: row.get(7)?,
148            wallpaper_ts: row.get::<_, i64>(8)? as u64,
149            wallpaper_blur: row.get::<_, i32>(9)?.clamp(0, 30) as u8,
150            wallpaper_dim: row.get::<_, i32>(10)?.clamp(0, 100) as u8,
151            wallpaper_url: row.get(11)?,
152            wallpaper_uploader: row.get(12)?,
153            replied: row.get::<_, i32>(14)? != 0,
154        })
155    }).map_err(|e| format!("Failed to query chats: {}", e))?;
156
157    rows.collect::<Result<Vec<_>, _>>()
158        .map_err(|e| format!("Failed to collect chats: {}", e))
159}
160
161/// Keep a wallpaper rumor (sealed at rest) until its chat's request is accepted; only a
162/// newer one replaces it. Whether it was kept.
163pub fn hold_wallpaper(chat_identifier: &str, created_at: u64, payload: &str) -> Result<bool, String> {
164    /// Each row is one stranger's, so fabricated npubs could otherwise grow it without end.
165    const MAX_HELD: i64 = 200;
166    let _seal = crate::crypto::gate::sealing();
167    let conn = super::get_write_connection_guard_static()?;
168    let sealed = crate::crypto::maybe_encrypt_text(payload)?;
169    let n = conn.execute(
170        "INSERT INTO dm_held_wallpapers (chat_id, created_at, payload) VALUES (?1, ?2, ?3)
171         ON CONFLICT(chat_id) DO UPDATE SET created_at = excluded.created_at, payload = excluded.payload
172         WHERE excluded.created_at > dm_held_wallpapers.created_at",
173        rusqlite::params![chat_identifier, created_at as i64, sealed],
174    )
175    .map_err(|e| format!("hold_wallpaper: {e}"))?;
176    conn.execute(
177        "DELETE FROM dm_held_wallpapers WHERE chat_id NOT IN
178            (SELECT chat_id FROM dm_held_wallpapers ORDER BY created_at DESC LIMIT ?1)",
179        rusqlite::params![MAX_HELD],
180    )
181    .map_err(|e| format!("hold_wallpaper cap: {e}"))?;
182    Ok(n > 0)
183}
184
185/// The wallpaper held for this chat, removed as it's handed over.
186pub fn take_held_wallpaper(chat_identifier: &str) -> Result<Option<String>, String> {
187    let conn = super::get_write_connection_guard_static()?;
188    let payload: Option<String> = conn
189        .query_row(
190            "DELETE FROM dm_held_wallpapers WHERE chat_id = ?1 RETURNING payload",
191            rusqlite::params![chat_identifier],
192            |row| row.get(0),
193        )
194        .optional()
195        .map_err(|e| format!("take_held_wallpaper: {e}"))?;
196    Ok(payload.map(|p| crate::crypto::maybe_decrypt_text(&p)))
197}
198
199/// Withdraw a held wallpaper older than `created_at` (its sender since removed it).
200pub fn drop_held_wallpaper_before(chat_identifier: &str, created_at: u64) -> Result<(), String> {
201    let conn = super::get_write_connection_guard_static()?;
202    conn.execute(
203        "DELETE FROM dm_held_wallpapers WHERE chat_id = ?1 AND created_at < ?2",
204        rusqlite::params![chat_identifier, created_at as i64],
205    )
206    .map_err(|e| format!("drop_held_wallpaper_before: {e}"))?;
207    Ok(())
208}
209
210/// Upsert a chat to the database.
211/// Clear a chat's read marker to never-read. The [`save_slim_chat`] upsert
212/// deliberately refuses to regress `last_read` to empty (a partially-hydrated
213/// STATE chat would otherwise wipe the stored position), so a DELIBERATE
214/// clear — Mark as Unread on a chat whose only message is the target — must
215/// come through here or it silently no-ops.
216pub fn clear_chat_last_read(chat_identifier: &str) -> Result<(), String> {
217    let conn = super::get_write_connection_guard_static()?;
218    conn.execute(
219        "UPDATE chats SET last_read = '' WHERE chat_identifier = ?1",
220        rusqlite::params![chat_identifier],
221    )
222    .map_err(|e| format!("clear_chat_last_read: {e}"))?;
223    Ok(())
224}
225
226pub fn save_slim_chat(slim_chat: &SlimChatDB) -> Result<(), String> {
227    if slim_chat.id.is_empty() {
228        return Err("refusing to persist a chat with an empty identifier".into());
229    }
230    let conn = super::get_write_connection_guard_static()?;
231
232    let chat_type_int = slim_chat.chat_type.to_i32();
233    let participants_json = serde_json::to_string(&slim_chat.participants)
234        .unwrap_or_else(|_| "[]".to_string());
235    let metadata_json = serde_json::to_string(&slim_chat.metadata)
236        .unwrap_or_else(|_| "{}".to_string());
237
238    conn.execute(
239        // `last_read` never regresses to empty through a chat save: a STATE chat can
240        // predate marker hydration (realtime-created, partial boot), and persisting its
241        // empty marker would wipe the stored read position — resurrecting every message
242        // since as phantom unread. Marker clears go through the dedicated
243        // `UPDATE chats SET last_read` paths, not this upsert.
244        "INSERT INTO chats (chat_identifier, chat_type, participants, last_read, created_at, metadata, muted, wallpaper_path, wallpaper_ts, wallpaper_blur, wallpaper_dim, wallpaper_url, wallpaper_uploader, unread_from) \
245         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14) \
246         ON CONFLICT(chat_identifier) DO UPDATE SET \
247            chat_type = excluded.chat_type, participants = excluded.participants, \
248            last_read = CASE WHEN excluded.last_read = '' THEN chats.last_read ELSE excluded.last_read END, \
249            metadata = excluded.metadata, muted = excluded.muted, \
250            wallpaper_path = excluded.wallpaper_path, wallpaper_ts = excluded.wallpaper_ts, \
251            wallpaper_blur = excluded.wallpaper_blur, wallpaper_dim = excluded.wallpaper_dim, \
252            wallpaper_url = excluded.wallpaper_url, wallpaper_uploader = excluded.wallpaper_uploader, \
253            unread_from = excluded.unread_from",
254        rusqlite::params![
255            slim_chat.id,
256            chat_type_int,
257            participants_json,
258            slim_chat.last_read,
259            slim_chat.created_at as i64,
260            metadata_json,
261            slim_chat.muted as i32,
262            slim_chat.wallpaper_path,
263            slim_chat.wallpaper_ts as i64,
264            slim_chat.wallpaper_blur as i32,
265            slim_chat.wallpaper_dim as i32,
266            slim_chat.wallpaper_url,
267            slim_chat.wallpaper_uploader,
268            slim_chat.unread_from,
269        ],
270    ).map_err(|e| format!("Failed to upsert chat: {}", e))?;
271
272    Ok(())
273}
274
275/// Delete a chat and all its messages from the database. `chat_identifier` is the
276/// string id (npub for DMs, channel id for Communities) — NOT the integer PK.
277pub fn delete_chat(chat_identifier: &str) -> Result<(), String> {
278    let conn = super::get_write_connection_guard_static()?;
279    // Drop messages first (explicit, not reliant on the FK cascade pragma being on).
280    conn.execute(
281        "DELETE FROM events WHERE chat_id IN (SELECT id FROM chats WHERE chat_identifier = ?1)",
282        rusqlite::params![chat_identifier],
283    ).map_err(|e| format!("Failed to delete chat events: {}", e))?;
284    conn.execute(
285        "DELETE FROM chats WHERE chat_identifier = ?1",
286        rusqlite::params![chat_identifier],
287    ).map_err(|e| format!("Failed to delete chat: {}", e))?;
288    super::id_cache::forget_chat_id(chat_identifier);
289    Ok(())
290}
291
292#[cfg(test)]
293mod tests {
294    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(900);
295
296    fn make_test_npub(n: u32) -> String {
297        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
298        let mut payload = vec![b'q'; 58];
299        let mut x = n as u64;
300        let mut i = 58;
301        while x > 0 && i > 0 {
302            i -= 1;
303            payload[i] = BECH32[(x as usize) % 32];
304            x /= 32;
305        }
306        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
307    }
308
309    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
310        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
311        crate::db::close_database();
312        // Per-account row-id caches survive close_database; clear them so a stale entry from a prior
313        // test's DB can't point into this fresh account's DB and FK-fail an insert.
314        crate::db::clear_id_caches();
315        let tmp = tempfile::tempdir().unwrap();
316        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
317        let account = make_test_npub(n);
318        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
319        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
320        crate::db::set_current_account(account.clone()).unwrap();
321        crate::db::init_database(&account).unwrap();
322        (tmp, guard)
323    }
324
325    // A chat save carrying an EMPTY marker (a STATE chat that predates marker
326    // hydration) must not wipe the persisted read position — message persists
327    // re-save the chat row constantly, and a wipe resurrects every message
328    // since as phantom unread. A real marker still advances normally.
329    #[test]
330    fn chat_upsert_preserves_last_read_against_empty_marker() {
331        let (_tmp, _guard) = init_test_db();
332        let chat_id = "npub1markerkeeper";
333
334        let mut slim = super::SlimChatDB {
335            id: chat_id.to_string(),
336            chat_type: crate::ChatType::DirectMessage,
337            participants: vec![],
338            last_read: "aa".repeat(32),
339            unread_from: String::new(),
340            created_at: 1000,
341            metadata: crate::chat::ChatMetadata::default(),
342            muted: false,
343            wallpaper_path: String::new(),
344            wallpaper_ts: 0,
345            wallpaper_blur: 0,
346            wallpaper_dim: 50,
347            wallpaper_url: String::new(),
348            wallpaper_uploader: String::new(),
349            replied: false,
350        };
351        super::save_slim_chat(&slim).unwrap();
352
353        // Un-hydrated STATE copy re-saves the row: marker survives.
354        slim.last_read = String::new();
355        super::save_slim_chat(&slim).unwrap();
356        let chats = super::get_all_chats().unwrap();
357        let chat = chats.iter().find(|c| c.id == chat_id).expect("chat saved");
358        assert_eq!(chat.last_read, "aa".repeat(32), "empty marker must not wipe the stored one");
359
360        // A real marker still advances.
361        slim.last_read = "bb".repeat(32);
362        super::save_slim_chat(&slim).unwrap();
363        let chats = super::get_all_chats().unwrap();
364        let chat = chats.iter().find(|c| c.id == chat_id).expect("chat saved");
365        assert_eq!(chat.last_read, "bb".repeat(32), "non-empty marker advances normally");
366    }
367
368    // A DM is a request until we send in it; their messages alone, however many, don't
369    // answer it, and the flag comes from the events rather than the page we boot with.
370    #[tokio::test]
371    async fn a_dm_counts_as_replied_once_we_send_in_it() {
372        let (_tmp, _guard) = init_test_db();
373        let chat_id = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
374        let msg = |seed: u8, mine: bool| crate::types::Message {
375            id: format!("{:02x}", seed).repeat(32),
376            content: "hi".into(),
377            at: 1_700_000_000_000 + seed as u64,
378            mine,
379            npub: Some(chat_id.clone()),
380            ..Default::default()
381        };
382        let replied = || super::get_all_chats().unwrap().into_iter().find(|c| c.id == chat_id).expect("chat saved").replied;
383
384        for seed in 1..=3 {
385            crate::db::events::save_message(&chat_id, &msg(seed, false)).await.unwrap();
386        }
387        assert!(!replied(), "only their messages: still a request");
388
389        crate::db::events::save_message(&chat_id, &msg(4, true)).await.unwrap();
390        assert!(replied(), "one of ours answers it");
391    }
392
393    // Only a newer wallpaper replaces a held one, a removal withdraws an older one, and
394    // handing it over empties the slot.
395    #[test]
396    fn a_held_wallpaper_keeps_the_newest_until_taken() {
397        let (_tmp, _guard) = init_test_db();
398        let chat = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
399        assert!(super::hold_wallpaper(&chat, 10, "ten").unwrap());
400        assert!(!super::hold_wallpaper(&chat, 5, "five").unwrap(), "an older one never replaces it");
401        assert!(super::hold_wallpaper(&chat, 20, "twenty").unwrap());
402
403        super::drop_held_wallpaper_before(&chat, 15).unwrap();
404        assert_eq!(super::take_held_wallpaper(&chat).unwrap().as_deref(), Some("twenty"), "a removal older than it leaves it");
405        assert_eq!(super::take_held_wallpaper(&chat).unwrap(), None, "taken once");
406
407        super::hold_wallpaper(&chat, 30, "thirty").unwrap();
408        super::drop_held_wallpaper_before(&chat, 40).unwrap();
409        assert_eq!(super::take_held_wallpaper(&chat).unwrap(), None, "a newer removal withdraws it");
410    }
411
412    // Regression: a non-npub id stub-created via get_or_create_chat_id must use the
413    // Community discriminant (2), not the retired MLS value (1) which get_all_chats
414    // drops — otherwise the chat (and its messages) vanish on the next reload.
415    #[test]
416    fn stub_created_non_npub_chat_survives_reload() {
417        let (_tmp, _guard) = init_test_db();
418        let channel_id = "abc123def456channelid";
419        let _ = crate::db::id_cache::get_or_create_chat_id(channel_id).unwrap();
420
421        let chats = super::get_all_chats().unwrap();
422        let found = chats.iter().find(|c| c.id == channel_id)
423            .expect("stub-created non-npub chat must survive get_all_chats");
424        assert_eq!(found.chat_type, crate::ChatType::Community);
425    }
426
427    // Regression: a DM row stub-created by a message save (no prior chat row) must carry
428    // its counterparty — a bare '[]' roster boots into STATE participant-less, and every
429    // participant-keyed lookup (attachment downloads) misses forever after.
430    #[test]
431    fn stub_created_dm_chat_carries_its_counterparty() {
432        let (_tmp, _guard) = init_test_db();
433        let npub = "npub1stubcounterparty";
434        let _ = crate::db::id_cache::get_or_create_chat_id(npub).unwrap();
435
436        let chats = super::get_all_chats().unwrap();
437        let found = chats.iter().find(|c| c.id == npub).expect("stub DM row exists");
438        assert_eq!(found.chat_type, crate::ChatType::DirectMessage);
439        assert_eq!(found.participants, vec![npub.to_string()], "the DM's id IS its participant");
440    }
441
442    // Rows already persisted with an empty roster (pre-fix stubs) heal at load: the id
443    // is the counterparty, so to_chat re-derives it.
444    #[test]
445    fn to_chat_heals_bare_dm_participants() {
446        let slim = super::SlimChatDB {
447            id: "npub1baredmrow".to_string(),
448            chat_type: crate::ChatType::DirectMessage,
449            participants: vec![],
450            last_read: String::new(),
451            unread_from: String::new(),
452            created_at: 1000,
453            metadata: crate::chat::ChatMetadata::default(),
454            muted: false,
455            wallpaper_path: String::new(),
456            wallpaper_ts: 0,
457            wallpaper_blur: 0,
458            wallpaper_dim: 50,
459            wallpaper_url: String::new(),
460            wallpaper_uploader: String::new(),
461            replied: false,
462        };
463        let mut interner = crate::compact::NpubInterner::new();
464        let chat = slim.to_chat(&mut interner);
465        assert!(chat.has_participant("npub1baredmrow", &interner), "bare DM roster heals from the id");
466
467        // A community row with no participants stays empty — only DMs derive from the id.
468        let mut community = slim.clone();
469        community.id = "aabbccddeeff00".to_string();
470        community.chat_type = crate::ChatType::Community;
471        let chat = community.to_chat(&mut interner);
472        assert!(chat.participants().is_empty(), "non-DM rosters are not invented");
473    }
474}