forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

comments.rs350 lines, 11.7 KiBHistoryRawDownload
1//! Comments on tasks. Posting is the caller's check (a member, not a viewer). Editing and deleting are
2//! checked here through `authz::authorize`, against the comment's own author, so the rule lives in one
3//! place: an author edits or deletes their own comment, and an admin may delete any comment. Deletion is
4//! soft: the row stays so the activity trail can name it, and lists skip it.
5
6use turso::Connection;
7
8use super::activity::{self, NewActivity};
9use super::events::{EventDraft, emit};
10use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
11use crate::authz::{Action, Actor, authorize};
12use crate::error::{Error, Result};
13use crate::limits::COMMENT_MAX;
14use crate::store::Store;
15use crate::time::now_stamp;
16
17/// One comment as stored.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Comment {
20 /// Comment id (ULID).
21 pub id: String,
22 /// The task it belongs to.
23 pub task_id: String,
24 /// The author's member id.
25 pub author: String,
26 /// Plain text, 1 to 10 000 characters.
27 pub body: String,
28 /// UTC stamp.
29 pub created_at: String,
30 /// UTC stamp of the last edit, if edited.
31 pub edited_at: Option<String>,
32 /// UTC stamp of deletion, if deleted (such rows are not listed).
33 pub deleted_at: Option<String>,
34}
35
36const COMMENT_COLS: &str = "id, task_id, author, body, created_at, edited_at, deleted_at";
37
38fn map_comment(row: &turso::Row) -> Result<Comment> {
39 Ok(Comment {
40 id: col_text(row, 0)?,
41 task_id: col_text(row, 1)?,
42 author: col_text(row, 2)?,
43 body: col_text(row, 3)?,
44 created_at: col_text(row, 4)?,
45 edited_at: col_opt_text(row, 5)?,
46 deleted_at: col_opt_text(row, 6)?,
47 })
48}
49
50fn clean_body(body: &str) -> Result<String> {
51 let body = crate::text::multi_line(body);
52 if body.is_empty() || body.chars().count() > COMMENT_MAX {
53 return Err(Error::Invalid(format!(
54 "comment must be 1 to {COMMENT_MAX} characters"
55 )));
56 }
57 Ok(body)
58}
59
60/// The member id behind an actor that has already passed `authorize`.
61fn member_sub(actor: &Actor) -> Result<&str> {
62 match actor {
63 Actor::Member { sub, .. } => Ok(sub),
64 Actor::Anonymous => Err(Error::Forbidden("sign in to continue".into())),
65 }
66}
67
68/// Reads a live comment of a live task of `board_id` with its task id and author. A comment whose task
69/// was deleted, or a comment of another board, is `NotFound`.
70async fn live_comment(conn: &Connection, board_id: &str, comment_id: &str) -> Result<Comment> {
71 fetch_opt(
72 conn,
73 "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \
74 JOIN tasks t ON t.id = c.task_id \
75 WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL AND t.deleted_at IS NULL",
76 (comment_id.to_owned(), board_id.to_owned()),
77 map_comment,
78 )
79 .await?
80 .ok_or(Error::NotFound)
81}
82
83impl Store {
84 /// Posts a comment on a live task of `board_id`, with its `comment_added` activity row.
85 pub async fn add_comment(
86 &self,
87 board_id: &str,
88 task_id: &str,
89 author: &str,
90 body: &str,
91 ) -> Result<Comment> {
92 let body = clean_body(body)?;
93 let conn = self.inner.conn.lock().await;
94 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
95 let outcome: Result<Comment> = async {
96 let live = fetch_opt(
97 &tx,
98 "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL",
99 (task_id.to_owned(), board_id.to_owned()),
100 |row| col_text(row, 0),
101 )
102 .await?;
103 if live.is_none() {
104 return Err(Error::NotFound);
105 }
106 let id = new_id();
107 tx.execute(
108 "INSERT INTO comments (id, task_id, author, body, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",
109 (id.clone(), task_id.to_owned(), author.to_owned(), body, now_stamp()),
110 )
111 .await
112 .map_err(db_err)?;
113 emit(
114 &tx,
115 EventDraft {
116 board_id,
117 task_id: Some(task_id),
118 kind: "commented",
119 column_id: None,
120 actor: Some(author),
121 subject: None,
122 detail: serde_json::json!({ "comment": id }),
123 },
124 )
125 .await?;
126 activity::record(
127 &tx,
128 NewActivity {
129 task_id: Some(task_id),
130 actor: Some(author),
131 subject: None,
132 kind: "comment_added",
133 detail: serde_json::json!({ "comment": id }),
134 },
135 )
136 .await?;
137 fetch_opt(
138 &tx,
139 &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"),
140 (id,),
141 map_comment,
142 )
143 .await?
144 .ok_or_else(|| Error::Database("comment vanished after insert".into()))
145 }
146 .await;
147 finish(tx, outcome).await
148 }
149
150 /// Live comments of a task of `board_id`, oldest first.
151 pub async fn list_comments(&self, board_id: &str, task_id: &str) -> Result<Vec<Comment>> {
152 let conn = self.read_conn().await;
153 fetch_all(
154 &conn,
155 "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \
156 JOIN tasks t ON t.id = c.task_id \
157 WHERE c.task_id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL ORDER BY c.created_at, c.id",
158 (task_id.to_owned(), board_id.to_owned()),
159 map_comment,
160 )
161 .await
162 }
163
164 /// Edits a comment. Only its author may, and only while still a member (`authz`).
165 pub async fn edit_comment(
166 &self,
167 board_id: &str,
168 comment_id: &str,
169 actor: &Actor,
170 body: &str,
171 ) -> Result<Comment> {
172 let body = clean_body(body)?;
173 let conn = self.inner.conn.lock().await;
174 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
175 let outcome: Result<Comment> = async {
176 let current = live_comment(&tx, board_id, comment_id).await?;
177 authorize(
178 actor,
179 &Action::EditComment {
180 author: current.author.clone(),
181 },
182 )?;
183 let sub = member_sub(actor)?;
184 tx.execute(
185 "UPDATE comments SET body = ?2, edited_at = ?3 WHERE id = ?1",
186 (comment_id.to_owned(), body, now_stamp()),
187 )
188 .await
189 .map_err(db_err)?;
190 activity::record(
191 &tx,
192 NewActivity {
193 task_id: Some(&current.task_id),
194 actor: Some(sub),
195 subject: None,
196 kind: "comment_edited",
197 detail: serde_json::json!({ "comment": comment_id }),
198 },
199 )
200 .await?;
201 fetch_opt(
202 &tx,
203 &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"),
204 (comment_id.to_owned(),),
205 map_comment,
206 )
207 .await?
208 .ok_or(Error::NotFound)
209 }
210 .await;
211 finish(tx, outcome).await
212 }
213
214 /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). Returns the id
215 /// of the task the comment belonged to, so the caller can tell that task's viewers.
216 pub async fn delete_comment(
217 &self,
218 board_id: &str,
219 comment_id: &str,
220 actor: &Actor,
221 ) -> Result<String> {
222 let conn = self.inner.conn.lock().await;
223 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
224 let outcome: Result<String> = async {
225 let current = live_comment(&tx, board_id, comment_id).await?;
226 authorize(
227 actor,
228 &Action::DeleteComment {
229 author: current.author.clone(),
230 },
231 )?;
232 let sub = member_sub(actor)?;
233 tx.execute(
234 "UPDATE comments SET deleted_at = ?2 WHERE id = ?1",
235 (comment_id.to_owned(), now_stamp()),
236 )
237 .await
238 .map_err(db_err)?;
239 activity::record(
240 &tx,
241 NewActivity {
242 task_id: Some(&current.task_id),
243 actor: Some(sub),
244 subject: Some(&current.author),
245 kind: "comment_deleted",
246 detail: serde_json::json!({ "comment": comment_id }),
247 },
248 )
249 .await?;
250 Ok(current.task_id)
251 }
252 .await;
253 finish(tx, outcome).await
254 }
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use crate::authz::Role;
261 use crate::store::activity::ActivityFilter;
262 use crate::store::tasks::NewTask;
263 use crate::store::test_support::seeded;
264
265 fn member(sub: &str, role: Role) -> Actor {
266 Actor::Member {
267 sub: sub.into(),
268 role,
269 im_admin: false,
270 disabled: false,
271 }
272 }
273
274 #[tokio::test]
275 async fn only_the_author_edits_and_admins_moderate() {
276 let (_dir, store, board) = seeded().await;
277 let tag = store.tags(&board).await.unwrap()[0].id.clone();
278 let column = store.columns(&board).await.unwrap()[0].id.clone();
279 let task = store
280 .create_task(
281 &board,
282 NewTask {
283 title: "Talk".into(),
284 description: String::new(),
285 column_id: column,
286 tag_id: tag,
287 deadline: None,
288 meeting_at: None,
289 assignees: vec![],
290 parent_id: None,
291 link: None,
292 },
293 "ada",
294 )
295 .await
296 .unwrap();
297 let comment = store
298 .add_comment(&board, &task.id, "bo", " hello ")
299 .await
300 .unwrap();
301 assert_eq!(comment.body, "hello");
302 // The admin cannot edit someone else's words, but can delete them.
303 let ada = member("ada", Role::Admin);
304 assert!(matches!(
305 store
306 .edit_comment(&board, &comment.id, &ada, "changed")
307 .await,
308 Err(Error::Forbidden(_))
309 ));
310 let bo = member("bo", Role::Member);
311 let edited = store
312 .edit_comment(&board, &comment.id, &bo, "edited")
313 .await
314 .unwrap();
315 assert!(edited.edited_at.is_some());
316 store
317 .delete_comment(&board, &comment.id, &ada)
318 .await
319 .unwrap();
320 assert!(
321 store
322 .list_comments(&board, &task.id)
323 .await
324 .unwrap()
325 .is_empty()
326 );
327 // The activity trail pages newest first with a keyset cursor.
328 let page = store
329 .list_recent(&board, &ActivityFilter::default(), None, 2)
330 .await
331 .unwrap();
332 assert_eq!(page.items.len(), 2);
333 let next = store
334 .list_recent(
335 &board,
336 &ActivityFilter::default(),
337 page.next_cursor.as_deref(),
338 200,
339 )
340 .await
341 .unwrap();
342 assert!(next.items.iter().all(|a| !page.items.contains(a)));
343 assert!(
344 store
345 .list_recent(&board, &ActivityFilter::default(), None, 0)
346 .await
347 .is_err()
348 );
349 }
350}