| 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"; |
| 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) |
| 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 | ))?; |
| 30 | for message in messages { |
| 31 | upsert.execute(params![ |
| 32 | message.conversation_id, |
| 33 | message.message_id, |
| 34 | message.reply_to_id, |
| 35 | message.sender_id, |
| 36 | message.sender_name, |
| 37 | to_millis(message.created_at), |
| 38 | optional_to_millis(message.edited_at), |
| 39 | message.deleted, |
| 40 | message.body_html, |
| 41 | message.attachments_json, |
| 42 | message.reactions_json, |
| 43 | message.mentions_json, |
| 44 | ])?; |
| 45 | index_message(&transaction, message)?; |
| 46 | } |
| 47 | } |
| 48 | Ok(transaction.commit()?) |
| 49 | } |
| 50 | |
| 51 | pub fn count_messages_after( |
| 52 | &self, |
| 53 | conversation_id: &str, |
| 54 | after: Option<DateTime<Utc>>, |
| 55 | not_from_user_id: &str, |
| 56 | ) -> Result<usize> { |
| 57 | let connection = self.lock()?; |
| 58 | let count: i64 = connection.query_row( |
| 59 | "SELECT COUNT(*) FROM messages |
| 60 | WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2 |
| 61 | AND (sender_id IS NULL OR sender_id != ?3)", |
| 62 | params![ |
| 63 | conversation_id, |
| 64 | optional_to_millis(after).unwrap_or(i64::MIN), |
| 65 | not_from_user_id |
| 66 | ], |
| 67 | |row| row.get(0), |
| 68 | )?; |
| 69 | Ok(count as usize) |
| 70 | } |
| 71 | |
| 72 | pub fn first_message_after_from_others( |
| 73 | &self, |
| 74 | conversation_id: &str, |
| 75 | after: Option<DateTime<Utc>>, |
| 76 | not_from_user_id: &str, |
| 77 | ) -> Result<Option<String>> { |
| 78 | let connection = self.lock()?; |
| 79 | Ok(connection |
| 80 | .query_row( |
| 81 | "SELECT message_id FROM messages |
| 82 | WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2 |
| 83 | AND (sender_id IS NULL OR sender_id != ?3) |
| 84 | ORDER BY created_at ASC, message_id ASC LIMIT 1", |
| 85 | params![ |
| 86 | conversation_id, |
| 87 | optional_to_millis(after).unwrap_or(i64::MIN), |
| 88 | not_from_user_id |
| 89 | ], |
| 90 | |row| row.get(0), |
| 91 | ) |
| 92 | .optional()?) |
| 93 | } |
| 94 | |
| 95 | /// Oldest-first page of the `limit` newest messages strictly older than `before` (all when `None`). |
| 96 | pub fn messages( |
| 97 | &self, |
| 98 | conversation_id: &str, |
| 99 | before: Option<DateTime<Utc>>, |
| 100 | limit: usize, |
| 101 | ) -> Result<Vec<MessageRecord>> { |
| 102 | let connection = self.lock()?; |
| 103 | let mut statement = connection.prepare_cached(&format!( |
| 104 | "SELECT {MESSAGE_COLUMNS} FROM messages |
| 105 | WHERE conversation_id = ?1 AND (?2 IS NULL OR created_at < ?2) |
| 106 | ORDER BY created_at DESC, message_id DESC LIMIT ?3" |
| 107 | ))?; |
| 108 | let mut messages = statement |
| 109 | .query_map( |
| 110 | params![conversation_id, optional_to_millis(before), limit as i64], |
| 111 | message_from_row, |
| 112 | )? |
| 113 | .collect::<rusqlite::Result<Vec<_>>>()?; |
| 114 | messages.reverse(); |
| 115 | Ok(messages) |
| 116 | } |
| 117 | |
| 118 | pub fn messages_by_id( |
| 119 | &self, |
| 120 | conversation_id: &str, |
| 121 | message_ids: &[String], |
| 122 | ) -> Result<HashMap<String, MessageRecord>> { |
| 123 | let connection = self.lock()?; |
| 124 | let mut statement = connection.prepare_cached(&format!( |
| 125 | "SELECT {MESSAGE_COLUMNS} FROM messages |
| 126 | WHERE conversation_id = ?1 AND message_id IN (SELECT value FROM json_each(?2))" |
| 127 | ))?; |
| 128 | let ids = serde_json::to_string(message_ids).unwrap_or_else(|_| "[]".to_owned()); |
| 129 | let rows = statement.query_map( |
| 130 | params_from_iter([conversation_id, ids.as_str()]), |
| 131 | message_from_row, |
| 132 | )?; |
| 133 | let mut found = HashMap::new(); |
| 134 | for row in rows { |
| 135 | let message = row?; |
| 136 | found.insert(message.message_id.clone(), message); |
| 137 | } |
| 138 | Ok(found) |
| 139 | } |
| 140 | |
| 141 | pub fn message_count(&self, conversation_id: &str) -> Result<usize> { |
| 142 | let connection = self.lock()?; |
| 143 | let count: i64 = connection.query_row( |
| 144 | "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1", |
| 145 | [conversation_id], |
| 146 | |row| row.get(0), |
| 147 | )?; |
| 148 | Ok(count as usize) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> { |
| 153 | Ok(MessageRecord { |
| 154 | conversation_id: row.get(0)?, |
| 155 | message_id: row.get(1)?, |
| 156 | reply_to_id: row.get(2)?, |
| 157 | sender_id: row.get(3)?, |
| 158 | sender_name: row.get(4)?, |
| 159 | created_at: from_millis(row.get(5)?), |
| 160 | edited_at: optional_from_millis(row.get(6)?), |
| 161 | deleted: row.get(7)?, |
| 162 | body_html: row.get(8)?, |
| 163 | attachments_json: row.get(9)?, |
| 164 | reactions_json: row.get(10)?, |
| 165 | mentions_json: row.get(11)?, |
| 166 | }) |
| 167 | } |