BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 18.6 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::{MessageImportance, MessageRecord, RecentScope, UNKNOWN_USER_NAME};
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, call_event_json, importance";
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, ?16, ?17)
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 importance = COALESCE(excluded.importance, messages.importance),
32 call_event_json = excluded.call_event_json,
33 links_json = CASE WHEN excluded.links_json IN ('', '[]')
34 THEN messages.links_json ELSE excluded.links_json END"
35 ))?;
36 for message in messages {
37 upsert.execute(params![
38 message.conversation_id,
39 message.message_id,
40 message.reply_to_id,
41 message.sender_id,
42 message.sender_name,
43 to_millis(message.created_at),
44 optional_to_millis(message.edited_at),
45 message.deleted,
46 message.body_html,
47 message.attachments_json,
48 message.reactions_json,
49 message.mentions_json,
50 message.sender_application_id,
51 message.links_json,
52 message.subject,
53 message.call_event_json,
54 message.importance.stored(),
55 ])?;
56 index_message(&transaction, message)?;
57 }
58 }
59 Ok(transaction.commit()?)
60 }
61
62 pub fn set_message_links(
63 &self,
64 conversation_id: &str,
65 message_id: &str,
66 links_json: &str,
67 ) -> Result<bool> {
68 let connection = self.lock()?;
69 let changed = connection.execute(
70 "UPDATE messages SET links_json = ?3
71 WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",
72 params![conversation_id, message_id, links_json],
73 )?;
74 Ok(changed > 0)
75 }
76
77 pub fn count_messages_after(
78 &self,
79 conversation_id: &str,
80 after: Option<DateTime<Utc>>,
81 not_from_user_id: &str,
82 ) -> Result<usize> {
83 let connection = self.read()?;
84 let count: i64 = connection.query_row(
85 "SELECT COUNT(*) FROM messages
86 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
87 AND call_event_json IS NULL
88 AND (sender_id IS NULL OR sender_id != ?3)",
89 params![
90 conversation_id,
91 optional_to_millis(after).unwrap_or(i64::MIN),
92 not_from_user_id
93 ],
94 |row| row.get(0),
95 )?;
96 Ok(count as usize)
97 }
98
99 /// Teams marks a chat in the list by the importance of its last message while it is unread and from someone else.
100 pub fn unread_last_message_importance(
101 &self,
102 conversation_id: &str,
103 after: Option<DateTime<Utc>>,
104 not_from_user_id: &str,
105 ) -> Result<MessageImportance> {
106 let connection = self.read()?;
107 let last: Option<(Option<String>, Option<String>, i64)> = connection
108 .query_row(
109 "SELECT importance, sender_id, created_at FROM messages
110 WHERE conversation_id = ?1 AND deleted = 0 AND call_event_json IS NULL
111 ORDER BY created_at DESC, message_id DESC LIMIT 1",
112 params![conversation_id],
113 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
114 )
115 .optional()?;
116 let Some((importance, sender_id, created_at)) = last else {
117 return Ok(MessageImportance::Normal);
118 };
119 let unread = created_at > optional_to_millis(after).unwrap_or(i64::MIN);
120 let from_others = sender_id.as_deref() != Some(not_from_user_id);
121 Ok(if unread && from_others {
122 MessageImportance::from_stored(importance.as_deref())
123 } else {
124 MessageImportance::Normal
125 })
126 }
127
128 pub fn first_message_after_from_others(
129 &self,
130 conversation_id: &str,
131 after: Option<DateTime<Utc>>,
132 not_from_user_id: &str,
133 ) -> Result<Option<String>> {
134 let connection = self.read()?;
135 Ok(connection
136 .query_row(
137 "SELECT message_id FROM messages
138 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
139 AND call_event_json IS NULL
140 AND (sender_id IS NULL OR sender_id != ?3)
141 ORDER BY created_at ASC, message_id ASC LIMIT 1",
142 params![
143 conversation_id,
144 optional_to_millis(after).unwrap_or(i64::MIN),
145 not_from_user_id
146 ],
147 |row| row.get(0),
148 )
149 .optional()?)
150 }
151
152 /// Oldest-first page of the `limit` newest messages strictly older than `before` (all when `None`).
153 pub fn messages(
154 &self,
155 conversation_id: &str,
156 before: Option<DateTime<Utc>>,
157 limit: usize,
158 ) -> Result<Vec<MessageRecord>> {
159 let connection = self.read()?;
160 let mut statement = connection.prepare_cached(&format!(
161 "SELECT {MESSAGE_COLUMNS} FROM messages
162 WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)
163 ORDER BY created_at DESC, message_id DESC LIMIT ?3"
164 ))?;
165 let mut messages = statement
166 .query_map(
167 params![conversation_id, optional_to_millis(before), limit as i64],
168 message_from_row,
169 )?
170 .collect::<rusqlite::Result<Vec<_>>>()?;
171 messages.reverse();
172 Ok(messages)
173 }
174
175 pub fn messages_between(
176 &self,
177 conversation_id: &str,
178 from: DateTime<Utc>,
179 to: DateTime<Utc>,
180 ) -> Result<Vec<MessageRecord>> {
181 let connection = self.read()?;
182 let mut statement = connection.prepare_cached(&format!(
183 "SELECT {MESSAGE_COLUMNS} FROM messages
184 WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3
185 ORDER BY created_at ASC, message_id ASC"
186 ))?;
187 let messages = statement
188 .query_map(
189 params![conversation_id, to_millis(from), to_millis(to)],
190 message_from_row,
191 )?
192 .collect::<rusqlite::Result<Vec<_>>>()?;
193 Ok(messages)
194 }
195
196 /// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
197 pub fn messages_after(
198 &self,
199 conversation_id: &str,
200 after: DateTime<Utc>,
201 limit: usize,
202 ) -> Result<Vec<MessageRecord>> {
203 let connection = self.read()?;
204 let mut statement = connection.prepare_cached(&format!(
205 "SELECT {MESSAGE_COLUMNS} FROM messages
206 WHERE conversation_id = ?1 AND created_at > ?2
207 ORDER BY created_at ASC, message_id ASC LIMIT ?3"
208 ))?;
209 let messages = statement
210 .query_map(
211 params![conversation_id, to_millis(after), limit as i64],
212 message_from_row,
213 )?
214 .collect::<rusqlite::Result<Vec<_>>>()?;
215 Ok(messages)
216 }
217
218 /// Oldest-first root and replies of one channel thread.
219 pub fn thread_messages(
220 &self,
221 conversation_id: &str,
222 root_id: &str,
223 ) -> Result<Vec<MessageRecord>> {
224 let connection = self.read()?;
225 let mut statement = connection.prepare_cached(&format!(
226 "SELECT {MESSAGE_COLUMNS} FROM messages
227 WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
228 ORDER BY created_at ASC, message_id ASC"
229 ))?;
230 let messages = statement
231 .query_map(params![conversation_id, root_id], message_from_row)?
232 .collect::<rusqlite::Result<Vec<_>>>()?;
233 Ok(messages)
234 }
235
236 pub fn recent_messages(
237 &self,
238 scopes: &[RecentScope],
239 before: Option<(DateTime<Utc>, &str, &str)>,
240 limit: usize,
241 ) -> Result<Vec<MessageRecord>> {
242 let scope_json = serde_json::to_string(
243 &scopes
244 .iter()
245 .map(|scope| {
246 serde_json::json!({
247 "conversation_id": scope.conversation_id,
248 "after": to_millis(scope.after),
249 })
250 })
251 .collect::<Vec<_>>(),
252 )
253 .unwrap_or_else(|_| "[]".to_owned());
254 let (before_time, before_message_id, before_conversation_id) = match before {
255 Some((time, message_id, conversation_id)) => (
256 Some(to_millis(time)),
257 Some(message_id),
258 Some(conversation_id),
259 ),
260 None => (None, None, None),
261 };
262 let connection = self.read()?;
263 let mut statement = connection.prepare_cached(&format!(
264 "SELECT {MESSAGE_COLUMNS} FROM messages
265 JOIN json_each(?1) AS scope
266 ON messages.conversation_id = json_extract(scope.value, '$.conversation_id')
267 WHERE deleted = 0 AND created_at > json_extract(scope.value, '$.after')
268 AND (?2 IS NULL OR (created_at, message_id, messages.conversation_id) < (?2, ?3, ?4))
269 ORDER BY created_at DESC, message_id DESC, messages.conversation_id DESC LIMIT ?5"
270 ))?;
271 let messages = statement
272 .query_map(
273 params![
274 scope_json,
275 before_time,
276 before_message_id,
277 before_conversation_id,
278 limit as i64
279 ],
280 message_from_row,
281 )?
282 .collect::<rusqlite::Result<Vec<_>>>()?;
283 Ok(messages)
284 }
285
286 pub fn messages_with_attachment_type(
287 &self,
288 conversation_id: &str,
289 content_type: &str,
290 ) -> Result<Vec<MessageRecord>> {
291 let connection = self.read()?;
292 let mut statement = connection.prepare_cached(&format!(
293 "SELECT {MESSAGE_COLUMNS} FROM messages
294 WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"
295 ))?;
296 let needle = format!("\"content_type\":\"{content_type}\"");
297 let messages = statement
298 .query_map(params![conversation_id, needle], message_from_row)?
299 .collect::<rusqlite::Result<Vec<_>>>()?;
300 Ok(messages)
301 }
302
303 /// Chats, newest first, holding an attachment of `content_type` without content that is not marked unavailable.
304 pub fn conversations_with_stale_attachments(&self, content_type: &str) -> Result<Vec<String>> {
305 let connection = self.read()?;
306 let mut statement = connection.prepare_cached(
307 "SELECT chats.id FROM chats
308 WHERE EXISTS (
309 SELECT 1 FROM messages, json_each(messages.attachments_json) AS attachment
310 WHERE messages.conversation_id = chats.id
311 AND instr(messages.attachments_json, ?1) > 0
312 AND json_extract(attachment.value, '$.content_type') = ?2
313 AND json_extract(attachment.value, '$.content') IS NULL
314 AND NOT coalesce(json_extract(attachment.value, '$.unavailable'), 0)
315 )
316 ORDER BY chats.last_message_at DESC",
317 )?;
318 let needle = format!("\"content_type\":\"{content_type}\"");
319 let conversation_ids = statement
320 .query_map(params![needle, content_type], |row| row.get(0))?
321 .collect::<rusqlite::Result<Vec<String>>>()?;
322 Ok(conversation_ids)
323 }
324
325 pub fn messages_by_id(
326 &self,
327 conversation_id: &str,
328 message_ids: &[String],
329 ) -> Result<HashMap<String, MessageRecord>> {
330 let connection = self.read()?;
331 let mut statement = connection.prepare_cached(&format!(
332 "SELECT {MESSAGE_COLUMNS} FROM messages
333 WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
334 ))?;
335 let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned());
336 let rows = statement.query_map(
337 params_from_iter([conversation_id, ids.as_str()]),
338 message_from_row,
339 )?;
340 let mut found = HashMap::new();
341 for row in rows {
342 let message = row?;
343 found.insert(message.message_id.clone(), message);
344 }
345 Ok(found)
346 }
347
348 /// Newest first: (message_id, reactions_json) of the sender's undeleted messages.
349 pub fn reaction_state_of_sender(
350 &self,
351 conversation_id: &str,
352 sender_id: &str,
353 limit: usize,
354 ) -> Result<Vec<(String, String)>> {
355 let connection = self.read()?;
356 let mut statement = connection.prepare_cached(
357 "SELECT message_id, reactions_json FROM messages
358 WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0
359 ORDER BY created_at DESC, message_id DESC LIMIT ?3",
360 )?;
361 let rows = statement
362 .query_map(params![conversation_id, sender_id, limit as i64], |row| {
363 Ok((row.get(0)?, row.get(1)?))
364 })?
365 .collect::<rusqlite::Result<_>>()?;
366 Ok(rows)
367 }
368
369 /// (user_id, display name) of the senders and mentioned people in the newest `scan` messages.
370 pub fn conversation_people(
371 &self,
372 conversation_id: &str,
373 scan: usize,
374 ) -> Result<Vec<(String, String)>> {
375 let connection = self.read()?;
376 let mut statement = connection.prepare_cached(
377 "WITH recent AS (
378 SELECT sender_id, sender_name, mentions_json FROM messages
379 WHERE conversation_id = ?1 ORDER BY created_at DESC, message_id DESC LIMIT ?2)
380 SELECT DISTINCT sender_id, sender_name FROM recent
381 WHERE sender_id IS NOT NULL AND sender_name IS NOT NULL
382 UNION
383 SELECT DISTINCT json_extract(mention.value, '$.user_id'), json_extract(mention.value, '$.name')
384 FROM recent, json_each(CASE WHEN json_valid(mentions_json) THEN mentions_json ELSE '[]' END) AS mention
385 WHERE json_extract(mention.value, '$.user_id') IS NOT NULL
386 AND json_extract(mention.value, '$.name') IS NOT NULL",
387 )?;
388 let people = statement
389 .query_map(params![conversation_id, scan as i64], |row| {
390 Ok((row.get(0)?, row.get(1)?))
391 })?
392 .collect::<rusqlite::Result<_>>()?;
393 Ok(people)
394 }
395
396 pub fn display_names(&self, user_ids: &[String]) -> Result<HashMap<String, String>> {
397 if user_ids.is_empty() {
398 return Ok(HashMap::new());
399 }
400 let connection = self.read()?;
401 let mut statement = connection.prepare_cached(
402 "SELECT value, COALESCE(
403 (SELECT display_name FROM chat_members
404 WHERE user_id = value AND display_name NOT IN ('', '?', ?2) LIMIT 1),
405 (SELECT sender_name FROM messages
406 WHERE sender_id = value AND sender_name NOT IN ('', '?', ?2)
407 ORDER BY created_at DESC LIMIT 1))
408 FROM json_each(?1)",
409 )?;
410 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
411 let rows = statement.query_map(params![ids, UNKNOWN_USER_NAME], |row| {
412 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
413 })?;
414 let mut names = HashMap::new();
415 for row in rows {
416 if let (user_id, Some(name)) = row? {
417 names.insert(user_id, name);
418 }
419 }
420 Ok(names)
421 }
422
423 pub fn thread_has_sender(
424 &self,
425 conversation_id: &str,
426 root_id: &str,
427 user_id: &str,
428 ) -> Result<bool> {
429 let connection = self.read()?;
430 Ok(connection.query_row(
431 "SELECT EXISTS (
432 SELECT 1 FROM messages
433 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
434 AND (message_id = ?2 OR reply_to_id = ?2))",
435 params![conversation_id, root_id, user_id],
436 |row| row.get(0),
437 )?)
438 }
439
440 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
441 let connection = self.read()?;
442 let count: i64 = connection.query_row(
443 "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
444 [conversation_id],
445 |row| row.get(0),
446 )?;
447 Ok(count as usize)
448 }
449}
450
451fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
452 Ok(MessageRecord {
453 conversation_id: row.get(0)?,
454 message_id: row.get(1)?,
455 reply_to_id: row.get(2)?,
456 sender_id: row.get(3)?,
457 sender_name: row.get(4)?,
458 created_at: from_millis(row.get(5)?),
459 edited_at: optional_from_millis(row.get(6)?),
460 deleted: row.get(7)?,
461 body_html: row.get(8)?,
462 attachments_json: row.get(9)?,
463 reactions_json: row.get(10)?,
464 mentions_json: row.get(11)?,
465 sender_application_id: row.get(12)?,
466 links_json: row.get(13)?,
467 subject: row.get(14)?,
468 call_event_json: row.get(15)?,
469 importance: MessageImportance::from_stored(row.get::<_, Option<String>>(16)?.as_deref()),
470 })
471}