BlueGit

ict rusty-teams

Files

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

chats.rs

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