BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 9.5 KiB Download Raw
1use std::collections::HashMap;
2
3use chrono::{DateTime, Utc};
4use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5
6use crate::error::Result;
7use crate::models::MessageRecord;
8use crate::search::index_message;
9use crate::store::Store;
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject";
14
15impl Store {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
17 let mut connection = self.lock()?;
18 let transaction = connection.transaction()?;
19 {
20 let mut upsert = transaction.prepare_cached(&format!(
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
26 edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28 mentions_json = excluded.mentions_json,
29 sender_application_id = excluded.sender_application_id,
30 subject = COALESCE(excluded.subject, messages.subject),
31 links_json = CASE WHEN excluded.links_json IN ('', '[]')
32 THEN messages.links_json ELSE excluded.links_json END"
33 ))?;
34 for message in messages {
35 upsert.execute(params![
36 message.conversation_id,
37 message.message_id,
38 message.reply_to_id,
39 message.sender_id,
40 message.sender_name,
41 to_millis(message.created_at),
42 optional_to_millis(message.edited_at),
43 message.deleted,
44 message.body_html,
45 message.attachments_json,
46 message.reactions_json,
47 message.mentions_json,
48 message.sender_application_id,
49 message.links_json,
50 message.subject,
51 ])?;
52 index_message(&transaction, message)?;
53 }
54 }
55 Ok(transaction.commit()?)
56 }
57
58 pub fn set_message_links(
59 &self,
60 conversation_id: &str,
61 message_id: &str,
62 links_json: &str,
63 ) -> Result<bool> {
64 let connection = self.lock()?;
65 let changed = connection.execute(
66 "UPDATE messages SET links_json = ?3
67 WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",
68 params![conversation_id, message_id, links_json],
69 )?;
70 Ok(changed > 0)
71 }
72
73 pub fn count_messages_after(
74 &self,
75 conversation_id: &str,
76 after: Option<DateTime<Utc>>,
77 not_from_user_id: &str,
78 ) -> Result<usize> {
79 let connection = self.lock()?;
80 let count: i64 = connection.query_row(
81 "SELECT COUNT(*) FROM messages
82 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
83 AND (sender_id IS NULL OR sender_id != ?3)",
84 params![
85 conversation_id,
86 optional_to_millis(after).unwrap_or(i64::MIN),
87 not_from_user_id
88 ],
89 |row| row.get(0),
90 )?;
91 Ok(count as usize)
92 }
93
94 pub fn first_message_after_from_others(
95 &self,
96 conversation_id: &str,
97 after: Option<DateTime<Utc>>,
98 not_from_user_id: &str,
99 ) -> Result<Option<String>> {
100 let connection = self.lock()?;
101 Ok(connection
102 .query_row(
103 "SELECT message_id FROM messages
104 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
105 AND (sender_id IS NULL OR sender_id != ?3)
106 ORDER BY created_at ASC, message_id ASC LIMIT 1",
107 params![
108 conversation_id,
109 optional_to_millis(after).unwrap_or(i64::MIN),
110 not_from_user_id
111 ],
112 |row| row.get(0),
113 )
114 .optional()?)
115 }
116
117 /// Oldest-first page of the `limit` newest messages strictly older than `before` (all when `None`).
118 pub fn messages(
119 &self,
120 conversation_id: &str,
121 before: Option<DateTime<Utc>>,
122 limit: usize,
123 ) -> Result<Vec<MessageRecord>> {
124 let connection = self.lock()?;
125 let mut statement = connection.prepare_cached(&format!(
126 "SELECT {MESSAGE_COLUMNS} FROM messages
127 WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)
128 ORDER BY created_at DESC, message_id DESC LIMIT ?3"
129 ))?;
130 let mut messages = statement
131 .query_map(
132 params![conversation_id, optional_to_millis(before), limit as i64],
133 message_from_row,
134 )?
135 .collect::<rusqlite::Result<Vec<_>>>()?;
136 messages.reverse();
137 Ok(messages)
138 }
139
140 /// Oldest-first root and replies of one channel thread.
141 pub fn thread_messages(
142 &self,
143 conversation_id: &str,
144 root_id: &str,
145 ) -> Result<Vec<MessageRecord>> {
146 let connection = self.lock()?;
147 let mut statement = connection.prepare_cached(&format!(
148 "SELECT {MESSAGE_COLUMNS} FROM messages
149 WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(params![conversation_id, root_id], message_from_row)?
154 .collect::<rusqlite::Result<Vec<_>>>()?;
155 Ok(messages)
156 }
157
158 pub fn messages_by_id(
159 &self,
160 conversation_id: &str,
161 message_ids: &[String],
162 ) -> Result<HashMap<String, MessageRecord>> {
163 let connection = self.lock()?;
164 let mut statement = connection.prepare_cached(&format!(
165 "SELECT {MESSAGE_COLUMNS} FROM messages
166 WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
167 ))?;
168 let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned());
169 let rows = statement.query_map(
170 params_from_iter([conversation_id, ids.as_str()]),
171 message_from_row,
172 )?;
173 let mut found = HashMap::new();
174 for row in rows {
175 let message = row?;
176 found.insert(message.message_id.clone(), message);
177 }
178 Ok(found)
179 }
180
181 pub fn display_names(&self, user_ids: &[String]) -> Result<HashMap<String, String>> {
182 if user_ids.is_empty() {
183 return Ok(HashMap::new());
184 }
185 let connection = self.lock()?;
186 let mut statement = connection.prepare_cached(
187 "SELECT value, COALESCE(
188 (SELECT display_name FROM chat_members
189 WHERE user_id = value AND display_name <> '' LIMIT 1),
190 (SELECT sender_name FROM messages
191 WHERE sender_id = value AND sender_name <> ''
192 ORDER BY created_at DESC LIMIT 1))
193 FROM json_each(?1)",
194 )?;
195 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
196 let rows = statement.query_map([ids], |row| {
197 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
198 })?;
199 let mut names = HashMap::new();
200 for row in rows {
201 if let (user_id, Some(name)) = row? {
202 names.insert(user_id, name);
203 }
204 }
205 Ok(names)
206 }
207
208 pub fn thread_has_sender(
209 &self,
210 conversation_id: &str,
211 root_id: &str,
212 user_id: &str,
213 ) -> Result<bool> {
214 let connection = self.lock()?;
215 Ok(connection.query_row(
216 "SELECT EXISTS (
217 SELECT 1 FROM messages
218 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
219 AND (message_id = ?2 OR reply_to_id = ?2))",
220 params![conversation_id, root_id, user_id],
221 |row| row.get(0),
222 )?)
223 }
224
225 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
226 let connection = self.lock()?;
227 let count: i64 = connection.query_row(
228 "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
229 [conversation_id],
230 |row| row.get(0),
231 )?;
232 Ok(count as usize)
233 }
234}
235
236fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
237 Ok(MessageRecord {
238 conversation_id: row.get(0)?,
239 message_id: row.get(1)?,
240 reply_to_id: row.get(2)?,
241 sender_id: row.get(3)?,
242 sender_name: row.get(4)?,
243 created_at: from_millis(row.get(5)?),
244 edited_at: optional_from_millis(row.get(6)?),
245 deleted: row.get(7)?,
246 body_html: row.get(8)?,
247 attachments_json: row.get(9)?,
248 reactions_json: row.get(10)?,
249 mentions_json: row.get(11)?,
250 sender_application_id: row.get(12)?,
251 links_json: row.get(13)?,
252 subject: row.get(14)?,
253 })
254}