BlueGit

ict rusty-teams

Files

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

chats.rs

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