use common::{ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, error::{Error, Field, Problem}, model::{CallLog, Edit, Id, Message, MessageHit, Quote, Reaction, Reply, SnippetMessage}, time::now_ms, }; use super::{Connection, Reader, all, attachment, community, maybe, one, poll, run, snippet, user}; use crate::error::{ServerError, ensure_with}; const SEARCH_LIMIT: u32 = 200; const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32; const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.created_at, m.body, m.edited, m.reply_to, r.id, r.user_id, COALESCE(NULLIF(r.body, ''), (SELECT question FROM poll p WHERE p.message_id = r.id), r.body), (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned, m.deleted_at IS NOT NULL, r.deleted_at IS NOT NULL FROM message m LEFT JOIN message r ON r.id = m.reply_to"; fn row(r: &mut Reader) -> Result { let id = r.get()?; let user_id = r.get()?; let community_id = r.get()?; let created_at = r.get()?; let body = r.get()?; let edited = r.get()?; let reply_to: Option = r.get()?; let reply_id: Option = r.get()?; let reply_user_id: Option = r.get()?; let reply_body: Option = r.get()?; let reply_attachments: u32 = r.get()?; let call: Option = r.get()?; let call_seconds: u64 = r.get()?; let pinned = r.get()?; let deleted = r.get()?; let reply_deleted: bool = r.get()?; let reply = match (reply_id, reply_user_id, reply_body) { (Some(message_id), Some(user_id), Some(body)) => { let quote = Quote { message_id, user_id, body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(), attachments: reply_attachments, }; Some(if reply_deleted { Reply::Deleted(Some(quote)) } else { Reply::Quote(quote) }) } _ => reply_to.map(|_| Reply::Deleted(None)), }; Ok(Message { id, user_id, community_id, created_at, body, attachments: Vec::new(), reactions: Vec::new(), reply, snippet: None, poll: None, edited, pinned, deleted, call: call.and_then(|text| CallLog::parse(&text, call_seconds)), }) } async fn reactions(message_id: Id, db: &Connection) -> Result, ServerError> { let rows: Vec<(String, Id)> = all( db, "SELECT emoji, user_id FROM reaction WHERE message_id = ?1 ORDER BY emoji, user_id", (message_id,), |r| Ok((r.get()?, r.get()?)), ) .await?; let mut reactions: Vec = Vec::new(); for (emoji, user_id) in rows { match reactions .last_mut() .filter(|reaction| reaction.emoji == emoji) { Some(reaction) => reaction.user_ids.push(user_id), None => reactions.push(Reaction { emoji, user_ids: vec![user_id], }), } } Ok(reactions) } async fn insert( user_id: Id, community_id: Id, body: &str, reply_to: Option, db: &Connection, ) -> Result { one( db, "INSERT INTO message (community_id, user_id, created_at, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", (community_id, user_id, now_ms(), body, reply_to), |r| r.get(), ) .await } pub async fn community_of(message_id: Id, db: &Connection) -> Result { one( db, "SELECT community_id FROM message WHERE id = ?1", (message_id,), |r| r.get(), ) .await } pub async fn create_call_log( community_id: Id, user_id: Id, call: CallLog, db: &Connection, ) -> Result { let id: Id = one( db, "INSERT INTO message (community_id, user_id, created_at, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5) RETURNING id", (community_id, user_id, now_ms(), call.as_str(), call.seconds()), |r| r.get(), ) .await?; read(id, db).await } pub async fn create( user_id: Id, community_id: Id, body: &str, attachments: &[Id], reply_to: Option, db: &Connection, ) -> Result { let id = insert(user_id, community_id, body, reply_to, db).await?; attachment::bind(id, user_id, community_id, attachments, db).await?; read(id, db).await } pub async fn read(id: Id, db: &Connection) -> Result { let message = load(id, db).await?; ensure_with(!message.deleted, Error::NotFound)?; Ok(message) } async fn load(id: Id, db: &Connection) -> Result { let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?; message.reactions = reactions(id, db).await?; message.poll = poll::of(id, db).await?; message.attachments = attachment::of_message(id, None, db).await?; message.snippet = snippet::of(id, db).await?; Ok(message) } async fn read_all(ids: Vec, db: &Connection) -> Result, ServerError> { let mut messages = Vec::new(); for id in ids { messages.push(load(id, db).await?); } Ok(messages) } pub async fn read_page( community_id: Id, before: Option, with_deleted: bool, db: &Connection, ) -> Result, ServerError> { let mut ids = all( db, "SELECT id FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) AND (?4 OR deleted_at IS NULL) ORDER BY id DESC LIMIT ?3", (community_id, before, PAGE_LIMIT, with_deleted), |r| r.get(), ) .await?; ids.reverse(); read_all(ids, db).await } pub async fn pinned(community_id: Id, db: &Connection) -> Result, ServerError> { let ids = all( db, "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 AND deleted_at IS NULL ORDER BY id DESC", (community_id,), |r| r.get(), ) .await?; read_all(ids, db).await } pub async fn create_poll( user_id: Id, poll: &common::call::CreatePoll, db: &Connection, ) -> Result { let id = insert(user_id, poll.community_id, "", None, db).await?; poll::create(id, poll, db).await?; read(id, db).await } pub async fn vote( message_id: Id, user_id: Id, positions: &[u32], db: &Connection, ) -> Result { poll::set_votes(message_id, user_id, positions, db).await?; read(message_id, db).await } pub async fn close_poll(message_id: Id, db: &Connection) -> Result { poll::close(message_id, db).await?; read(message_id, db).await } pub async fn react( message_id: Id, user_id: Id, emoji: &str, db: &Connection, ) -> Result { let removed = run( db, "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", (message_id, user_id, emoji), ) .await?; if removed == 0 { run( db, "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", (message_id, user_id, emoji), ) .await?; } read(message_id, db).await } pub async fn pin(message_id: Id, pinned: bool, db: &Connection) -> Result { run( db, "UPDATE message SET pinned = ?2 WHERE id = ?1", (message_id, pinned), ) .await?; read(message_id, db).await } pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result { run( db, "INSERT INTO message_edit (message_id, body, edited_at) SELECT id, body, ?2 FROM message WHERE id = ?1 AND deleted_at IS NULL", (message_id, now_ms()), ) .await?; ensure_with( run( db, "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1 AND deleted_at IS NULL", (message_id, body), ) .await? == 1, Error::NotFound, )?; read(message_id, db).await } pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> { ensure_with( run( db, "UPDATE message SET deleted_at = ?2, pinned = 0 WHERE id = ?1 AND deleted_at IS NULL", (message_id, now_ms()), ) .await? == 1, Error::NotFound, ) } pub async fn edits(message_id: Id, db: &Connection) -> Result, ServerError> { all( db, "SELECT body, edited_at FROM message_edit WHERE message_id = ?1 ORDER BY id DESC", (message_id,), |r| { Ok(Edit { body: r.get()?, edited_at: r.get()?, }) }, ) .await } pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result, ServerError> { all( db, "DELETE FROM message WHERE user_id = ?1 RETURNING community_id, id", (user_id,), |r| Ok((r.get()?, r.get()?)), ) .await } pub async fn delete_before( cutoff: u64, limit: u32, db: &Connection, ) -> Result, ServerError> { all( db, "DELETE FROM message WHERE id IN (SELECT id FROM message WHERE created_at < ?1 ORDER BY id LIMIT ?2) RETURNING community_id, id", (cutoff, limit), |r| Ok((r.get()?, r.get()?)), ) .await } pub async fn search( text: Option<&str>, user_id: Option, community_id: Option, after_ms: Option, before_ms: Option, db: &Connection, ) -> Result, ServerError> { let ids: Vec = all( db, "SELECT id FROM message WHERE deleted_at IS NULL AND (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR created_at >= ?4) AND (?5 IS NULL OR created_at < ?5) ORDER BY id DESC LIMIT ?6", ( text, user_id, community_id, after_ms.map(|ms| ms as i64), before_ms.map(|ms| ms as i64), SEARCH_LIMIT, ), |r| r.get(), ) .await?; let mut hits = Vec::new(); for id in ids { let message = read(id, db).await?; let community = community::label(message.community_id, db).await?; let author = user::read(message.user_id, db).await?; hits.push(MessageHit { message, community, author: Some(author), }); } Ok(hits) } async fn origin(sources: &[Message], db: &Connection) -> Result, ServerError> { let Some(first) = sources.first() else { return Ok(None); }; if sources .iter() .any(|source| source.community_id != first.community_id) { return Ok(None); } maybe( db, "SELECT name FROM community WHERE id = ?1 AND kind = ?2", (first.community_id, community::Kind::Group.as_str()), |r| r.get(), ) .await } async fn entry(source: &Message, db: &Connection) -> Result { let author = user::read(source.user_id, db).await?; Ok(SnippetMessage { id: source.id, user_id: author.id, username: author.username, avatar_id: author.avatar_id, created_at: source.created_at, body: source.body.clone(), attachments: source.attachments.clone(), poll: source.poll.clone(), }) } pub async fn forward_copies( user_id: Id, community_id: Id, sources: &[Message], db: &Connection, ) -> Result, ServerError> { let mut created = Vec::new(); for source in sources { let id = insert(user_id, community_id, &source.body, None, db).await?; for attachment in &source.attachments { attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?; } if let Some(inner) = &source.snippet { snippet::write( id, user_id, community_id, inner.origin.as_deref(), &inner.messages, db, ) .await?; } created.push(read(id, db).await?); } Ok(created) } pub async fn forward_snippet( user_id: Id, community_id: Id, sources: &[Message], db: &Connection, ) -> Result, ServerError> { let mut entries = Vec::new(); for source in sources { match &source.snippet { Some(inner) => entries.extend(inner.messages.iter().cloned()), None => entries.push(entry(source, db).await?), } } if entries.len() > MAXIMUM_FORWARD_MESSAGES { return Err(Error::Invalid { field: Field::Forward, problem: Problem::Length { min: 1, max: MAXIMUM_FORWARD_MESSAGES as u64, actual: entries.len() as u64, }, } .into()); } let origin = origin(sources, db).await?; let id = insert(user_id, community_id, "", None, db).await?; snippet::write(id, user_id, community_id, origin.as_deref(), &entries, db).await?; Ok(vec![read(id, db).await?]) } #[cfg(test)] mod tests { use common::model::Role; use common::model::Reply; use super::{create, delete, edits, forward_snippet, read, read_page, update}; use crate::{ db::{community, user}, test, }; #[tokio::test] async fn read_page_orders_and_pages() { let db = test::db().await; let conn = db.lock().await.unwrap(); let user_1 = user::create("Tahinli", "hash", Role::User, &conn) .await .unwrap(); let user_2 = user::create("Not Tahinli", "hash", Role::User, &conn) .await .unwrap(); let community = community::create(community::Kind::Group, "Tahinli", &conn) .await .unwrap(); let message_1 = create(user_1.id, community, "Tahinli", &[], None, &conn) .await .unwrap(); let message_2 = create(user_2.id, community, "Tahinli", &[], None, &conn) .await .unwrap(); let message_3 = create(user_2.id, community, "Tahinli", &[], None, &conn) .await .unwrap(); let newest = read_page(community, None, false, &conn).await.unwrap(); let older = read_page(community, Some(message_3.id), false, &conn) .await .unwrap(); assert_eq!( vec![message_1.clone(), message_2.clone(), message_3], newest ); assert_eq!(vec![message_1, message_2], older); } #[tokio::test] async fn deleted_and_edited_stay_for_builders_only() { let db = test::db().await; let conn = db.lock().await.unwrap(); let author = user::create("Tahinli", "hash", Role::User, &conn) .await .unwrap(); let community = community::create(community::Kind::Group, "Tahinli", &conn) .await .unwrap(); let original = create(author.id, community, "first", &[], None, &conn) .await .unwrap(); let reply = create(author.id, community, "reply", &[], Some(original.id), &conn) .await .unwrap(); update(original.id, "second", &conn).await.unwrap(); delete(original.id, &conn).await.unwrap(); assert!(read(original.id, &conn).await.is_err()); assert!(delete(original.id, &conn).await.is_err()); assert_eq!( vec![reply.id], read_page(community, None, false, &conn) .await .unwrap() .iter() .map(|message| message.id) .collect::>() ); let all = read_page(community, None, true, &conn).await.unwrap(); assert!(all[0].deleted && all[0].body == "second"); assert!( matches!(&all[1].reply, Some(Reply::Deleted(Some(quote))) if quote.body == "second") ); let mut redacted = all[1].reply.clone().unwrap(); redacted.redact(); assert_eq!(Reply::Deleted(None), redacted); assert_eq!( vec!["first".to_string()], edits(original.id, &conn) .await .unwrap() .into_iter() .map(|edit| edit.body) .collect::>() ); } #[tokio::test] async fn forward_two_as_snippet() { let db = test::db().await; let conn = db.lock().await.unwrap(); let user = user::create("Tahinli", "hash", Role::User, &conn) .await .unwrap(); let community = community::create(community::Kind::Group, "Tahinli", &conn) .await .unwrap(); let first = create(user.id, community, "First", &[], None, &conn) .await .unwrap(); let second = create(user.id, community, "Second", &[], None, &conn) .await .unwrap(); let created = forward_snippet(user.id, community, &[first, second], &conn) .await .unwrap(); assert_eq!(1, created.len()); assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); } }