BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 15.8 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, 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 pub fn messages_by_id(
273 &self,
274 conversation_id: &str,
275 message_ids: &[String],
276 ) -> Result<HashMap<String, MessageRecord>> {
277 let connection = self.lock()?;
278 let mut statement = connection.prepare_cached(&format!(
279 "SELECT {MESSAGE_COLUMNS} FROM messages
280 WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
281 ))?;
282 let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned());
283 let rows = statement.query_map(
284 params_from_iter([conversation_id, ids.as_str()]),
285 message_from_row,
286 )?;
287 let mut found = HashMap::new();
288 for row in rows {
289 let message = row?;
290 found.insert(message.message_id.clone(), message);
291 }
292 Ok(found)
293 }
294
295 /// Newest first: (message_id, reactions_json) of the sender's undeleted messages.
296 pub fn reaction_state_of_sender(
297 &self,
298 conversation_id: &str,
299 sender_id: &str,
300 limit: usize,
301 ) -> Result<Vec<(String, String)>> {
302 let connection = self.lock()?;
303 let mut statement = connection.prepare_cached(
304 "SELECT message_id, reactions_json FROM messages
305 WHERE conversation_id = ?1 AND sender_id = ?2 AND deleted = 0
306 ORDER BY created_at DESC, message_id DESC LIMIT ?3",
307 )?;
308 let rows = statement
309 .query_map(params![conversation_id, sender_id, limit as i64], |row| {
310 Ok((row.get(0)?, row.get(1)?))
311 })?
312 .collect::<rusqlite::Result<_>>()?;
313 Ok(rows)
314 }
315
316 /// (user_id, display name) of the senders and mentioned people in the newest `scan` messages.
317 pub fn conversation_people(
318 &self,
319 conversation_id: &str,
320 scan: usize,
321 ) -> Result<Vec<(String, String)>> {
322 let connection = self.lock()?;
323 let mut statement = connection.prepare_cached(
324 "WITH recent AS (
325 SELECT sender_id, sender_name, mentions_json FROM messages
326 WHERE conversation_id = ?1 ORDER BY created_at DESC, message_id DESC LIMIT ?2)
327 SELECT DISTINCT sender_id, sender_name FROM recent
328 WHERE sender_id IS NOT NULL AND sender_name IS NOT NULL
329 UNION
330 SELECT DISTINCT json_extract(mention.value, '$.user_id'), json_extract(mention.value, '$.name')
331 FROM recent, json_each(CASE WHEN json_valid(mentions_json) THEN mentions_json ELSE '[]' END) AS mention
332 WHERE json_extract(mention.value, '$.user_id') IS NOT NULL
333 AND json_extract(mention.value, '$.name') IS NOT NULL",
334 )?;
335 let people = statement
336 .query_map(params![conversation_id, scan as i64], |row| {
337 Ok((row.get(0)?, row.get(1)?))
338 })?
339 .collect::<rusqlite::Result<_>>()?;
340 Ok(people)
341 }
342
343 pub fn display_names(&self, user_ids: &[String]) -> Result<HashMap<String, String>> {
344 if user_ids.is_empty() {
345 return Ok(HashMap::new());
346 }
347 let connection = self.lock()?;
348 let mut statement = connection.prepare_cached(
349 "SELECT value, COALESCE(
350 (SELECT display_name FROM chat_members
351 WHERE user_id = value AND display_name <> '' LIMIT 1),
352 (SELECT sender_name FROM messages
353 WHERE sender_id = value AND sender_name <> ''
354 ORDER BY created_at DESC LIMIT 1))
355 FROM json_each(?1)",
356 )?;
357 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
358 let rows = statement.query_map([ids], |row| {
359 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
360 })?;
361 let mut names = HashMap::new();
362 for row in rows {
363 if let (user_id, Some(name)) = row? {
364 names.insert(user_id, name);
365 }
366 }
367 Ok(names)
368 }
369
370 pub fn thread_has_sender(
371 &self,
372 conversation_id: &str,
373 root_id: &str,
374 user_id: &str,
375 ) -> Result<bool> {
376 let connection = self.lock()?;
377 Ok(connection.query_row(
378 "SELECT EXISTS (
379 SELECT 1 FROM messages
380 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
381 AND (message_id = ?2 OR reply_to_id = ?2))",
382 params![conversation_id, root_id, user_id],
383 |row| row.get(0),
384 )?)
385 }
386
387 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
388 let connection = self.lock()?;
389 let count: i64 = connection.query_row(
390 "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
391 [conversation_id],
392 |row| row.get(0),
393 )?;
394 Ok(count as usize)
395 }
396}
397
398fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
399 Ok(MessageRecord {
400 conversation_id: row.get(0)?,
401 message_id: row.get(1)?,
402 reply_to_id: row.get(2)?,
403 sender_id: row.get(3)?,
404 sender_name: row.get(4)?,
405 created_at: from_millis(row.get(5)?),
406 edited_at: optional_from_millis(row.get(6)?),
407 deleted: row.get(7)?,
408 body_html: row.get(8)?,
409 attachments_json: row.get(9)?,
410 reactions_json: row.get(10)?,
411 mentions_json: row.get(11)?,
412 sender_application_id: row.get(12)?,
413 links_json: row.get(13)?,
414 subject: row.get(14)?,
415 call_event_json: row.get(15)?,
416 })
417}