BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 14.9 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, RecentScope};
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 pub fn messages_between(
141 &self,
142 conversation_id: &str,
143 from: DateTime<Utc>,
144 to: DateTime<Utc>,
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 created_at >= ?2 AND created_at <= ?3
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(
154 params![conversation_id, to_millis(from), to_millis(to)],
155 message_from_row,
156 )?
157 .collect::<rusqlite::Result<Vec<_>>>()?;
158 Ok(messages)
159 }
160
161 /// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
162 pub fn messages_after(
163 &self,
164 conversation_id: &str,
165 after: DateTime<Utc>,
166 limit: usize,
167 ) -> Result<Vec<MessageRecord>> {
168 let connection = self.lock()?;
169 let mut statement = connection.prepare_cached(&format!(
170 "SELECT {MESSAGE_COLUMNS} FROM messages
171 WHERE conversation_id = ?1 AND created_at > ?2
172 ORDER BY created_at ASC, message_id ASC LIMIT ?3"
173 ))?;
174 let messages = statement
175 .query_map(
176 params![conversation_id, to_millis(after), limit as i64],
177 message_from_row,
178 )?
179 .collect::<rusqlite::Result<Vec<_>>>()?;
180 Ok(messages)
181 }
182
183 /// Oldest-first root and replies of one channel thread.
184 pub fn thread_messages(
185 &self,
186 conversation_id: &str,
187 root_id: &str,
188 ) -> Result<Vec<MessageRecord>> {
189 let connection = self.lock()?;
190 let mut statement = connection.prepare_cached(&format!(
191 "SELECT {MESSAGE_COLUMNS} FROM messages
192 WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
193 ORDER BY created_at ASC, message_id ASC"
194 ))?;
195 let messages = statement
196 .query_map(params![conversation_id, root_id], message_from_row)?
197 .collect::<rusqlite::Result<Vec<_>>>()?;
198 Ok(messages)
199 }
200
201 pub fn recent_messages(
202 &self,
203 scopes: &[RecentScope],
204 before: Option<(DateTime<Utc>, &str, &str)>,
205 limit: usize,
206 ) -> Result<Vec<MessageRecord>> {
207 let scope_json = serde_json::to_string(
208 &scopes
209 .iter()
210 .map(|scope| {
211 serde_json::json!({
212 "conversation_id": scope.conversation_id,
213 "after": to_millis(scope.after),
214 })
215 })
216 .collect::<Vec<_>>(),
217 )
218 .unwrap_or_else(|_| "[]".to_owned());
219 let (before_time, before_message_id, before_conversation_id) = match before {
220 Some((time, message_id, conversation_id)) => (
221 Some(to_millis(time)),
222 Some(message_id),
223 Some(conversation_id),
224 ),
225 None => (None, None, None),
226 };
227 let connection = self.lock()?;
228 let mut statement = connection.prepare_cached(&format!(
229 "SELECT {MESSAGE_COLUMNS} FROM messages
230 JOIN json_each(?1) AS scope
231 ON messages.conversation_id = json_extract(scope.value, '$.conversation_id')
232 WHERE deleted = 0 AND created_at > json_extract(scope.value, '$.after')
233 AND (?2 IS NULL OR (created_at, message_id, messages.conversation_id) < (?2, ?3, ?4))
234 ORDER BY created_at DESC, message_id DESC, messages.conversation_id DESC LIMIT ?5"
235 ))?;
236 let messages = statement
237 .query_map(
238 params![
239 scope_json,
240 before_time,
241 before_message_id,
242 before_conversation_id,
243 limit as i64
244 ],
245 message_from_row,
246 )?
247 .collect::<rusqlite::Result<Vec<_>>>()?;
248 Ok(messages)
249 }
250
251 pub fn messages_by_id(
252 &self,
253 conversation_id: &str,
254 message_ids: &[String],
255 ) -> Result<HashMap<String, MessageRecord>> {
256 let connection = self.lock()?;
257 let mut statement = connection.prepare_cached(&format!(
258 "SELECT {MESSAGE_COLUMNS} FROM messages
259 WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
260 ))?;
261 let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned());
262 let rows = statement.query_map(
263 params_from_iter([conversation_id, ids.as_str()]),
264 message_from_row,
265 )?;
266 let mut found = HashMap::new();
267 for row in rows {
268 let message = row?;
269 found.insert(message.message_id.clone(), message);
270 }
271 Ok(found)
272 }
273
274 /// Newest first: (message_id, reactions_json) of the sender's undeleted messages.
275 pub fn reaction_state_of_sender(
276 &self,
277 conversation_id: &str,
278 sender_id: &str,
279 limit: usize,
280 ) -> Result<Vec<(String, String)>> {
281 let connection = self.lock()?;
282 let mut statement = connection.prepare_cached(
283 "SELECT message_id, reactions_json FROM messages
284 WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0
285 ORDER BY created_at DESC, message_id DESC LIMIT ?3",
286 )?;
287 let rows = statement
288 .query_map(params![conversation_id, sender_id, limit as i64], |row| {
289 Ok((row.get(0)?, row.get(1)?))
290 })?
291 .collect::<rusqlite::Result<_>>()?;
292 Ok(rows)
293 }
294
295 /// (user_id, display name) of the senders and mentioned people in the newest `scan` messages.
296 pub fn conversation_people(
297 &self,
298 conversation_id: &str,
299 scan: usize,
300 ) -> Result<Vec<(String, String)>> {
301 let connection = self.lock()?;
302 let mut statement = connection.prepare_cached(
303 "WITH recent AS (
304 SELECT sender_id, sender_name, mentions_json FROM messages
305 WHERE conversation_id = ?1 ORDER BY created_at DESC, message_id DESC LIMIT ?2)
306 SELECT DISTINCT sender_id, sender_name FROM recent
307 WHERE sender_id IS NOT NULL AND sender_name IS NOT NULL
308 UNION
309 SELECT DISTINCT json_extract(mention.value, '$.user_id'), json_extract(mention.value, '$.name')
310 FROM recent, json_each(CASE WHEN json_valid(mentions_json) THEN mentions_json ELSE '[]' END) AS mention
311 WHERE json_extract(mention.value, '$.user_id') IS NOT NULL
312 AND json_extract(mention.value, '$.name') IS NOT NULL",
313 )?;
314 let people = statement
315 .query_map(params![conversation_id, scan as i64], |row| {
316 Ok((row.get(0)?, row.get(1)?))
317 })?
318 .collect::<rusqlite::Result<_>>()?;
319 Ok(people)
320 }
321
322 pub fn display_names(&self, user_ids: &[String]) -> Result<HashMap<String, String>> {
323 if user_ids.is_empty() {
324 return Ok(HashMap::new());
325 }
326 let connection = self.lock()?;
327 let mut statement = connection.prepare_cached(
328 "SELECT value, COALESCE(
329 (SELECT display_name FROM chat_members
330 WHERE user_id = value AND display_name <> '' LIMIT 1),
331 (SELECT sender_name FROM messages
332 WHERE sender_id = value AND sender_name <> ''
333 ORDER BY created_at DESC LIMIT 1))
334 FROM json_each(?1)",
335 )?;
336 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
337 let rows = statement.query_map([ids], |row| {
338 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
339 })?;
340 let mut names = HashMap::new();
341 for row in rows {
342 if let (user_id, Some(name)) = row? {
343 names.insert(user_id, name);
344 }
345 }
346 Ok(names)
347 }
348
349 pub fn thread_has_sender(
350 &self,
351 conversation_id: &str,
352 root_id: &str,
353 user_id: &str,
354 ) -> Result<bool> {
355 let connection = self.lock()?;
356 Ok(connection.query_row(
357 "SELECT EXISTS (
358 SELECT 1 FROM messages
359 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
360 AND (message_id = ?2 OR reply_to_id = ?2))",
361 params![conversation_id, root_id, user_id],
362 |row| row.get(0),
363 )?)
364 }
365
366 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
367 let connection = self.lock()?;
368 let count: i64 = connection.query_row(
369 "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
370 [conversation_id],
371 |row| row.get(0),
372 )?;
373 Ok(count as usize)
374 }
375}
376
377fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
378 Ok(MessageRecord {
379 conversation_id: row.get(0)?,
380 message_id: row.get(1)?,
381 reply_to_id: row.get(2)?,
382 sender_id: row.get(3)?,
383 sender_name: row.get(4)?,
384 created_at: from_millis(row.get(5)?),
385 edited_at: optional_from_millis(row.get(6)?),
386 deleted: row.get(7)?,
387 body_html: row.get(8)?,
388 attachments_json: row.get(9)?,
389 reactions_json: row.get(10)?,
390 mentions_json: row.get(11)?,
391 sender_application_id: row.get(12)?,
392 links_json: row.get(13)?,
393 subject: row.get(14)?,
394 })
395}