| 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"; |
| 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) |
| 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 thread_has_sender( |
| 144 | &self, |
| 145 | conversation_id: &str, |
| 146 | root_id: &str, |
| 147 | user_id: &str, |
| 148 | ) -> Result<bool> { |
| 149 | let connection = self.lock()?; |
| 150 | Ok(connection.query_row( |
| 151 | "SELECT EXISTS ( |
| 152 | SELECT 1 FROM messages |
| 153 | WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0 |
| 154 | AND (message_id = ?2 OR reply_to_id = ?2))", |
| 155 | params![conversation_id, root_id, user_id], |
| 156 | |row| row.get(0), |
| 157 | )?) |
| 158 | } |
| 159 | |
| 160 | pub fn message_count(&self, conversation_id: &str) -> Result<usize> { |
| 161 | let connection = self.lock()?; |
| 162 | let count: i64 = connection.query_row( |
| 163 | "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1", |
| 164 | [conversation_id], |
| 165 | |row| row.get(0), |
| 166 | )?; |
| 167 | Ok(count as usize) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> { |
| 172 | Ok(MessageRecord { |
| 173 | conversation_id: row.get(0)?, |
| 174 | message_id: row.get(1)?, |
| 175 | reply_to_id: row.get(2)?, |
| 176 | sender_id: row.get(3)?, |
| 177 | sender_name: row.get(4)?, |
| 178 | created_at: from_millis(row.get(5)?), |
| 179 | edited_at: optional_from_millis(row.get(6)?), |
| 180 | deleted: row.get(7)?, |
| 181 | body_html: row.get(8)?, |
| 182 | attachments_json: row.get(9)?, |
| 183 | reactions_json: row.get(10)?, |
| 184 | mentions_json: row.get(11)?, |
| 185 | sender_application_id: row.get(12)?, |
| 186 | }) |
| 187 | } |