Files
sorsfonalak/services/forum/src/routes/reports.rs
T
fecoandClaude Opus 5.5 2cf7266fc1 Forum: live notices over WebSocket
A doorbell, not the data: the forum service tells a member's page that
their menu counts, a thread or a conversation changed, and the page
fetches the news over HTTP. Events go through Postgres NOTIFY so every
instance hears them; pings keep the connection (and the online dot)
alive; only the site's own origin may connect. The menu now refreshes
its badges live, on every page change and when the page comes back to
the front, and polls while there is no connection. Caddy sends
/api/v1/forum/ws straight to the forum service; in development
FORUM_WS_URL points at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 11:41:45 +00:00

352 lines
13 KiB
Rust

//! Reports (the DSA's notice and action): any logged-in user may report a
//! post or a private message; moderators see the open ones, act on the post
//! (removal is in `posts`) and close the report. A reported private message
//! is the only way a moderator sees a conversation: the message and the few
//! before it.
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::moderation::{self, Action};
use super::threads::readable_thread;
use super::{Body, IdPath, St, authors, rfc3339};
use crate::auth::Viewer;
use crate::error::{ApiError, ApiResult};
use crate::text;
pub const KINDS: [&str; 6] = ["spam", "ad", "rude", "crisis", "illegal", "other"];
const NOTE_MAX: usize = 500;
/// Reports one user may send in 24 hours.
const PER_DAY: i64 = 20;
/// Messages shown to moderators around a reported one.
const MESSAGE_CONTEXT: i64 = 10;
#[derive(Deserialize)]
pub struct ReportRequest {
kind: String,
#[serde(default)]
note: Option<String>,
}
fn check(req: &ReportRequest) -> ApiResult<String> {
if !KINDS.contains(&req.kind.as_str()) {
return Err(ApiError::bad("Válaszd ki, mi a gond."));
}
let note = req.note.as_deref().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
if note.chars().count() > NOTE_MAX {
return Err(ApiError::bad(format!("A megjegyzés legfeljebb {NOTE_MAX} karakter lehet.")));
}
if req.kind == "other" && note.chars().count() < 3 {
return Err(ApiError::bad("Írd le röviden, mi a gond."));
}
Ok(note)
}
async fn within_limit(db: &PgPool, user: Uuid) -> ApiResult<()> {
let today: i64 = sqlx::query_scalar(
"SELECT count(*) FROM forum.reports WHERE reporter_id = $1 AND created_at > now() - interval '24 hours'",
)
.bind(user)
.fetch_one(db)
.await?;
if today >= PER_DAY {
return Err(ApiError::Limited("Ma már sok jelentést küldtél. Holnap újra lehet.".into()));
}
Ok(())
}
fn received(kind: &str) -> Json<Value> {
Json(json!({ "received": true, "crisis": kind == "crisis" }))
}
/// Reports a post (not one's own). A second report of the same post by the
/// same user while the first is open changes nothing.
pub async fn report_post(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let post: Option<(i64, Option<Uuid>)> =
sqlx::query_as("SELECT thread_id, author_id FROM forum.posts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?;
let (thread_id, author) = post.ok_or(ApiError::NotFound("post"))?;
readable_thread(&state.db, &viewer, thread_id).await?;
if author == Some(user.id) {
return Err(ApiError::bad("A saját hozzászólásodat nem jelentheted."));
}
within_limit(&state.db, user.id).await?;
sqlx::query(
"INSERT INTO forum.reports (post_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
)
.bind(id)
.bind(user.id)
.bind(&req.kind)
.bind(&note)
.execute(&state.db)
.await?;
tracing::info!(post = id, kind = %req.kind, "post reported");
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
Ok((StatusCode::CREATED, received(&req.kind)))
}
/// Reports a private message received in one's own conversation.
pub async fn report_message(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let found: Option<(Option<Uuid>,)> = sqlx::query_as(
"SELECT m.sender_id FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \
WHERE m.id = $1 AND $2 IN (c.user_a, c.user_b)",
)
.bind(id)
.bind(user.id)
.fetch_optional(&state.db)
.await?;
let (sender,) = found.ok_or(ApiError::NotFound("message"))?;
if sender == Some(user.id) {
return Err(ApiError::bad("A saját üzenetedet nem jelentheted."));
}
within_limit(&state.db, user.id).await?;
sqlx::query(
"INSERT INTO forum.reports (message_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
)
.bind(id)
.bind(user.id)
.bind(&req.kind)
.bind(&note)
.execute(&state.db)
.await?;
tracing::info!(message = id, kind = %req.kind, "message reported");
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
Ok((StatusCode::CREATED, received(&req.kind)))
}
#[derive(sqlx::FromRow)]
struct ReportRow {
id: i64,
post_id: Option<i64>,
message_id: Option<i64>,
reporter: Option<String>,
kind: String,
note: String,
status: String,
handled_by: Option<String>,
handled_at: Option<OffsetDateTime>,
created_at: OffsetDateTime,
}
#[derive(sqlx::FromRow)]
struct PostTarget {
id: i64,
thread_id: i64,
title: String,
author_id: Option<Uuid>,
body: String,
deleted: bool,
}
#[derive(sqlx::FromRow)]
struct MessageRow {
id: i64,
conversation_id: i64,
sender_id: Option<Uuid>,
body: String,
created_at: OffsetDateTime,
}
/// Open reports (the oldest first, crisis ones before all), and the last
/// handled ones, with what was reported.
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<ReportRow> = sqlx::query_as(
"SELECT r.id, r.post_id, r.message_id, COALESCE(rm.nickname, 'tag') AS reporter, r.kind, r.note, r.status, \
COALESCE(hm.nickname, hu.display_name) AS handled_by, r.handled_at, r.created_at \
FROM forum.reports r \
LEFT JOIN forum.members rm ON rm.user_id = r.reporter_id \
LEFT JOIN forum.members hm ON hm.user_id = r.handled_by \
LEFT JOIN users hu ON hu.id = r.handled_by \
WHERE r.status = 'open' OR r.handled_at > now() - interval '30 days' \
ORDER BY r.status <> 'open', r.kind <> 'crisis', \
CASE WHEN r.status = 'open' THEN r.created_at END, r.handled_at DESC \
LIMIT 200",
)
.fetch_all(&state.db)
.await?;
let post_ids: Vec<i64> = rows.iter().filter_map(|r| r.post_id).collect();
let posts: Vec<PostTarget> = sqlx::query_as(
"SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.deleted_at IS NOT NULL AS deleted \
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.id = ANY($1)",
)
.bind(&post_ids)
.fetch_all(&state.db)
.await?;
let message_ids: Vec<i64> = rows.iter().filter_map(|r| r.message_id).collect();
// Each reported message with the few before it in its conversation.
let messages: Vec<(i64, MessageRow)> = sqlx::query_as::<_, (i64, i64, i64, Option<Uuid>, String, OffsetDateTime)>(
"SELECT r.id AS reported, m.id, m.conversation_id, m.sender_id, m.body, m.created_at \
FROM forum.messages r \
JOIN LATERAL (SELECT * FROM forum.messages m WHERE m.conversation_id = r.conversation_id AND m.id <= r.id \
ORDER BY m.id DESC LIMIT $2) m ON true \
WHERE r.id = ANY($1) ORDER BY m.id",
)
.bind(&message_ids)
.bind(MESSAGE_CONTEXT)
.fetch_all(&state.db)
.await?
.into_iter()
.map(|(reported, id, conversation_id, sender_id, body, created_at)| {
(reported, MessageRow { id, conversation_id, sender_id, body, created_at })
})
.collect();
let people = authors(
&state.db,
posts.iter().filter_map(|p| p.author_id).chain(messages.iter().filter_map(|(_, m)| m.sender_id)),
)
.await?;
let open_counts: Vec<(Option<i64>, Option<i64>, i64)> =
sqlx::query_as("SELECT post_id, message_id, count(*) FROM forum.reports WHERE status = 'open' GROUP BY 1, 2")
.fetch_all(&state.db)
.await?;
let entries: Vec<Value> = rows
.into_iter()
.map(|r| {
let target = if let Some(post_id) = r.post_id {
posts.iter().find(|p| p.id == post_id).map(|p| {
json!({
"type": "post",
"id": p.id,
"thread": { "id": p.thread_id, "title": p.title, "slug": text::slug(&p.title) },
"author": p.author_id.and_then(|a| people.get(&a).cloned()),
"body": p.body,
"deleted": p.deleted,
})
})
} else {
let id = r.message_id.unwrap_or_default();
let context: Vec<Value> = messages
.iter()
.filter(|(reported, _)| *reported == id)
.map(|(_, m)| {
json!({
"id": m.id,
"sender": m.sender_id.and_then(|s| people.get(&s).cloned()),
"body": m.body,
"created_at": rfc3339(m.created_at),
"reported": m.id == id,
})
})
.collect();
let conversation =
messages.iter().find(|(reported, _)| *reported == id).map(|(_, m)| m.conversation_id);
Some(json!({ "type": "message", "id": id, "conversation_id": conversation, "messages": context }))
};
let reports = open_counts
.iter()
.find(|(p, m, _)| *p == r.post_id && *m == r.message_id)
.map(|(_, _, n)| *n)
.unwrap_or(0);
json!({
"id": r.id,
"kind": r.kind,
"note": r.note,
"reporter": r.reporter,
"status": r.status,
"handled_by": r.handled_by,
"handled_at": r.handled_at.map(rfc3339),
"created_at": rfc3339(r.created_at),
"open_reports_of_target": reports,
"target": target,
})
})
.collect();
Ok(Json(json!({ "reports": entries })))
}
#[derive(Deserialize)]
pub struct Handle {
/// `resolve`: acted on (or nothing needed beyond what was done);
/// `dismiss`: the report was unfounded.
action: String,
}
/// Closes a report, and every other open report of the same post or message.
pub async fn handle(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Handle>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let (status, action) = match req.action.as_str() {
"resolve" => ("resolved", Action::ResolveReport),
"dismiss" => ("dismissed", Action::DismissReport),
_ => return Err(ApiError::bad("Ismeretlen művelet.")),
};
let report: Option<(Option<i64>, Option<i64>)> =
sqlx::query_as("SELECT post_id, message_id FROM forum.reports WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?;
let (post_id, message_id) = report.ok_or(ApiError::NotFound("report"))?;
let mut tx = state.db.begin().await?;
let reporters: Vec<Option<Uuid>> = sqlx::query_scalar(
"UPDATE forum.reports SET status = $2, handled_by = $3, handled_at = now() \
WHERE status = 'open' AND (id = $1 OR ($4::bigint IS NOT NULL AND post_id = $4) \
OR ($5::bigint IS NOT NULL AND message_id = $5)) \
RETURNING reporter_id",
)
.bind(id)
.bind(status)
.bind(moderator.id)
.bind(post_id)
.bind(message_id)
.fetch_all(&mut *tx)
.await?;
moderation::record_report(&mut *tx, moderator.id, action, id, post_id).await?;
tx.commit().await?;
let outcome = if status == "resolved" { "handled" } else { "no_violation" };
crate::mail::notify_reporters(&state, &reporters, outcome).await;
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
Ok(StatusCode::NO_CONTENT)
}
/// When a moderator removes a post, its open reports are resolved with it.
/// Returns the reporters, to tell them.
pub async fn resolve_for_post(
tx: &mut sqlx::PgConnection,
post_id: i64,
moderator: Uuid,
) -> Result<Vec<Option<Uuid>>, sqlx::Error> {
sqlx::query_scalar(
"UPDATE forum.reports SET status = 'resolved', handled_by = $2, handled_at = now() \
WHERE post_id = $1 AND status = 'open' RETURNING reporter_id",
)
.bind(post_id)
.bind(moderator)
.fetch_all(&mut *tx)
.await
}
/// Open reports, for the moderators' badge.
pub async fn open_count(db: &PgPool) -> Result<i64, sqlx::Error> {
sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await
}