//! Comments on tasks. Posting is the caller's check (a member, not a viewer). Editing and deleting are //! checked here through `authz::authorize`, against the comment's own author, so the rule lives in one //! place: an author edits or deletes their own comment, and an admin may delete any comment. Deletion is //! soft: the row stays so the activity trail can name it, and lists skip it. use turso::Connection; use super::activity::{self, NewActivity}; use super::events::{EventDraft, emit}; use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::authz::{Action, Actor, authorize}; use crate::error::{Error, Result}; use crate::limits::COMMENT_MAX; use crate::store::Store; use crate::time::now_stamp; /// One comment as stored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Comment { /// Comment id (ULID). pub id: String, /// The task it belongs to. pub task_id: String, /// The author's member id. pub author: String, /// Plain text, 1 to 10 000 characters. pub body: String, /// UTC stamp. pub created_at: String, /// UTC stamp of the last edit, if edited. pub edited_at: Option, /// UTC stamp of deletion, if deleted (such rows are not listed). pub deleted_at: Option, } const COMMENT_COLS: &str = "id, task_id, author, body, created_at, edited_at, deleted_at"; fn map_comment(row: &turso::Row) -> Result { Ok(Comment { id: col_text(row, 0)?, task_id: col_text(row, 1)?, author: col_text(row, 2)?, body: col_text(row, 3)?, created_at: col_text(row, 4)?, edited_at: col_opt_text(row, 5)?, deleted_at: col_opt_text(row, 6)?, }) } fn clean_body(body: &str) -> Result { let body = crate::text::multi_line(body); if body.is_empty() || body.chars().count() > COMMENT_MAX { return Err(Error::Invalid(format!( "comment must be 1 to {COMMENT_MAX} characters" ))); } Ok(body) } /// The member id behind an actor that has already passed `authorize`. fn member_sub(actor: &Actor) -> Result<&str> { match actor { Actor::Member { sub, .. } => Ok(sub), Actor::Anonymous => Err(Error::Forbidden("sign in to continue".into())), } } /// Reads a live comment of a live task of `board_id` with its task id and author. A comment whose task /// was deleted, or a comment of another board, is `NotFound`. async fn live_comment(conn: &Connection, board_id: &str, comment_id: &str) -> Result { fetch_opt( conn, "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ JOIN tasks t ON t.id = c.task_id \ WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL AND t.deleted_at IS NULL", (comment_id.to_owned(), board_id.to_owned()), map_comment, ) .await? .ok_or(Error::NotFound) } impl Store { /// Posts a comment on a live task of `board_id`, with its `comment_added` activity row. pub async fn add_comment( &self, board_id: &str, task_id: &str, author: &str, body: &str, ) -> Result { let body = clean_body(body)?; let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let live = fetch_opt( &tx, "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", (task_id.to_owned(), board_id.to_owned()), |row| col_text(row, 0), ) .await?; if live.is_none() { return Err(Error::NotFound); } let id = new_id(); tx.execute( "INSERT INTO comments (id, task_id, author, body, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", (id.clone(), task_id.to_owned(), author.to_owned(), body, now_stamp()), ) .await .map_err(db_err)?; emit( &tx, EventDraft { board_id, task_id: Some(task_id), kind: "commented", column_id: None, actor: Some(author), subject: None, detail: serde_json::json!({ "comment": id }), }, ) .await?; activity::record( &tx, NewActivity { task_id: Some(task_id), actor: Some(author), subject: None, kind: "comment_added", detail: serde_json::json!({ "comment": id }), }, ) .await?; fetch_opt( &tx, &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), (id,), map_comment, ) .await? .ok_or_else(|| Error::Database("comment vanished after insert".into())) } .await; finish(tx, outcome).await } /// Live comments of a task of `board_id`, oldest first. pub async fn list_comments(&self, board_id: &str, task_id: &str) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ JOIN tasks t ON t.id = c.task_id \ WHERE c.task_id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL ORDER BY c.created_at, c.id", (task_id.to_owned(), board_id.to_owned()), map_comment, ) .await } /// Edits a comment. Only its author may, and only while still a member (`authz`). pub async fn edit_comment( &self, board_id: &str, comment_id: &str, actor: &Actor, body: &str, ) -> Result { let body = clean_body(body)?; let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let current = live_comment(&tx, board_id, comment_id).await?; authorize( actor, &Action::EditComment { author: current.author.clone(), }, )?; let sub = member_sub(actor)?; tx.execute( "UPDATE comments SET body = ?2, edited_at = ?3 WHERE id = ?1", (comment_id.to_owned(), body, now_stamp()), ) .await .map_err(db_err)?; activity::record( &tx, NewActivity { task_id: Some(¤t.task_id), actor: Some(sub), subject: None, kind: "comment_edited", detail: serde_json::json!({ "comment": comment_id }), }, ) .await?; fetch_opt( &tx, &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), (comment_id.to_owned(),), map_comment, ) .await? .ok_or(Error::NotFound) } .await; finish(tx, outcome).await } /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). Returns the id /// of the task the comment belonged to, so the caller can tell that task's viewers. pub async fn delete_comment( &self, board_id: &str, comment_id: &str, actor: &Actor, ) -> Result { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let current = live_comment(&tx, board_id, comment_id).await?; authorize( actor, &Action::DeleteComment { author: current.author.clone(), }, )?; let sub = member_sub(actor)?; tx.execute( "UPDATE comments SET deleted_at = ?2 WHERE id = ?1", (comment_id.to_owned(), now_stamp()), ) .await .map_err(db_err)?; activity::record( &tx, NewActivity { task_id: Some(¤t.task_id), actor: Some(sub), subject: Some(¤t.author), kind: "comment_deleted", detail: serde_json::json!({ "comment": comment_id }), }, ) .await?; Ok(current.task_id) } .await; finish(tx, outcome).await } } #[cfg(test)] mod tests { use super::*; use crate::authz::Role; use crate::store::activity::ActivityFilter; use crate::store::tasks::NewTask; use crate::store::test_support::seeded; fn member(sub: &str, role: Role) -> Actor { Actor::Member { sub: sub.into(), role, im_admin: false, disabled: false, } } #[tokio::test] async fn only_the_author_edits_and_admins_moderate() { let (_dir, store, board) = seeded().await; let tag = store.tags(&board).await.unwrap()[0].id.clone(); let column = store.columns(&board).await.unwrap()[0].id.clone(); let task = store .create_task( &board, NewTask { title: "Talk".into(), description: String::new(), column_id: column, tag_id: tag, deadline: None, meeting_at: None, assignees: vec![], parent_id: None, link: None, }, "ada", ) .await .unwrap(); let comment = store .add_comment(&board, &task.id, "bo", " hello ") .await .unwrap(); assert_eq!(comment.body, "hello"); // The admin cannot edit someone else's words, but can delete them. let ada = member("ada", Role::Admin); assert!(matches!( store .edit_comment(&board, &comment.id, &ada, "changed") .await, Err(Error::Forbidden(_)) )); let bo = member("bo", Role::Member); let edited = store .edit_comment(&board, &comment.id, &bo, "edited") .await .unwrap(); assert!(edited.edited_at.is_some()); store .delete_comment(&board, &comment.id, &ada) .await .unwrap(); assert!( store .list_comments(&board, &task.id) .await .unwrap() .is_empty() ); // The activity trail pages newest first with a keyset cursor. let page = store .list_recent(&board, &ActivityFilter::default(), None, 2) .await .unwrap(); assert_eq!(page.items.len(), 2); let next = store .list_recent( &board, &ActivityFilter::default(), page.next_cursor.as_deref(), 200, ) .await .unwrap(); assert!(next.items.iter().all(|a| !page.items.contains(a))); assert!( store .list_recent(&board, &ActivityFilter::default(), None, 0) .await .is_err() ); } }