BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 8.0 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";
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)
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 ))?;
31 for message in messages {
32 upsert.execute(params![
33 message.conversation_id,
34 message.message_id,
35 message.reply_to_id,
36 message.sender_id,
37 message.sender_name,
38 to_millis(message.created_at),
39 optional_to_millis(message.edited_at),
40 message.deleted,
41 message.body_html,
42 message.attachments_json,
43 message.reactions_json,
44 message.mentions_json,
45 message.sender_application_id,
46 ])?;
47 index_message(&transaction, message)?;
48 }
49 }
50 Ok(transaction.commit()?)
51 }
52
53 pub fn count_messages_after(
54 &self,
55 conversation_id: &str,
56 after: Option<DateTime<Utc>>,
57 not_from_user_id: &str,
58 ) -> Result<usize> {
59 let connection = self.lock()?;
60 let count: i64 = connection.query_row(
61 "SELECT COUNT(*) FROM messages
62 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
63 AND (sender_id IS NULL OR sender_id != ?3)",
64 params![
65 conversation_id,
66 optional_to_millis(after).unwrap_or(i64::MIN),
67 not_from_user_id
68 ],
69 |row| row.get(0),
70 )?;
71 Ok(count as usize)
72 }
73
74 pub fn first_message_after_from_others(
75 &self,
76 conversation_id: &str,
77 after: Option<DateTime<Utc>>,
78 not_from_user_id: &str,
79 ) -> Result<Option<String>> {
80 let connection = self.lock()?;
81 Ok(connection
82 .query_row(
83 "SELECT message_id FROM messages
84 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
85 AND (sender_id IS NULL OR sender_id != ?3)
86 ORDER BY created_at ASC, message_id ASC LIMIT 1",
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 .optional()?)
95 }
96
97 /// Oldest-first page of the `limit` newest messages strictly older than `before` (all when `None`).
98 pub fn messages(
99 &self,
100 conversation_id: &str,
101 before: Option<DateTime<Utc>>,
102 limit: usize,
103 ) -> Result<Vec<MessageRecord>> {
104 let connection = self.lock()?;
105 let mut statement = connection.prepare_cached(&format!(
106 "SELECT {MESSAGE_COLUMNS} FROM messages
107 WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2)
108 ORDER BY created_at DESC, message_id DESC LIMIT ?3"
109 ))?;
110 let mut messages = statement
111 .query_map(
112 params![conversation_id, optional_to_millis(before), limit as i64],
113 message_from_row,
114 )?
115 .collect::<rusqlite::Result<Vec<_>>>()?;
116 messages.reverse();
117 Ok(messages)
118 }
119
120 pub fn messages_by_id(
121 &self,
122 conversation_id: &str,
123 message_ids: &[String],
124 ) -> Result<HashMap<String, MessageRecord>> {
125 let connection = self.lock()?;
126 let mut statement = connection.prepare_cached(&format!(
127 "SELECT {MESSAGE_COLUMNS} FROM messages
128 WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))"
129 ))?;
130 let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned());
131 let rows = statement.query_map(
132 params_from_iter([conversation_id, ids.as_str()]),
133 message_from_row,
134 )?;
135 let mut found = HashMap::new();
136 for row in rows {
137 let message = row?;
138 found.insert(message.message_id.clone(), message);
139 }
140 Ok(found)
141 }
142
143 pub fn display_names(&self, user_ids: &[String]) -> Result<HashMap<String, String>> {
144 if user_ids.is_empty() {
145 return Ok(HashMap::new());
146 }
147 let connection = self.lock()?;
148 let mut statement = connection.prepare_cached(
149 "SELECT value, COALESCE(
150 (SELECT display_name FROM chat_members
151 WHERE user_id = value AND display_name <> '' LIMIT 1),
152 (SELECT sender_name FROM messages
153 WHERE sender_id = value AND sender_name <> ''
154 ORDER BY created_at DESC LIMIT 1))
155 FROM json_each(?1)",
156 )?;
157 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
158 let rows = statement.query_map([ids], |row| {
159 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
160 })?;
161 let mut names = HashMap::new();
162 for row in rows {
163 if let (user_id, Some(name)) = row? {
164 names.insert(user_id, name);
165 }
166 }
167 Ok(names)
168 }
169
170 pub fn thread_has_sender(
171 &self,
172 conversation_id: &str,
173 root_id: &str,
174 user_id: &str,
175 ) -> Result<bool> {
176 let connection = self.lock()?;
177 Ok(connection.query_row(
178 "SELECT EXISTS (
179 SELECT 1 FROM messages
180 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
181 AND (message_id = ?2 OR reply_to_id = ?2))",
182 params![conversation_id, root_id, user_id],
183 |row| row.get(0),
184 )?)
185 }
186
187 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
188 let connection = self.lock()?;
189 let count: i64 = connection.query_row(
190 "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
191 [conversation_id],
192 |row| row.get(0),
193 )?;
194 Ok(count as usize)
195 }
196}
197
198fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
199 Ok(MessageRecord {
200 conversation_id: row.get(0)?,
201 message_id: row.get(1)?,
202 reply_to_id: row.get(2)?,
203 sender_id: row.get(3)?,
204 sender_name: row.get(4)?,
205 created_at: from_millis(row.get(5)?),
206 edited_at: optional_from_millis(row.get(6)?),
207 deleted: row.get(7)?,
208 body_html: row.get(8)?,
209 attachments_json: row.get(9)?,
210 reactions_json: row.get(10)?,
211 mentions_json: row.get(11)?,
212 sender_application_id: row.get(12)?,
213 })
214}