Files
sorsfonalak/services/forum/src/routes/threads.rs
T

582 lines
21 KiB
Rust
Raw Normal View History

//! Threads: reading one, starting one, replying, read marks, following, and
//! the moderators' lock, pin, removal and the admin's restore.
use std::collections::HashMap;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;
use super::home::viewer_json;
use super::moderation::{self, Action};
use super::{Body, IdPath, St, authors, has_purchase, may_read, rfc3339};
use crate::AppState;
use crate::auth::{Member, Viewer};
use crate::error::{ApiError, ApiResult};
use crate::rank::{self, COLLAPSE_SCORE};
use crate::text;
/// The positive reactions; each is +1, the ⌄ (`down`) is -1.
pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct ThreadRow {
pub id: i64,
pub topic_slug: String,
pub topic_name: String,
pub visibility: String,
pub listening: bool,
pub author_id: Option<Uuid>,
pub title: String,
pub intent: Option<String>,
pub created_at: OffsetDateTime,
pub locked: bool,
pub pinned: bool,
pub deleted_at: Option<OffsetDateTime>,
pub delete_reason: Option<String>,
}
const THREAD_SELECT: &str = "SELECT th.id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \
th.delete_reason \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id";
/// A thread the viewer may read (deleted ones too): 404 when it does not
/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor.
pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
.bind(id)
.fetch_optional(db)
.await?
.ok_or(ApiError::NotFound("thread"))?;
if !may_read(viewer, &thread.visibility) {
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
}
Ok(thread)
}
/// A thread that can take new posts and reactions: not removed, and not
/// locked (moderators may still write in a locked one).
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
let thread = readable_thread(db, viewer, id).await?;
if thread.deleted_at.is_some() {
return Err(ApiError::NotFound("thread"));
}
if thread.locked && !viewer.is_moderator() {
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
}
Ok(thread)
}
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct PostRow {
pub id: i64,
pub thread_id: i64,
pub parent_id: Option<i64>,
pub is_opening: bool,
pub author_id: Option<Uuid>,
pub body: String,
pub created_at: OffsetDateTime,
pub edited_at: Option<OffsetDateTime>,
pub helped_at: Option<OffsetDateTime>,
pub deleted_at: Option<OffsetDateTime>,
pub deleted_by: Option<Uuid>,
pub delete_reason: Option<String>,
}
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
delete_reason";
/// Posts as the thread page shows them: authors, reactions, the viewer's own
/// reaction. A removed post keeps its place with the reason; only
/// moderators still see its text.
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
let counts: Vec<(i64, String, i64)> =
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
.bind(&ids)
.fetch_all(db)
.await?;
let mut by_post: HashMap<i64, HashMap<String, i64>> = HashMap::new();
for (post, kind, n) in counts {
by_post.entry(post).or_default().insert(kind, n);
}
let mine: HashMap<i64, String> = match viewer.user_id() {
Some(me) => {
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
.bind(&ids)
.bind(me)
.fetch_all(db)
.await?
.into_iter()
.collect()
}
None => HashMap::new(),
};
let moderator = viewer.is_moderator();
Ok(posts
.iter()
.map(|p| {
let counts = by_post.remove(&p.id).unwrap_or_default();
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
let down = counts.get("down").copied().unwrap_or(0);
let score = positive - down;
let deleted = p.deleted_at.map(|_| {
json!({
"by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id,
"reason": p.delete_reason,
})
});
let mut post = json!({
"id": p.id,
"parent_id": p.parent_id,
"is_opening": p.is_opening,
"author": p.author_id.and_then(|id| people.get(&id).cloned()),
"own": p.author_id.is_some() && p.author_id == viewer.user_id(),
"body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None },
"deleted": deleted,
"created_at": rfc3339(p.created_at),
"edited_at": p.edited_at.map(rfc3339),
"helped": p.helped_at.is_some(),
"reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0))))
.collect::<serde_json::Map<_, _>>(),
"score": score,
"collapsed": score <= COLLAPSE_SCORE,
"mine": mine.get(&p.id),
});
if moderator {
post["down"] = json!(down);
}
post
})
.collect())
}
/// A thread with all its posts, oldest first.
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
let thread = readable_thread(&state.db, &viewer, id).await?;
let people = authors(&state.db, thread.author_id).await?;
let moderator = viewer.is_moderator();
let mut out = json!({
"viewer": viewer_json(&viewer),
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
});
if thread.deleted_at.is_some() && !moderator {
out["posts"] = json!([]);
return Ok(Json(out));
}
let posts: Vec<PostRow> =
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
.bind(id)
.fetch_all(&state.db)
.await?;
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
let now = OffsetDateTime::now_utc();
let (following, last_read) = match viewer.user_id() {
Some(me) => {
let following: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
.bind(me)
.bind(id)
.fetch_one(&state.db)
.await?;
let last_read: Option<i64> =
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
.bind(me)
.bind(id)
.fetch_optional(&state.db)
.await?;
(following, last_read)
}
None => (false, None),
};
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
let open = thread.deleted_at.is_none() && (!thread.locked || moderator);
out["access"] = json!({
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()),
"can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
"is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(),
"following": following,
"last_read_post_id": last_read,
});
Ok(Json(out))
}
fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
json!({
"id": thread.id,
"slug": text::slug(&thread.title),
"title": thread.title,
"intent": thread.intent,
"topic": {
"slug": thread.topic_slug, "name": thread.topic_name,
"visibility": thread.visibility, "listening": thread.listening,
},
"author": author,
"created_at": rfc3339(thread.created_at),
"locked": thread.locked,
"pinned": thread.pinned,
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
})
}
/// Too fast, or past a newcomer's daily limit (lifted by a purchase and for moderators).
async fn check_limits(state: &AppState, viewer: &Viewer, member: &Member, new_thread: bool) -> ApiResult<()> {
let db = &state.db;
let recent: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM forum.posts \
WHERE author_id = $1 AND created_at > now() - make_interval(secs => $2))",
)
.bind(member.user_id)
.bind(f64::from(state.flood_secs))
.fetch_one(db)
.await?;
if recent {
return Err(ApiError::Limited("Várj pár másodpercet a következő hozzászólással.".into()));
}
if viewer.is_moderator() || !member.rank(OffsetDateTime::now_utc()).is_newcomer() {
return Ok(());
}
let (threads, posts): (i64, i64) = sqlx::query_as(
"SELECT count(*) FILTER (WHERE is_opening), count(*) FROM forum.posts \
WHERE author_id = $1 AND created_at > now() - interval '24 hours'",
)
.bind(member.user_id)
.fetch_one(db)
.await?;
let over =
if new_thread { threads >= rank::NEWCOMER_THREADS_PER_DAY } else { posts >= rank::NEWCOMER_POSTS_PER_DAY };
if over && !has_purchase(db, member.user_id).await? {
return Err(ApiError::Limited(if new_thread {
format!(
"Új tagként naponta legfeljebb {} szálat nyithatsz. Holnap újra lehet.",
rank::NEWCOMER_THREADS_PER_DAY
)
} else {
format!(
"Új tagként naponta legfeljebb {} hozzászólást írhatsz. Holnap újra lehet.",
rank::NEWCOMER_POSTS_PER_DAY
)
}));
}
Ok(())
}
#[derive(Deserialize)]
pub struct CreateThread {
topic: String,
title: String,
body: String,
#[serde(default)]
intent: Option<String>,
}
/// Starts a thread with its opening post; the author follows it.
pub async fn create(
State(state): St,
viewer: Viewer,
WithRejection(Json(req), _): Body<CreateThread>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?;
let topic: Option<(i16, String, bool)> =
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1")
.bind(&req.topic)
.fetch_optional(&state.db)
.await?;
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
if !may_read(&viewer, &visibility) {
return Err(ApiError::bad("Ismeretlen téma."));
}
let title = text::title(&req.title)?;
let body = text::body(&req.body)?;
let intent = match req.intent.as_deref() {
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
None | Some("") => listening.then(|| "listen".to_string()),
Some(_) => return Err(ApiError::bad("Ismeretlen szándék.")),
};
check_limits(&state, &viewer, member, true).await?;
let mut tx = state.db.begin().await?;
let thread_id: i64 = sqlx::query_scalar(
"INSERT INTO forum.threads (topic_id, author_id, title, intent) VALUES ($1, $2, $3, $4) RETURNING id",
)
.bind(topic_id)
.bind(member.user_id)
.bind(&title)
.bind(&intent)
.fetch_one(&mut *tx)
.await?;
let post_id: i64 = sqlx::query_scalar(
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, $3) RETURNING id",
)
.bind(thread_id)
.bind(member.user_id)
.bind(&body)
.fetch_one(&mut *tx)
.await?;
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
tx.commit().await?;
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
}
/// After a post: the author's count, following the thread, and the read mark
/// up to their own post.
async fn after_post(
tx: &mut sqlx::PgConnection,
author: Uuid,
thread_id: i64,
post_id: i64,
) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1")
.bind(author)
.execute(&mut *tx)
.await?;
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(author)
.bind(thread_id)
.execute(&mut *tx)
.await?;
upsert_read(&mut *tx, author, thread_id, post_id).await
}
async fn upsert_read(
db: impl sqlx::PgExecutor<'_>,
user: Uuid,
thread_id: i64,
post_id: i64,
) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \
ON CONFLICT (user_id, thread_id) DO UPDATE \
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
)
.bind(user)
.bind(thread_id)
.bind(post_id)
.execute(db)
.await?;
Ok(())
}
#[derive(Deserialize)]
pub struct Reply {
body: String,
/// The post answered; a reply to a reply goes under the same first-level
/// post (two levels at most), a reply to the opening post is first-level.
#[serde(default)]
parent_id: Option<i64>,
}
pub async fn reply(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Reply>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let member = viewer.require_writer()?;
open_thread(&state.db, &viewer, id).await?;
let body = text::body(&req.body)?;
let parent = match req.parent_id {
None => None,
Some(parent_id) => {
let parent: Option<(Option<i64>, bool, bool)> = sqlx::query_as(
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
)
.bind(parent_id)
.bind(id)
.fetch_optional(&state.db)
.await?;
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
if deleted {
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
}
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
}
};
check_limits(&state, &viewer, member, false).await?;
let mut tx = state.db.begin().await?;
let post: PostRow = sqlx::query_as(&format!(
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, $4) RETURNING {POST_COLUMNS}"
))
.bind(id)
.bind(member.user_id)
.bind(parent)
.bind(&body)
.fetch_one(&mut *tx)
.await?;
sqlx::query("UPDATE forum.threads SET last_post_at = now(), reply_count = reply_count + 1 WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
after_post(&mut tx, member.user_id, id, post.id).await?;
tx.commit().await?;
crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await;
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
Ok((StatusCode::CREATED, Json(post)))
}
#[derive(Deserialize)]
pub struct ReadMark {
post_id: i64,
}
/// Read up to that post (never backwards).
pub async fn mark_read(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReadMark>,
) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
readable_thread(&state.db, &viewer, id).await?;
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
readable_thread(&state.db, &viewer, id).await?;
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
.bind(member.user_id)
.bind(id)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
let member = viewer.require_member()?;
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
.bind(member.user_id)
.bind(id)
.execute(&state.db)
.await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct ThreadChange {
#[serde(default)]
locked: Option<bool>,
#[serde(default)]
pinned: Option<bool>,
}
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
pub async fn update(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ThreadChange>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let thread = readable_thread(&state.db, &viewer, id).await?;
let mut tx = state.db.begin().await?;
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
.bind(id)
.bind(locked)
.execute(&mut *tx)
.await?;
let action = if locked { Action::Lock } else { Action::Unlock };
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
}
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
.bind(id)
.bind(pinned)
.execute(&mut *tx)
.await?;
let action = if pinned { Action::Pin } else { Action::Unpin };
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
}
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
pub struct Reason {
#[serde(default)]
pub reason: Option<String>,
}
/// A moderator removes a whole thread; its place keeps the reason.
pub async fn remove(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Reason>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let thread = readable_thread(&state.db, &viewer, id).await?;
if thread.deleted_at.is_some() {
return Ok(StatusCode::NO_CONTENT);
}
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
.bind(id)
.bind(moderator.id)
.bind(&reason)
.execute(&mut *tx)
.await?;
moderation::record(
&mut *tx,
moderator.id,
Action::DeleteThread,
thread.author_id,
Some(id),
None,
Some(&reason),
None,
)
.await?;
tx.commit().await?;
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
if let Some(author) = thread.author_id {
let payload = json!({
"url": crate::mail::rules_url(&state),
"action": "thread_removed",
"reason": reason,
"thread_title": thread.title,
});
crate::mail::notify_user(&state, author, "forum_moderation", payload).await;
}
Ok(StatusCode::NO_CONTENT)
}
/// The admin undoes a thread's removal.
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
let admin = viewer.require_user()?;
if !viewer.is_admin() {
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
}
let thread = readable_thread(&state.db, &viewer, id).await?;
if thread.deleted_at.is_none() {
return Ok(StatusCode::NO_CONTENT);
}
let mut tx = state.db.begin().await?;
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}