//! 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; /// Anyone viewing the thread refetches it (reactions, edits, removals). async fn announce(state: &crate::AppState, thread: i64) { crate::live::emit(&state.db, crate::live::Event { thread: Some(thread), ..Default::default() }).await; } /// 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, ) -> ApiResult> { 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?; crate::links::process(&state, &body).await; announce(&state, post.thread_id).await; super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).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, ) -> ApiResult { let user = viewer.require_user()?; let (post, thread) = 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?; } // Deleting one's own question takes the shared chart's link down too. if own && let Some(share) = post.share_id { revoke_share(&mut *tx, share, user.id).await?; } let mut reporters = Vec::new(); if !own { reporters = super::reports::resolve_for_post(&mut tx, id, user.id).await?; 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?; if !own { if let Some(author) = post.author_id { let payload = serde_json::json!({ "url": crate::mail::rules_url(&state), "action": "post_removed", "reason": reason, "thread_title": thread.title, }); crate::mail::notify_user(&state, author, "forum_moderation", payload).await; } crate::mail::notify_reporters(&state, &reporters, "removed").await; } announce(&state, post.thread_id).await; Ok(StatusCode::NO_CONTENT) } /// The admin undoes a removal. pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult { 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, ) -> ApiResult> { 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?; announce(&state, post.thread_id).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> { 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?; announce(&state, post.thread_id).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, 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> { set_helped(state, viewer, path, true).await } pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult> { set_helped(state, viewer, path, false).await } async fn set_helped( State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath, on: bool, ) -> ApiResult> { 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 = 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?; announce(&state, thread.id).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))) } /// The sharer's link goes (as when revoked on the main site). async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> { sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL") .bind(share) .bind(owner) .execute(db) .await?; Ok(()) } /// The author takes the shared chart off their question: the card goes, and /// the link stops working. pub async fn detach_share( State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath, ) -> ApiResult { let user = viewer.require_user()?; let (post, _) = load(&state.db, &viewer, id).await?; if post.author_id != Some(user.id) { return Err(ApiError::Forbidden("Csak a saját kérdésedről veheted le a képletet.".into())); } let Some(share) = post.share_id else { return Ok(StatusCode::NO_CONTENT) }; let mut tx = state.db.begin().await?; sqlx::query("UPDATE forum.posts SET share_id = NULL WHERE id = $1").bind(id).execute(&mut *tx).await?; revoke_share(&mut *tx, share, user.id).await?; tx.commit().await?; announce(&state, post.thread_id).await; Ok(StatusCode::NO_CONTENT) }