Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the forum schema (migration 0038, which also adds the moderator role): nicknames, profiles with shared signs, topics, threads with listening or advice intent, two-level replies, read marks and followed threads, reactions as ratings with points and ranks, newcomer limits (lifted by a purchase), moderation with reasons, bans and a log. Integration tests run in CI. The frontend's /forum pages (light by default, dark on request, phone first with a desktop layout) are switched on by FORUM_URL; the /api/v1 proxy sends /api/v1/forum/* to the forum service. Concept and status: docs/kozosseg.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
//! A post: editing one's own, removal (one's own, or a moderator's with a
|
||||
//! reason), the admin's restore, reactions and the "Ez segített" mark.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::moderation::{self, Action};
|
||||
use super::threads::{POST_COLUMNS, PostRow, REACTIONS, Reason, ThreadRow, open_thread, posts_json, readable_thread};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::HELPED_POINTS;
|
||||
use crate::text;
|
||||
|
||||
/// A post and its thread, both readable by the viewer.
|
||||
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("post"))?;
|
||||
let thread = readable_thread(db, viewer, post.thread_id).await?;
|
||||
Ok((post, thread))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Edit {
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// The author changes their post (while the thread is open).
|
||||
pub async fn edit(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Edit>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
|
||||
}
|
||||
open_thread(&state.db, &viewer, post.thread_id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The author takes back their post, or a moderator removes it with a reason.
|
||||
/// Hidden, not erased: the admin can restore it.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let own = post.author_id == Some(user.id);
|
||||
let reason = if own {
|
||||
None
|
||||
} else if viewer.is_moderator() {
|
||||
Some(text::reason(req.reason.as_deref().unwrap_or(""))?)
|
||||
} else {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat törölheted.".into()));
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = greatest(reply_count - 1, 0) WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
if !own {
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
user.id,
|
||||
Action::DeletePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
reason.as_deref(),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a 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 (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
admin.id,
|
||||
Action::RestorePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct React {
|
||||
kind: String,
|
||||
}
|
||||
|
||||
fn points_of(kind: &str) -> i32 {
|
||||
if kind == "down" { -1 } else { 1 }
|
||||
}
|
||||
|
||||
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
|
||||
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
|
||||
/// not offered in listening topics.
|
||||
pub async fn react(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<React>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("post"));
|
||||
}
|
||||
open_thread(&state.db, &viewer, thread.id).await?;
|
||||
if post.author_id == Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
|
||||
}
|
||||
let kind = req.kind.as_str();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let rank = member.rank(now);
|
||||
if kind == "down" {
|
||||
if thread.listening {
|
||||
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
|
||||
}
|
||||
if !rank.may_downvote() {
|
||||
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
|
||||
}
|
||||
} else if !REACTIONS.contains(&kind) {
|
||||
return Err(ApiError::bad("Ismeretlen reakció."));
|
||||
}
|
||||
let counted = !rank.is_newcomer();
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let previous: Option<(String, bool)> =
|
||||
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let mut delta = if counted { points_of(kind) } else { 0 };
|
||||
if let Some((old, true)) = &previous {
|
||||
delta -= points_of(old);
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(kind)
|
||||
.bind(counted)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
add_points(&mut tx, post.author_id, delta).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let removed: Option<(String, bool)> =
|
||||
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some((kind, true)) = removed {
|
||||
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
async fn add_points(tx: &mut sqlx::PgConnection, author: Option<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
|
||||
if let (Some(author), true) = (author, delta != 0) {
|
||||
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.bind(delta)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The thread's author marks a reply that helped (worth more than a reaction).
|
||||
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, true).await
|
||||
}
|
||||
|
||||
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, false).await
|
||||
}
|
||||
|
||||
async fn set_helped(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
on: bool,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if thread.author_id != Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
|
||||
}
|
||||
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
let changed: Option<i64> = if on {
|
||||
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
|
||||
)
|
||||
}
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if changed.is_some() {
|
||||
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
Reference in New Issue
Block a user