BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / chats.rs

chats.rs

chats.rs 10.6 KiB Download Raw
1use std::collections::HashMap;
2
3use chrono::{DateTime, Utc};
4use rusqlite::{Row, params};
5
6use crate::error::Result;
7use crate::models::{ChatPreview, ChatRecord, MemberRecord};
8use crate::store::{Store, json_ids};
9use crate::time::{optional_from_millis, optional_to_millis, to_millis};
10
11const 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, muted, preview_at";
13
14impl 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, preview_at)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?14)
23 ON CONFLICT (id) DO UPDATE SET
24 kind = excluded.kind,
25 title = CASE WHEN excluded.title IN ('(only you)', 'Unknown User') AND chats.title NOT IN ('', '?', '(only you)', 'Unknown User')
26 THEN chats.title ELSE excluded.title END,
27 member_summary = excluded.member_summary,
28 last_message_at = excluded.last_message_at,
29 last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),
30 unread = CASE WHEN ?12 THEN chats.unread ELSE excluded.unread AND (
31 excluded.last_message_at IS NULL
32 OR COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at) IS NULL
33 OR excluded.last_message_at > COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at)
34 ) END,
35 last_message_preview = CASE WHEN ?13 THEN chats.last_message_preview ELSE excluded.last_message_preview END,
36 last_message_sender_id = CASE WHEN ?13 THEN chats.last_message_sender_id ELSE excluded.last_message_sender_id END,
37 last_message_sender_name = CASE WHEN ?13 THEN chats.last_message_sender_name ELSE excluded.last_message_sender_name END,
38 last_message_deleted = CASE WHEN ?13 THEN chats.last_message_deleted ELSE excluded.last_message_deleted END,
39 preview_at = CASE WHEN ?13 THEN chats.preview_at ELSE excluded.preview_at END",
40 )?;
41 let mut clear_members =
42 transaction.prepare_cached("DELETE FROM chat_members WHERE chat_id = ?1")?;
43 let mut insert_member = transaction.prepare_cached(
44 "INSERT INTO chat_members (chat_id, position, user_id, display_name) VALUES (?1, ?2, ?3, ?4)",
45 )?;
46 for chat in chats {
47 upsert.execute(params![
48 chat.id,
49 chat.kind,
50 chat.title,
51 chat.member_summary,
52 optional_to_millis(chat.last_message_at),
53 optional_to_millis(chat.last_read_at),
54 chat.unread,
55 chat.last_message_preview,
56 chat.last_message_sender_id,
57 chat.last_message_sender_name,
58 chat.last_message_deleted,
59 chat.last_event_system,
60 chat.keeps_stored_preview,
61 optional_to_millis(chat.preview_at),
62 ])?;
63 clear_members.execute([&chat.id])?;
64 for (position, member) in chat.members.iter().enumerate() {
65 insert_member.execute(params![
66 chat.id,
67 position as i64,
68 member.user_id,
69 member.display_name
70 ])?;
71 }
72 }
73 }
74 Ok(transaction.commit()?)
75 }
76
77 pub fn chat_last_message_times(
78 &self,
79 chat_ids: &[String],
80 ) -> Result<HashMap<String, Option<DateTime<Utc>>>> {
81 let connection = self.lock()?;
82 let mut statement = connection.prepare_cached(
83 "SELECT id, last_message_at FROM chats WHERE id IN (SELECT value FROM json_each(?1))",
84 )?;
85 let rows = statement.query_map([json_ids(chat_ids)], |row| {
86 Ok((row.get::<_, String>(0)?, optional_from_millis(row.get(1)?)))
87 })?;
88 Ok(rows.collect::<rusqlite::Result<_>>()?)
89 }
90
91 pub fn chat_count(&self) -> Result<usize> {
92 let connection = self.lock()?;
93 let count: i64 =
94 connection.query_row("SELECT COUNT(*) FROM chats", [], |row| row.get(0))?;
95 Ok(count as usize)
96 }
97
98 pub fn remove_chats(&self, chat_ids: &[String]) -> Result<usize> {
99 let connection = self.lock()?;
100 Ok(connection.execute(
101 "DELETE FROM chats WHERE id IN (SELECT value FROM json_each(?1))",
102 [json_ids(chat_ids)],
103 )?)
104 }
105
106 pub fn remove_chats_except(&self, kept_chat_ids: &[String]) -> Result<usize> {
107 let connection = self.lock()?;
108 Ok(connection.execute(
109 "DELETE FROM chats WHERE id NOT IN (SELECT value FROM json_each(?1))",
110 [json_ids(kept_chat_ids)],
111 )?)
112 }
113
114 pub fn mark_chat_read(&self, chat_id: &str, read_at: DateTime<Utc>) -> Result<()> {
115 let connection = self.lock()?;
116 connection.execute(
117 "UPDATE chats SET unread = 0, last_read_at = ?2 WHERE id = ?1",
118 params![chat_id, to_millis(read_at)],
119 )?;
120 Ok(())
121 }
122
123 pub fn mark_chat_unread(&self, chat_id: &str, last_read_at: DateTime<Utc>) -> Result<()> {
124 let connection = self.lock()?;
125 connection.execute(
126 "UPDATE chats SET unread = 1, last_read_at = ?2 WHERE id = ?1",
127 params![chat_id, to_millis(last_read_at)],
128 )?;
129 Ok(())
130 }
131
132 pub fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
133 let connection = self.lock()?;
134 connection.execute(
135 "UPDATE chats SET muted = ?2 WHERE id = ?1",
136 params![chat_id, muted],
137 )?;
138 Ok(())
139 }
140
141 pub fn apply_muted_states(&self, states: &[(String, bool)]) -> Result<()> {
142 let mut connection = self.lock()?;
143 let transaction = connection.transaction()?;
144 {
145 let mut update =
146 transaction.prepare_cached("UPDATE chats SET muted = ?2 WHERE id = ?1")?;
147 for (chat_id, muted) in states {
148 update.execute(params![chat_id, muted])?;
149 }
150 }
151 transaction.commit()?;
152 Ok(())
153 }
154
155 /// Applies the preview only when the message is at least as new as the cached last message and differs. Returns whether the row changed.
156 pub fn update_chat_preview(
157 &self,
158 chat_id: &str,
159 message_at: DateTime<Utc>,
160 preview: &ChatPreview<'_>,
161 ) -> Result<bool> {
162 let connection = self.lock()?;
163 let changed = connection.execute(
164 "UPDATE chats SET last_message_at = ?2, preview_at = ?2, last_message_preview = ?3, last_message_sender_id = ?4,
165 last_message_sender_name = ?5, last_message_deleted = ?6
166 WHERE id = ?1 AND (last_message_at IS NULL OR last_message_at <= ?2)
167 AND (last_message_at IS NOT ?2 OR preview_at IS NOT ?2 OR last_message_preview IS NOT ?3 OR last_message_sender_id IS NOT ?4
168 OR last_message_sender_name IS NOT ?5 OR last_message_deleted IS NOT ?6)",
169 params![
170 chat_id,
171 to_millis(message_at),
172 preview.text,
173 preview.sender_id,
174 preview.sender_name,
175 preview.deleted
176 ],
177 )?;
178 Ok(changed > 0)
179 }
180
181 pub fn touch_chat_time(&self, chat_id: &str, at: DateTime<Utc>) -> Result<bool> {
182 let connection = self.lock()?;
183 let changed = connection.execute(
184 "UPDATE chats SET last_message_at = ?2
185 WHERE id = ?1 AND (last_message_at IS NULL OR last_message_at < ?2)",
186 params![chat_id, to_millis(at)],
187 )?;
188 Ok(changed > 0)
189 }
190
191 pub fn recent_chats(&self, limit: usize) -> Result<Vec<ChatRecord>> {
192 let connection = self.lock()?;
193 let mut statement = connection.prepare_cached(&format!(
194 "SELECT {CHAT_COLUMNS} FROM chats ORDER BY last_message_at IS NULL, last_message_at DESC, id LIMIT ?1"
195 ))?;
196 let mut chats = statement
197 .query_map([limit as i64], chat_from_row)?
198 .collect::<rusqlite::Result<Vec<_>>>()?;
199 load_members(&connection, &mut chats)?;
200 Ok(chats)
201 }
202
203 pub fn chat(&self, chat_id: &str) -> Result<Option<ChatRecord>> {
204 let connection = self.lock()?;
205 let mut statement = connection
206 .prepare_cached(&format!("SELECT {CHAT_COLUMNS} FROM chats WHERE id = ?1"))?;
207 let mut chats = statement
208 .query_map([chat_id], chat_from_row)?
209 .collect::<rusqlite::Result<Vec<_>>>()?;
210 load_members(&connection, &mut chats)?;
211 Ok(chats.pop())
212 }
213}
214
215fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {
216 Ok(ChatRecord {
217 id: row.get(0)?,
218 kind: row.get(1)?,
219 title: row.get(2)?,
220 member_summary: row.get(3)?,
221 last_message_at: optional_from_millis(row.get(4)?),
222 last_read_at: optional_from_millis(row.get(5)?),
223 unread: row.get(6)?,
224 members: Vec::new(),
225 last_message_preview: row.get(7)?,
226 last_message_sender_id: row.get(8)?,
227 last_message_sender_name: row.get(9)?,
228 last_message_deleted: row.get(10)?,
229 muted: row.get(11)?,
230 preview_at: optional_from_millis(row.get(12)?),
231 last_event_system: false,
232 keeps_stored_preview: false,
233 })
234}
235
236fn load_members(connection: &rusqlite::Connection, chats: &mut [ChatRecord]) -> Result<()> {
237 let mut statement = connection.prepare_cached(
238 "SELECT user_id, display_name FROM chat_members WHERE chat_id = ?1 ORDER BY position",
239 )?;
240 for chat in chats {
241 chat.members = statement
242 .query_map([&chat.id], |row| {
243 Ok(MemberRecord {
244 user_id: row.get(0)?,
245 display_name: row.get(1)?,
246 })
247 })?
248 .collect::<rusqlite::Result<Vec<_>>>()?;
249 }
250 Ok(())
251}