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