| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use rusqlite::{Row, params}; |
| 5 | |
| 6 | use crate::error::Result; |
| 7 | use crate::models::{ChatPreview, ChatRecord, MemberRecord}; |
| 8 | use crate::store::{Store, json_ids}; |
| 9 | use crate::time::{optional_from_millis, optional_to_millis, to_millis}; |
| 10 | |
| 11 | const CHAT_COLUMNS: &str = "id, kind, title, member_summary, last_message_at, last_read_at, unread, \ |
| 12 | last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted"; |
| 13 | |
| 14 | impl Store { |
| 15 | pub fn upsert_chats(&self, chats: &[ChatRecord]) -> Result<()> { |
| 16 | let mut connection = self.lock()?; |
| 17 | let transaction = connection.transaction()?; |
| 18 | { |
| 19 | let mut upsert = transaction.prepare_cached( |
| 20 | "INSERT INTO chats (id, kind, title, member_summary, last_message_at, last_read_at, unread, |
| 21 | last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted) |
| 22 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) |
| 23 | ON CONFLICT (id) DO UPDATE SET |
| 24 | kind = excluded.kind, title = excluded.title, member_summary = excluded.member_summary, |
| 25 | last_message_at = excluded.last_message_at, last_read_at = excluded.last_read_at, |
| 26 | unread = excluded.unread, last_message_preview = excluded.last_message_preview, |
| 27 | last_message_sender_id = excluded.last_message_sender_id, |
| 28 | last_message_sender_name = excluded.last_message_sender_name, |
| 29 | last_message_deleted = excluded.last_message_deleted", |
| 30 | )?; |
| 31 | let mut clear_members = |
| 32 | transaction.prepare_cached("DELETE FROM chat_members WHERE chat_id = ?1")?; |
| 33 | let mut insert_member = transaction.prepare_cached( |
| 34 | "INSERT INTO chat_members (chat_id, position, user_id, display_name) VALUES (?1, ?2, ?3, ?4)", |
| 35 | )?; |
| 36 | for chat in chats { |
| 37 | upsert.execute(params![ |
| 38 | chat.id, |
| 39 | chat.kind, |
| 40 | chat.title, |
| 41 | chat.member_summary, |
| 42 | optional_to_millis(chat.last_message_at), |
| 43 | optional_to_millis(chat.last_read_at), |
| 44 | chat.unread, |
| 45 | chat.last_message_preview, |
| 46 | chat.last_message_sender_id, |
| 47 | chat.last_message_sender_name, |
| 48 | chat.last_message_deleted, |
| 49 | ])?; |
| 50 | clear_members.execute([&chat.id])?; |
| 51 | for (position, member) in chat.members.iter().enumerate() { |
| 52 | insert_member.execute(params![ |
| 53 | chat.id, |
| 54 | position as i64, |
| 55 | member.user_id, |
| 56 | member.display_name |
| 57 | ])?; |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | Ok(transaction.commit()?) |
| 62 | } |
| 63 | |
| 64 | pub fn chat_last_message_times( |
| 65 | &self, |
| 66 | chat_ids: &[String], |
| 67 | ) -> Result<HashMap<String, Option<DateTime<Utc>>>> { |
| 68 | let connection = self.lock()?; |
| 69 | let mut statement = connection.prepare_cached( |
| 70 | "SELECT id, last_message_at FROM chats WHERE id IN (SELECT value FROM json_each(?1))", |
| 71 | )?; |
| 72 | let rows = statement.query_map([json_ids(chat_ids)], |row| { |
| 73 | Ok((row.get::<_, String>(0)?, optional_from_millis(row.get(1)?))) |
| 74 | })?; |
| 75 | Ok(rows.collect::<rusqlite::Result<_>>()?) |
| 76 | } |
| 77 | |
| 78 | pub fn chat_count(&self) -> Result<usize> { |
| 79 | let connection = self.lock()?; |
| 80 | let count: i64 = |
| 81 | connection.query_row("SELECT COUNT(*) FROM chats", [], |row| row.get(0))?; |
| 82 | Ok(count as usize) |
| 83 | } |
| 84 | |
| 85 | pub fn remove_chats(&self, chat_ids: &[String]) -> Result<usize> { |
| 86 | let connection = self.lock()?; |
| 87 | Ok(connection.execute( |
| 88 | "DELETE FROM chats WHERE id IN (SELECT value FROM json_each(?1))", |
| 89 | [json_ids(chat_ids)], |
| 90 | )?) |
| 91 | } |
| 92 | |
| 93 | pub fn remove_chats_except(&self, kept_chat_ids: &[String]) -> Result<usize> { |
| 94 | let connection = self.lock()?; |
| 95 | Ok(connection.execute( |
| 96 | "DELETE FROM chats WHERE id NOT IN (SELECT value FROM json_each(?1))", |
| 97 | [json_ids(kept_chat_ids)], |
| 98 | )?) |
| 99 | } |
| 100 | |
| 101 | pub fn mark_chat_read(&self, chat_id: &str, read_at: DateTime<Utc>) -> Result<()> { |
| 102 | let connection = self.lock()?; |
| 103 | connection.execute( |
| 104 | "UPDATE chats SET unread = 0, last_read_at = ?2 WHERE id = ?1", |
| 105 | params![chat_id, to_millis(read_at)], |
| 106 | )?; |
| 107 | Ok(()) |
| 108 | } |
| 109 | |
| 110 | /// Applies the preview only when the message is at least as new as the cached last message and differs. Returns whether the row changed. |
| 111 | pub fn update_chat_preview( |
| 112 | &self, |
| 113 | chat_id: &str, |
| 114 | message_at: DateTime<Utc>, |
| 115 | preview: &ChatPreview<'_>, |
| 116 | ) -> Result<bool> { |
| 117 | let connection = self.lock()?; |
| 118 | let changed = connection.execute( |
| 119 | "UPDATE chats SET last_message_at = ?2, last_message_preview = ?3, last_message_sender_id = ?4, |
| 120 | last_message_sender_name = ?5, last_message_deleted = ?6 |
| 121 | WHERE id = ?1 AND (last_message_at IS NULL OR last_message_at <= ?2) |
| 122 | AND (last_message_at IS NOT ?2 OR last_message_preview IS NOT ?3 OR last_message_sender_id IS NOT ?4 |
| 123 | OR last_message_sender_name IS NOT ?5 OR last_message_deleted IS NOT ?6)", |
| 124 | params![ |
| 125 | chat_id, |
| 126 | to_millis(message_at), |
| 127 | preview.text, |
| 128 | preview.sender_id, |
| 129 | preview.sender_name, |
| 130 | preview.deleted |
| 131 | ], |
| 132 | )?; |
| 133 | Ok(changed > 0) |
| 134 | } |
| 135 | |
| 136 | pub fn recent_chats(&self, limit: usize) -> Result<Vec<ChatRecord>> { |
| 137 | let connection = self.lock()?; |
| 138 | let mut statement = connection.prepare_cached(&format!( |
| 139 | "SELECT {CHAT_COLUMNS} FROM chats ORDER BY last_message_at IS NULL, last_message_at DESC, id LIMIT ?1" |
| 140 | ))?; |
| 141 | let mut chats = statement |
| 142 | .query_map([limit as i64], chat_from_row)? |
| 143 | .collect::<rusqlite::Result<Vec<_>>>()?; |
| 144 | load_members(&connection, &mut chats)?; |
| 145 | Ok(chats) |
| 146 | } |
| 147 | |
| 148 | pub fn chat(&self, chat_id: &str) -> Result<Option<ChatRecord>> { |
| 149 | let connection = self.lock()?; |
| 150 | let mut statement = connection |
| 151 | .prepare_cached(&format!("SELECT {CHAT_COLUMNS} FROM chats WHERE id = ?1"))?; |
| 152 | let mut chats = statement |
| 153 | .query_map([chat_id], chat_from_row)? |
| 154 | .collect::<rusqlite::Result<Vec<_>>>()?; |
| 155 | load_members(&connection, &mut chats)?; |
| 156 | Ok(chats.pop()) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> { |
| 161 | Ok(ChatRecord { |
| 162 | id: row.get(0)?, |
| 163 | kind: row.get(1)?, |
| 164 | title: row.get(2)?, |
| 165 | member_summary: row.get(3)?, |
| 166 | last_message_at: optional_from_millis(row.get(4)?), |
| 167 | last_read_at: optional_from_millis(row.get(5)?), |
| 168 | unread: row.get(6)?, |
| 169 | members: Vec::new(), |
| 170 | last_message_preview: row.get(7)?, |
| 171 | last_message_sender_id: row.get(8)?, |
| 172 | last_message_sender_name: row.get(9)?, |
| 173 | last_message_deleted: row.get(10)?, |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | fn load_members(connection: &rusqlite::Connection, chats: &mut [ChatRecord]) -> Result<()> { |
| 178 | let mut statement = connection.prepare_cached( |
| 179 | "SELECT user_id, display_name FROM chat_members WHERE chat_id = ?1 ORDER BY position", |
| 180 | )?; |
| 181 | for chat in chats { |
| 182 | chat.members = statement |
| 183 | .query_map([&chat.id], |row| { |
| 184 | Ok(MemberRecord { |
| 185 | user_id: row.get(0)?, |
| 186 | display_name: row.get(1)?, |
| 187 | }) |
| 188 | })? |
| 189 | .collect::<rusqlite::Result<Vec<_>>>()?; |
| 190 | } |
| 191 | Ok(()) |
| 192 | } |