BlueGit

ict rusty-teams

Files

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

chats.rs

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