BlueGit

ict rusty-teams

Files

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

chats.rs

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