BlueGit

ict rusty-teams

Files

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

messages.rs

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