From 4def9569b1db5f6142ce3cc928711ad2544b1f2b Mon Sep 17 00:00:00 2001
From: feco
Date: Thu, 26 Nov 2026 10:48:28 +0000
Subject: [PATCH] Forum: reports for moderators and private messages by request
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Any logged-in user can report a post, or a private message received; a
possible crisis shows the helplines at once. Moderators get the open
reports (crisis first) with what was reported, remove or close them, and
every step goes to the log; the operator gets a Telegram notice of each
new report (kind and link only). Private conversations start with a
request and a short introduction (from the Kereső rank, a few a day); the
recipient accepts, declines silently or blocks.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
---
.../0039_forum_reports_messages.sql | 69 +++
docs/kozosseg.md | 28 +-
services/forum/src/routes/home.rs | 12 +-
services/forum/src/routes/members.rs | 1 +
services/forum/src/routes/messages.rs | 506 ++++++++++++++++++
services/forum/src/routes/mod.rs | 13 +
services/forum/src/routes/moderation.rs | 32 +-
services/forum/src/routes/posts.rs | 1 +
services/forum/src/routes/reports.rs | 341 ++++++++++++
services/forum/src/tests.rs | 185 +++++++
services/frontend/src/app/forum/forum.css | 53 ++
services/frontend/src/app/forum/layout.tsx | 13 +-
.../src/app/forum/moderalas/ReportsList.tsx | 154 ++++++
.../frontend/src/app/forum/moderalas/page.tsx | 104 ++--
services/frontend/src/app/forum/page.tsx | 2 +-
.../src/app/forum/tag/[nev]/RequestPanel.tsx | 98 ++++
.../frontend/src/app/forum/tag/[nev]/page.tsx | 2 +
.../src/app/forum/uzenetek/Conversations.tsx | 176 ++++++
.../src/app/forum/uzenetek/[id]/Chat.tsx | 207 +++++++
.../src/app/forum/uzenetek/[id]/page.tsx | 21 +
.../frontend/src/app/forum/uzenetek/page.tsx | 24 +
.../src/components/forum/ForumNav.tsx | 31 +-
.../src/components/forum/ReportButton.tsx | 99 ++++
.../src/components/forum/ThreadView.tsx | 2 +
services/frontend/src/lib/forum.ts | 89 +++
services/worker/src/main.rs | 5 +-
services/worker/src/notify.rs | 107 +++-
services/worker/src/tests.rs | 5 +-
28 files changed, 2322 insertions(+), 58 deletions(-)
create mode 100644 crates/db/migrations/0039_forum_reports_messages.sql
create mode 100644 services/forum/src/routes/messages.rs
create mode 100644 services/forum/src/routes/reports.rs
create mode 100644 services/frontend/src/app/forum/moderalas/ReportsList.tsx
create mode 100644 services/frontend/src/app/forum/tag/[nev]/RequestPanel.tsx
create mode 100644 services/frontend/src/app/forum/uzenetek/Conversations.tsx
create mode 100644 services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx
create mode 100644 services/frontend/src/app/forum/uzenetek/[id]/page.tsx
create mode 100644 services/frontend/src/app/forum/uzenetek/page.tsx
create mode 100644 services/frontend/src/components/forum/ReportButton.tsx
diff --git a/crates/db/migrations/0039_forum_reports_messages.sql b/crates/db/migrations/0039_forum_reports_messages.sql
new file mode 100644
index 0000000..eb457e1
--- /dev/null
+++ b/crates/db/migrations/0039_forum_reports_messages.sql
@@ -0,0 +1,69 @@
+-- The forum, second round (docs/kozosseg.md): private messages that start
+-- with a request, and reports of posts and messages (the DSA's notice and
+-- action), handled by moderators.
+
+-- One conversation per pair of members (user_a < user_b). It starts as a
+-- request with a short introduction; the recipient accepts, declines
+-- (silently: the sender is not told) or blocks.
+CREATE TABLE forum.conversations (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ user_a uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ user_b uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ requested_by uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ intro text NOT NULL,
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'declined', 'blocked')),
+ -- Who blocked (the other may not send a new request).
+ blocked_by uuid REFERENCES users ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ responded_at timestamptz,
+ last_message_at timestamptz,
+ UNIQUE (user_a, user_b),
+ CONSTRAINT conversations_ordered CHECK (user_a < user_b),
+ CONSTRAINT conversations_requester CHECK (requested_by IN (user_a, user_b))
+);
+CREATE INDEX conversations_b_idx ON forum.conversations (user_b);
+
+CREATE TABLE forum.messages (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ conversation_id bigint NOT NULL REFERENCES forum.conversations ON DELETE CASCADE,
+ sender_id uuid REFERENCES users ON DELETE SET NULL,
+ body text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX messages_conversation_idx ON forum.messages (conversation_id, id);
+
+-- How far each member has read a conversation.
+CREATE TABLE forum.conversation_reads (
+ conversation_id bigint NOT NULL REFERENCES forum.conversations ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ last_message_id bigint NOT NULL,
+ PRIMARY KEY (conversation_id, user_id)
+);
+
+-- A report of a post or a private message. Moderators see a reported
+-- message (and the conversation around it) only through its report.
+CREATE TABLE forum.reports (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ post_id bigint REFERENCES forum.posts ON DELETE CASCADE,
+ message_id bigint REFERENCES forum.messages ON DELETE CASCADE,
+ reporter_id uuid REFERENCES users ON DELETE SET NULL,
+ kind text NOT NULL CHECK (kind IN ('spam', 'ad', 'rude', 'crisis', 'illegal', 'other')),
+ note text NOT NULL DEFAULT '',
+ status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'resolved', 'dismissed')),
+ handled_by uuid REFERENCES users ON DELETE SET NULL,
+ handled_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ -- The operator's Telegram notice went out (worker notify task).
+ notified_at timestamptz,
+ CONSTRAINT reports_one_target CHECK ((post_id IS NULL) <> (message_id IS NULL))
+);
+CREATE UNIQUE INDEX reports_post_once ON forum.reports (post_id, reporter_id) WHERE status = 'open' AND post_id IS NOT NULL;
+CREATE UNIQUE INDEX reports_message_once ON forum.reports (message_id, reporter_id) WHERE status = 'open' AND message_id IS NOT NULL;
+CREATE INDEX reports_open_idx ON forum.reports (created_at) WHERE status = 'open';
+CREATE INDEX reports_unnotified_idx ON forum.reports (created_at) WHERE notified_at IS NULL;
+
+ALTER TABLE forum.mod_log DROP CONSTRAINT mod_log_action_check;
+ALTER TABLE forum.mod_log ADD CONSTRAINT mod_log_action_check
+ CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', 'ban', 'unban',
+ 'lock', 'unlock', 'pin', 'unpin', 'resolve_report', 'dismiss_report'));
+ALTER TABLE forum.mod_log ADD COLUMN report_id bigint;
diff --git a/docs/kozosseg.md b/docs/kozosseg.md
index cc53d34..e2d11cf 100644
--- a/docs/kozosseg.md
+++ b/docs/kozosseg.md
@@ -59,12 +59,34 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több
- A profiloldal két hasábos.
- **Tesztek:** `cargo test -p forum` (integrációs tesztek valódi Postgresszel), a CI-ban is fut.
+### Ami elkészült (2. kör)
+
+- **Jelentés gomb:**
+ - Bármely belépett felhasználó jelentheti más hozzászólását vagy a neki küldött privát üzenetet. Az okok: bántó, szolgáltatást hirdet, spam, lelki krízis, jogsértő, más.
+ - Krízisjelentésnél azonnal megjelenik a 112 és a 116-123.
+ - Egy felhasználó naponta legfeljebb 20 jelentést küldhet.
+- **A moderátorok jelentéslistája** (`/forum/moderalas`):
+ - Felül a nyitott jelentések, köztük legelöl a krízisjelentések; mellettük a jelentett tartalom.
+ - Privát üzenetnél csak a jelentett üzenet és az előtte lévő legfeljebb 9 látszik.
+ - Műveletek: eltávolítás, lezárás, alaptalan. Egy hozzászólás eltávolítása az összes jelentését is lezárja.
+ - Minden lépés bekerül a naplóba, ami egy második fülön érhető el.
+ - A fórum sávjában a moderátorok egy „Jelentés: N” jelzést látnak.
+- **Telegram-értesítés** az adminnak minden új jelentésről (a worker `notify` feladata): csak a jelentés fajtája és a moderálási oldal linkje, krízisnél kiemelve és elsőként.
+- **Privát üzenetek kéréssel:**
+ - Kérést a Kereső ranggal lehet küldeni, és csak akkor, ha a tag már írt a fórumba. Moderátorra ez nem vonatkozik.
+ - A kérés egy bemutatkozással megy, legfeljebb 200 karakter, link nélkül. Naponta legfeljebb 3 kérés küldhető.
+ - A címzett elfogadja, csendben elutasítja (a küldő továbbra is „válaszra vár”-t lát, 14 nap után „lejárt”-at) vagy letiltja a küldőt.
+ - A saját elutasított vagy lejárt kérés után 30 napig nem lehet újat küldeni.
+ - A beszélgetésben szöveg és emoji mehet, olvasási visszaigazolás nincs. Az új üzeneteket 15 másodpercenként kérdezi le.
+ - Bármelyik fél letilthatja a másikat, és csak a letiltó oldhatja fel a tiltást.
+ - Az „Üzenetek” menüpont jelvénye mutatja az olvasatlan üzeneteket és a megválaszolatlan kéréseket. A profilon jelenik meg a „Beszélgetést kezdeményezek” gomb.
+- **Adatbázis:** `crates/db/migrations/0039_forum_reports_messages.sql`.
+
### Ami még hátravan
-- **Jelentés gomb** hozzászóláshoz (a DSA miatt kell), és az ÁSZF kiegészítése.
-- **Privát üzenetek** kéréssel.
- **E-mail értesítések:** a napi összesítő, az értesítési beállítások oldala és a hírlevél-kapcsoló.
-- **WebSocket-csengő** a 30 másodperces lekérdezés helyett.
+- **ÁSZF kiegészítése a fórummal:** a DSA szerinti bejelentés, a kapcsolattartási pont és az indoklás rendje, plusz egy mondat az adatvédelmi tájékoztatóba, hogy a moderátor csak jelentett privát üzenetet lát.
+- **WebSocket-csengő** a lekérdezés helyett.
- **Napi „Mai égbolt” szál:** a worker nyitná meg automatikusan.
- **AI-funkciók:** előszűrés, lelki krízis jelzése, az AI-összefoglaló kártya a főoldalon.
- **Saját avatar feltöltése** (Spaces), és a „Támogató” jelvény.
diff --git a/services/forum/src/routes/home.rs b/services/forum/src/routes/home.rs
index 2ca7b72..00b5c93 100644
--- a/services/forum/src/routes/home.rs
+++ b/services/forum/src/routes/home.rs
@@ -172,7 +172,17 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult
/// For the forum's menu on every page: who the viewer is, and the badge.
pub async fn nav(state: St, viewer: Viewer) -> ApiResult> {
- Ok(Json(json!({ "viewer": viewer_json(&viewer), "followed": followed_counts(&state, &viewer).await? })))
+ let messages = match &viewer.member {
+ Some(m) => Some(super::messages::unread_count(&state.db, m.user_id).await?),
+ None => None,
+ };
+ let reports = if viewer.is_moderator() { Some(super::reports::open_count(&state.db).await?) } else { None };
+ Ok(Json(json!({
+ "viewer": viewer_json(&viewer),
+ "followed": followed_counts(&state, &viewer).await?,
+ "messages": messages,
+ "reports": reports,
+ })))
}
pub async fn topics(state: St, viewer: Viewer) -> ApiResult> {
diff --git a/services/forum/src/routes/members.rs b/services/forum/src/routes/members.rs
index b3ab7bc..4797cdd 100644
--- a/services/forum/src/routes/members.rs
+++ b/services/forum/src/routes/members.rs
@@ -293,6 +293,7 @@ pub async fn profile(
}),
"ban_reason": row.ban_reason.filter(|_| show_ban && banned.is_some()),
},
+ "relation": super::messages::relation(&state.db, &viewer, row.user_id).await?,
"recent": recent.into_iter().map(|r| json!({
"id": r.id,
"thread_id": r.thread_id,
diff --git a/services/forum/src/routes/messages.rs b/services/forum/src/routes/messages.rs
new file mode 100644
index 0000000..86f5519
--- /dev/null
+++ b/services/forum/src/routes/messages.rs
@@ -0,0 +1,506 @@
+//! Private messages. Nobody can just write to someone: first a request with
+//! a short introduction (from the Kereső rank, after writing in public; at
+//! most a few a day), which the recipient accepts, declines (silently: the
+//! sender keeps seeing "sent" until it expires) or blocks. Then one-to-one
+//! text. Moderators never read conversations, only a reported message.
+
+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::{Body, IdPath, St, authors, rfc3339};
+use crate::auth::{Member, Viewer};
+use crate::error::{ApiError, ApiResult};
+use crate::text;
+
+/// A request not answered in this many days expires.
+const REQUEST_DAYS: i64 = 14;
+/// After a decline (or an expired request) a new request may come this much later.
+const RETRY_DAYS: i64 = 30;
+/// New requests one member may send in 24 hours.
+const REQUESTS_PER_DAY: i64 = 3;
+const INTRO_MIN: usize = 3;
+const INTRO_MAX: usize = 200;
+const MESSAGE_MAX: usize = 4000;
+/// Messages one member may send in 24 hours (all conversations).
+const MESSAGES_PER_DAY: i64 = 300;
+/// Messages shown in a conversation.
+const MESSAGES_SHOWN: i64 = 200;
+
+#[derive(Debug, Clone, sqlx::FromRow)]
+struct Conversation {
+ id: i64,
+ user_a: Uuid,
+ user_b: Uuid,
+ requested_by: Uuid,
+ intro: String,
+ status: String,
+ blocked_by: Option,
+ created_at: OffsetDateTime,
+ responded_at: Option,
+ last_message_at: Option,
+}
+
+const CONVERSATION_COLUMNS: &str =
+ "id, user_a, user_b, requested_by, intro, status, blocked_by, created_at, responded_at, last_message_at";
+
+impl Conversation {
+ fn other(&self, me: Uuid) -> Uuid {
+ if self.user_a == me { self.user_b } else { self.user_a }
+ }
+
+ fn expired(&self, now: OffsetDateTime) -> bool {
+ now - self.created_at > time::Duration::days(REQUEST_DAYS)
+ }
+
+ /// How the conversation looks to `me`. A decline, or a block by the
+ /// other, looks like a request still waiting (then expired).
+ fn state_for(&self, me: Uuid, now: OffsetDateTime) -> &'static str {
+ match self.status.as_str() {
+ "accepted" => "accepted",
+ "blocked" if self.blocked_by == Some(me) => "blocked_by_me",
+ _ if self.requested_by == me => {
+ if self.expired(now) {
+ "expired"
+ } else {
+ "outgoing"
+ }
+ }
+ "pending" if !self.expired(now) => "incoming",
+ _ => "closed",
+ }
+ }
+}
+
+fn pair(a: Uuid, b: Uuid) -> (Uuid, Uuid) {
+ if a < b { (a, b) } else { (b, a) }
+}
+
+/// Whether a member may start conversations: from the Kereső rank and after
+/// writing in public (moderators always).
+fn may_request(viewer: &Viewer, member: &Member) -> bool {
+ viewer.is_moderator() || (!member.rank(OffsetDateTime::now_utc()).is_newcomer() && member.post_count > 0)
+}
+
+/// The viewer's relation to another member, for the profile page.
+pub async fn relation(db: &PgPool, viewer: &Viewer, other: Uuid) -> ApiResult {
+ let Some(member) = &viewer.member else { return Ok(Value::Null) };
+ if member.user_id == other {
+ return Ok(Value::Null);
+ }
+ let (a, b) = pair(member.user_id, other);
+ let conversation: Option = sqlx::query_as(&format!(
+ "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2"
+ ))
+ .bind(a)
+ .bind(b)
+ .fetch_optional(db)
+ .await?;
+ let now = OffsetDateTime::now_utc();
+ let state = conversation.as_ref().map(|c| c.state_for(member.user_id, now));
+ let can_request =
+ !member.banned(now) && may_request(viewer, member) && matches!(state, None | Some("expired") | Some("closed"));
+ Ok(json!({
+ "conversation_id": conversation.as_ref().map(|c| c.id),
+ "state": state,
+ "can_request": can_request,
+ "eligible": may_request(viewer, member),
+ }))
+}
+
+fn intro_text(raw: &str) -> ApiResult {
+ let intro: String = raw.split_whitespace().collect::>().join(" ");
+ let len = intro.chars().count();
+ if !(INTRO_MIN..=INTRO_MAX).contains(&len) {
+ return Err(ApiError::bad(format!("A bemutatkozás {INTRO_MIN}–{INTRO_MAX} karakter legyen.")));
+ }
+ let lower = intro.to_lowercase();
+ if lower.contains("http") || lower.contains("www.") {
+ return Err(ApiError::bad("A kérésbe nem tehetsz linket."));
+ }
+ text::body(&intro)
+}
+
+#[derive(Deserialize)]
+pub struct NewRequest {
+ /// The other member's nickname.
+ to: String,
+ intro: String,
+}
+
+/// Sends a conversation request.
+pub async fn request(
+ State(state): St,
+ viewer: Viewer,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult<(StatusCode, Json)> {
+ let me = viewer.require_writer()?;
+ if !may_request(&viewer, me) {
+ return Err(ApiError::Forbidden(
+ "Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba. A neked küldött kéréseket addig is elfogadhatod."
+ .into(),
+ ));
+ }
+ let other: Uuid = sqlx::query_scalar("SELECT user_id FROM forum.members WHERE nickname_key = $1")
+ .bind(text::nickname_key(&req.to))
+ .fetch_optional(&state.db)
+ .await?
+ .ok_or(ApiError::NotFound("member"))?;
+ if other == me.user_id {
+ return Err(ApiError::bad("Magaddal nem kezdeményezhetsz beszélgetést."));
+ }
+ let intro = intro_text(&req.intro)?;
+ let sent_today: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM forum.conversations WHERE requested_by = $1 AND created_at > now() - interval '24 hours'",
+ )
+ .bind(me.user_id)
+ .fetch_one(&state.db)
+ .await?;
+ if sent_today >= REQUESTS_PER_DAY && !viewer.is_moderator() {
+ return Err(ApiError::Limited(format!("Naponta legfeljebb {REQUESTS_PER_DAY} kérést küldhetsz.")));
+ }
+
+ let (a, b) = pair(me.user_id, other);
+ let now = OffsetDateTime::now_utc();
+ let mut tx = state.db.begin().await?;
+ let existing: Option = sqlx::query_as(&format!(
+ "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE user_a = $1 AND user_b = $2 FOR UPDATE"
+ ))
+ .bind(a)
+ .bind(b)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let waiting = || ApiError::conflict("request_pending", "Már elküldted a kérésedet.");
+ let id = match existing {
+ None => {
+ sqlx::query_scalar(
+ "INSERT INTO forum.conversations (user_a, user_b, requested_by, intro) VALUES ($1, $2, $3, $4) RETURNING id",
+ )
+ .bind(a)
+ .bind(b)
+ .bind(me.user_id)
+ .bind(&intro)
+ .fetch_one(&mut *tx)
+ .await?
+ }
+ Some(c) => {
+ match c.state_for(me.user_id, now) {
+ "accepted" => return Err(ApiError::conflict("conversation_open", "Már beszélgettek.")),
+ "incoming" => {
+ return Err(ApiError::conflict("request_incoming", "Ő már küldött neked kérést: nézd meg az üzeneteidnél."));
+ }
+ "blocked_by_me" => {
+ return Err(ApiError::conflict("blocked", "Letiltottad őt. Előbb oldd fel a tiltást az üzeneteidnél."));
+ }
+ "outgoing" => return Err(waiting()),
+ _ => {}
+ }
+ // Blocked by the other: looks like a request still waiting.
+ if c.status == "blocked" {
+ return Err(waiting());
+ }
+ // After one's own declined or expired request, a new one only
+ // after a while (the one who declined may write at once).
+ let since = c.responded_at.unwrap_or(c.created_at);
+ if c.requested_by == me.user_id && now - since < time::Duration::days(RETRY_DAYS) {
+ return Err(waiting());
+ }
+ sqlx::query(
+ "UPDATE forum.conversations SET requested_by = $2, intro = $3, status = 'pending', blocked_by = NULL, \
+ created_at = now(), responded_at = NULL WHERE id = $1",
+ )
+ .bind(c.id)
+ .bind(me.user_id)
+ .bind(&intro)
+ .execute(&mut *tx)
+ .await?;
+ c.id
+ }
+ };
+ tx.commit().await?;
+ Ok((StatusCode::CREATED, Json(json!({ "id": id }))))
+}
+
+/// A conversation of the viewer (any state), or 404.
+async fn own(db: &PgPool, me: Uuid, id: i64) -> ApiResult {
+ sqlx::query_as(&format!(
+ "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE id = $1 AND $2 IN (user_a, user_b)"
+ ))
+ .bind(id)
+ .bind(me)
+ .fetch_optional(db)
+ .await?
+ .ok_or(ApiError::NotFound("conversation"))
+}
+
+#[derive(sqlx::FromRow)]
+struct LastMessage {
+ conversation_id: i64,
+ sender_id: Option,
+ body: String,
+}
+
+/// The viewer's conversations and requests, and how many messages are unread.
+pub async fn list(State(state): St, viewer: Viewer) -> ApiResult> {
+ let me = viewer.require_member()?.user_id;
+ let rows: Vec = sqlx::query_as(&format!(
+ "SELECT {CONVERSATION_COLUMNS} FROM forum.conversations WHERE $1 IN (user_a, user_b) \
+ ORDER BY COALESCE(last_message_at, created_at) DESC LIMIT 200"
+ ))
+ .bind(me)
+ .fetch_all(&state.db)
+ .await?;
+ let ids: Vec = rows.iter().map(|c| c.id).collect();
+ let last: Vec = sqlx::query_as(
+ "SELECT DISTINCT ON (conversation_id) conversation_id, sender_id, left(body, 120) AS body \
+ FROM forum.messages WHERE conversation_id = ANY($1) ORDER BY conversation_id, id DESC",
+ )
+ .bind(&ids)
+ .fetch_all(&state.db)
+ .await?;
+ let unread: Vec<(i64, i64)> = sqlx::query_as(
+ "SELECT m.conversation_id, count(*) FROM forum.messages m \
+ WHERE m.conversation_id = ANY($1) AND m.sender_id IS DISTINCT FROM $2 \
+ AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \
+ WHERE r.conversation_id = m.conversation_id AND r.user_id = $2), 0) \
+ GROUP BY 1",
+ )
+ .bind(&ids)
+ .bind(me)
+ .fetch_all(&state.db)
+ .await?;
+ let people = authors(&state.db, rows.iter().map(|c| c.other(me))).await?;
+ let now = OffsetDateTime::now_utc();
+ let items: Vec = rows
+ .iter()
+ .filter_map(|c| {
+ let state = c.state_for(me, now);
+ if state == "closed" {
+ return None;
+ }
+ let last = last.iter().find(|l| l.conversation_id == c.id);
+ Some(json!({
+ "id": c.id,
+ "other": people.get(&c.other(me)),
+ "state": state,
+ "intro": c.intro,
+ "created_at": rfc3339(c.created_at),
+ "last_message_at": c.last_message_at.map(rfc3339),
+ "last_message": last.map(|l| json!({ "excerpt": l.body, "mine": l.sender_id == Some(me) })),
+ "unread": unread.iter().find(|(id, _)| *id == c.id).map(|(_, n)| *n).unwrap_or(0),
+ }))
+ })
+ .collect();
+ Ok(Json(json!({ "conversations": items })))
+}
+
+/// Unread messages and requests waiting for an answer (the menu's badge).
+pub async fn unread_count(db: &PgPool, me: Uuid) -> Result {
+ sqlx::query_scalar(
+ "SELECT (SELECT count(*) FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \
+ WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'accepted' AND m.sender_id IS DISTINCT FROM $1 \
+ AND m.id > COALESCE((SELECT r.last_message_id FROM forum.conversation_reads r \
+ WHERE r.conversation_id = c.id AND r.user_id = $1), 0)) \
+ + (SELECT count(*) FROM forum.conversations c \
+ WHERE $1 IN (c.user_a, c.user_b) AND c.status = 'pending' AND c.requested_by <> $1 \
+ AND c.created_at > now() - make_interval(days => $2))",
+ )
+ .bind(me)
+ .bind(REQUEST_DAYS as i32)
+ .fetch_one(db)
+ .await
+}
+
+/// One conversation: the request, and the messages once accepted.
+pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult> {
+ let me = viewer.require_member()?.user_id;
+ let c = own(&state.db, me, id).await?;
+ let now = OffsetDateTime::now_utc();
+ let conversation_state = c.state_for(me, now);
+ if conversation_state == "closed" {
+ return Err(ApiError::NotFound("conversation"));
+ }
+ let messages: Vec<(i64, Option, String, OffsetDateTime)> =
+ if c.status == "accepted" || conversation_state == "blocked_by_me" {
+ sqlx::query_as(
+ "SELECT id, sender_id, body, created_at FROM \
+ (SELECT id, sender_id, body, created_at FROM forum.messages WHERE conversation_id = $1 \
+ ORDER BY id DESC LIMIT $2) recent ORDER BY id",
+ )
+ .bind(id)
+ .bind(MESSAGES_SHOWN)
+ .fetch_all(&state.db)
+ .await?
+ } else {
+ Vec::new()
+ };
+ let people = authors(&state.db, [c.other(me)]).await?;
+ Ok(Json(json!({
+ "viewer": super::home::viewer_json(&viewer),
+ "conversation": {
+ "id": c.id,
+ "other": people.get(&c.other(me)),
+ "state": conversation_state,
+ "intro": c.intro,
+ "requested_by_me": c.requested_by == me,
+ "created_at": rfc3339(c.created_at),
+ },
+ "messages": messages.into_iter().map(|(id, sender, body, at)| json!({
+ "id": id, "mine": sender == Some(me), "body": body, "created_at": rfc3339(at),
+ })).collect::>(),
+ })))
+}
+
+/// The recipient answers a request: accept, decline (silently) or block.
+pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static str) -> ApiResult {
+ let State(state) = state;
+ let WithRejection(Path(id), _) = path;
+ let me = viewer.require_member()?.user_id;
+ let c = own(&state.db, me, id).await?;
+ let now = OffsetDateTime::now_utc();
+ match answer {
+ "block" => {
+ sqlx::query(
+ "UPDATE forum.conversations SET status = 'blocked', blocked_by = $2, responded_at = now() WHERE id = $1",
+ )
+ .bind(id)
+ .bind(me)
+ .execute(&state.db)
+ .await?;
+ }
+ "unblock" => {
+ if c.blocked_by != Some(me) {
+ return Err(ApiError::bad("Ezt a tiltást nem te állítottad be."));
+ }
+ sqlx::query(
+ "UPDATE forum.conversations SET status = 'declined', blocked_by = NULL, responded_at = now() WHERE id = $1",
+ )
+ .bind(id)
+ .execute(&state.db)
+ .await?;
+ }
+ _ => {
+ if c.state_for(me, now) != "incoming" {
+ return Err(ApiError::bad("Erre a kérésre már nem lehet válaszolni."));
+ }
+ let status = if answer == "accept" { "accepted" } else { "declined" };
+ sqlx::query("UPDATE forum.conversations SET status = $2, responded_at = now() WHERE id = $1")
+ .bind(id)
+ .bind(status)
+ .execute(&state.db)
+ .await?;
+ }
+ }
+ Ok(StatusCode::NO_CONTENT)
+}
+
+pub async fn accept(state: St, viewer: Viewer, path: IdPath) -> ApiResult {
+ respond(state, viewer, path, "accept").await
+}
+
+pub async fn decline(state: St, viewer: Viewer, path: IdPath) -> ApiResult {
+ respond(state, viewer, path, "decline").await
+}
+
+pub async fn block(state: St, viewer: Viewer, path: IdPath) -> ApiResult {
+ respond(state, viewer, path, "block").await
+}
+
+pub async fn unblock(state: St, viewer: Viewer, path: IdPath) -> ApiResult {
+ respond(state, viewer, path, "unblock").await
+}
+
+#[derive(Deserialize)]
+pub struct NewMessage {
+ body: String,
+}
+
+/// A message in an accepted conversation.
+pub async fn send(
+ State(state): St,
+ viewer: Viewer,
+ WithRejection(Path(id), _): IdPath,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult<(StatusCode, Json)> {
+ let me = viewer.require_writer()?.user_id;
+ let c = own(&state.db, me, id).await?;
+ if c.status != "accepted" {
+ return Err(ApiError::Forbidden("Ebben a beszélgetésben most nem lehet írni.".into()));
+ }
+ let body = text::body(&req.body)?;
+ if body.chars().count() > MESSAGE_MAX {
+ return Err(ApiError::bad(format!("Az üzenet legfeljebb {MESSAGE_MAX} karakter lehet.")));
+ }
+ let today: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM forum.messages WHERE sender_id = $1 AND created_at > now() - interval '24 hours'",
+ )
+ .bind(me)
+ .fetch_one(&state.db)
+ .await?;
+ if today >= MESSAGES_PER_DAY {
+ return Err(ApiError::Limited("Ma már nagyon sok üzenetet küldtél. Holnap folytathatod.".into()));
+ }
+ let mut tx = state.db.begin().await?;
+ let (message_id, created_at): (i64, OffsetDateTime) = sqlx::query_as(
+ "INSERT INTO forum.messages (conversation_id, sender_id, body) VALUES ($1, $2, $3) RETURNING id, created_at",
+ )
+ .bind(id)
+ .bind(me)
+ .bind(&body)
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE forum.conversations SET last_message_at = now() WHERE id = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ mark(&mut *tx, id, me, message_id).await?;
+ tx.commit().await?;
+ Ok((
+ StatusCode::CREATED,
+ Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })),
+ ))
+}
+
+async fn mark(db: impl sqlx::PgExecutor<'_>, conversation: i64, user: Uuid, message: i64) -> Result<(), sqlx::Error> {
+ sqlx::query(
+ "INSERT INTO forum.conversation_reads (conversation_id, user_id, last_message_id) VALUES ($1, $2, $3) \
+ ON CONFLICT (conversation_id, user_id) DO UPDATE \
+ SET last_message_id = GREATEST(forum.conversation_reads.last_message_id, EXCLUDED.last_message_id)",
+ )
+ .bind(conversation)
+ .bind(user)
+ .bind(message)
+ .execute(db)
+ .await?;
+ Ok(())
+}
+
+#[derive(Deserialize)]
+pub struct ReadMark {
+ message_id: i64,
+}
+
+/// Read up to that message. No read receipts: the other never sees this.
+pub async fn read(
+ State(state): St,
+ viewer: Viewer,
+ WithRejection(Path(id), _): IdPath,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult {
+ let me = viewer.require_member()?.user_id;
+ own(&state.db, me, id).await?;
+ let last: Option = sqlx::query_scalar("SELECT max(id) FROM forum.messages WHERE conversation_id = $1")
+ .bind(id)
+ .fetch_one(&state.db)
+ .await?;
+ if let Some(last) = last {
+ mark(&state.db, id, me, req.message_id.min(last)).await?;
+ }
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs
index 97a3c4e..d0c00d2 100644
--- a/services/forum/src/routes/mod.rs
+++ b/services/forum/src/routes/mod.rs
@@ -7,8 +7,10 @@
mod home;
mod members;
+mod messages;
mod moderation;
mod posts;
+mod reports;
mod threads;
use std::collections::HashMap;
@@ -51,12 +53,23 @@ pub fn router(state: Arc) -> Router {
.route("/v1/forum/posts/{id}/restore", post(posts::restore))
.route("/v1/forum/posts/{id}/reaction", put(posts::react).delete(posts::unreact))
.route("/v1/forum/posts/{id}/helped", put(posts::mark_helped).delete(posts::unmark_helped))
+ .route("/v1/forum/posts/{id}/report", post(reports::report_post))
+ .route("/v1/forum/messages/{id}/report", post(reports::report_message))
+ .route("/v1/forum/conversations", get(messages::list).post(messages::request))
+ .route("/v1/forum/conversations/{id}", get(messages::show))
+ .route("/v1/forum/conversations/{id}/accept", post(messages::accept))
+ .route("/v1/forum/conversations/{id}/decline", post(messages::decline))
+ .route("/v1/forum/conversations/{id}/block", post(messages::block).delete(messages::unblock))
+ .route("/v1/forum/conversations/{id}/messages", post(messages::send))
+ .route("/v1/forum/conversations/{id}/read", post(messages::read))
.route("/v1/forum/me", get(members::me).put(members::save_me))
.route("/v1/forum/nickname-check", get(members::nickname_check))
.route("/v1/forum/presence", post(members::presence))
.route("/v1/forum/members/{nickname}", get(members::profile))
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
+ .route("/v1/forum/mod/reports", get(reports::list))
+ .route("/v1/forum/mod/reports/{id}", post(reports::handle))
// The request log: masked paths, health checks only when they fail.
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
.with_state(state)
diff --git a/services/forum/src/routes/moderation.rs b/services/forum/src/routes/moderation.rs
index ab556b0..7c777b6 100644
--- a/services/forum/src/routes/moderation.rs
+++ b/services/forum/src/routes/moderation.rs
@@ -27,6 +27,8 @@ pub enum Action {
Unlock,
Pin,
Unpin,
+ ResolveReport,
+ DismissReport,
}
impl Action {
@@ -42,6 +44,8 @@ impl Action {
Action::Unlock => "unlock",
Action::Pin => "pin",
Action::Unpin => "unpin",
+ Action::ResolveReport => "resolve_report",
+ Action::DismissReport => "dismiss_report",
}
}
}
@@ -74,6 +78,29 @@ pub async fn record(
Ok(())
}
+/// Logs the closing of a report.
+pub async fn record_report(
+ db: impl sqlx::PgExecutor<'_>,
+ actor: Uuid,
+ action: Action,
+ report_id: i64,
+ post_id: Option,
+) -> Result<(), sqlx::Error> {
+ sqlx::query(
+ "INSERT INTO forum.mod_log (actor_id, actor_kind, action, report_id, post_id, \
+ thread_id, target_user) \
+ SELECT $1, 'human', $2, $3, $4, p.thread_id, p.author_id \
+ FROM (SELECT 1) one LEFT JOIN forum.posts p ON p.id = $4",
+ )
+ .bind(actor)
+ .bind(action.as_str())
+ .bind(report_id)
+ .bind(post_id)
+ .execute(db)
+ .await?;
+ Ok(())
+}
+
/// A ban for good: the last day of year 9999.
fn forever() -> OffsetDateTime {
let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date");
@@ -163,6 +190,7 @@ struct LogRow {
thread_id: Option,
thread_title: Option,
post_id: Option,
+ report_id: Option,
reason: Option,
until: Option,
created_at: OffsetDateTime,
@@ -173,7 +201,8 @@ pub async fn log(State(state): St, viewer: Viewer) -> ApiResult> {
viewer.require_moderator()?;
let rows: Vec = sqlx::query_as(
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
- tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.reason, l.until, l.created_at \
+ tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.report_id, l.reason, l.until, \
+ l.created_at \
FROM forum.mod_log l \
LEFT JOIN forum.members am ON am.user_id = l.actor_id \
LEFT JOIN users au ON au.id = l.actor_id \
@@ -192,6 +221,7 @@ pub async fn log(State(state): St, viewer: Viewer) -> ApiResult> {
"target": r.target,
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
"post_id": r.post_id,
+ "report_id": r.report_id,
"reason": r.reason,
"until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }),
"created_at": rfc3339(r.created_at),
diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs
index 2b2cec8..dbb70e2 100644
--- a/services/forum/src/routes/posts.rs
+++ b/services/forum/src/routes/posts.rs
@@ -93,6 +93,7 @@ pub async fn remove(
.await?;
}
if !own {
+ super::reports::resolve_for_post(&mut tx, id, user.id).await?;
moderation::record(
&mut *tx,
user.id,
diff --git a/services/forum/src/routes/reports.rs b/services/forum/src/routes/reports.rs
new file mode 100644
index 0000000..dadd58e
--- /dev/null
+++ b/services/forum/src/routes/reports.rs
@@ -0,0 +1,341 @@
+//! 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,
+}
+
+fn check(req: &ReportRequest) -> ApiResult {
+ 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::>().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 {
+ 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,
+) -> ApiResult<(StatusCode, Json)> {
+ let user = viewer.require_user()?;
+ let note = check(&req)?;
+ let post: Option<(i64, Option)> =
+ 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(¬e)
+ .execute(&state.db)
+ .await?;
+ tracing::info!(post = id, kind = %req.kind, "post reported");
+ 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,
+) -> ApiResult<(StatusCode, Json)> {
+ let user = viewer.require_user()?;
+ let note = check(&req)?;
+ let found: Option<(Option,)> = 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(¬e)
+ .execute(&state.db)
+ .await?;
+ tracing::info!(message = id, kind = %req.kind, "message reported");
+ Ok((StatusCode::CREATED, received(&req.kind)))
+}
+
+#[derive(sqlx::FromRow)]
+struct ReportRow {
+ id: i64,
+ post_id: Option,
+ message_id: Option,
+ reporter: Option,
+ kind: String,
+ note: String,
+ status: String,
+ handled_by: Option,
+ handled_at: Option,
+ created_at: OffsetDateTime,
+}
+
+#[derive(sqlx::FromRow)]
+struct PostTarget {
+ id: i64,
+ thread_id: i64,
+ title: String,
+ author_id: Option,
+ body: String,
+ deleted: bool,
+}
+
+#[derive(sqlx::FromRow)]
+struct MessageRow {
+ id: i64,
+ conversation_id: i64,
+ sender_id: Option,
+ 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> {
+ viewer.require_moderator()?;
+ let rows: Vec = 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 = rows.iter().filter_map(|r| r.post_id).collect();
+ let posts: Vec = 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 = 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, 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, Option, 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 = 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 = 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,
+) -> ApiResult {
+ 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, Option)> =
+ 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?;
+ sqlx::query(
+ "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))",
+ )
+ .bind(id)
+ .bind(status)
+ .bind(moderator.id)
+ .bind(post_id)
+ .bind(message_id)
+ .execute(&mut *tx)
+ .await?;
+ moderation::record_report(&mut *tx, moderator.id, action, id, post_id).await?;
+ tx.commit().await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// When a moderator removes a post, its open reports are resolved with it.
+pub async fn resolve_for_post(tx: &mut sqlx::PgConnection, post_id: i64, moderator: Uuid) -> Result<(), sqlx::Error> {
+ sqlx::query(
+ "UPDATE forum.reports SET status = 'resolved', handled_by = $2, handled_at = now() \
+ WHERE post_id = $1 AND status = 'open'",
+ )
+ .bind(post_id)
+ .bind(moderator)
+ .execute(&mut *tx)
+ .await?;
+ Ok(())
+}
+
+/// Open reports, for the moderators' badge.
+pub async fn open_count(db: &PgPool) -> Result {
+ sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await
+}
diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs
index 57deefc..febc3b1 100644
--- a/services/forum/src/tests.rs
+++ b/services/forum/src/tests.rs
@@ -519,3 +519,188 @@ async fn profiles_share_signs_never_degrees(pool: PgPool) {
assert_eq!(profile["member"]["author"]["online"], false);
assert!(profile["member"]["last_seen"].is_null());
}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn reports_reach_moderators(pool: PgPool) {
+ let app = TestApp::new(pool);
+ let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
+ let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
+ let cili = app.user("cili@example.com", &["user"]).await; // no nickname: may still report
+ let moderator = app.member("mod@example.com", "Őrangyal", &["user", "moderator"]).await;
+ let thread = app.thread(&anna, "belso-utak", "Energiák").await;
+ let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap();
+
+ let report = |user: &User, body: Value| {
+ let uri = format!("/v1/forum/posts/{post}/report");
+ let user = User { id: user.id, token: user.token.clone() };
+ let app = &app;
+ async move { app.call("POST", &uri, Some(&user), body).await }
+ };
+ assert_eq!(
+ app.call("POST", &format!("/v1/forum/posts/{post}/report"), None, json!({"kind": "ad"})).await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(report(&bea, json!({"kind": "ad"})).await.0, StatusCode::BAD_REQUEST, "not one's own");
+ assert_eq!(report(&anna, json!({"kind": "other"})).await.0, StatusCode::BAD_REQUEST, "'other' needs a note");
+ assert_eq!(report(&anna, json!({"kind": "nonsense"})).await.0, StatusCode::BAD_REQUEST);
+ let (status, body) = report(&anna, json!({"kind": "ad", "note": "jóslást árul"})).await;
+ assert_eq!((status, body["crisis"].as_bool()), (StatusCode::CREATED, Some(false)));
+ assert_eq!(report(&anna, json!({"kind": "ad"})).await.0, StatusCode::CREATED, "a repeat changes nothing");
+ let (_, body) = report(&cili, json!({"kind": "crisis"})).await;
+ assert_eq!(body["crisis"], true);
+
+ // Only moderators see them; the crisis one first; the menu shows the count.
+ assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&anna), Value::Null).await.0, StatusCode::FORBIDDEN);
+ let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
+ let reports = list["reports"].as_array().unwrap();
+ assert_eq!(reports.len(), 2);
+ assert_eq!(reports[0]["kind"], "crisis");
+ assert_eq!(reports[1]["reporter"], "Csendesvíz");
+ assert_eq!(reports[1]["target"]["body"], "Energetikai gyógyítás, írj!");
+ assert_eq!(reports[1]["open_reports_of_target"], 2);
+ assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 2);
+ assert!(app.get("/v1/forum/nav", Some(&anna)).await["reports"].is_null());
+
+ // Removing the post resolves every open report of it, and it is logged.
+ let (status, _) = app
+ .call(
+ "DELETE",
+ &format!("/v1/forum/posts/{post}"),
+ Some(&moderator),
+ json!({ "reason": "szolgáltatás hirdetése" }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::NO_CONTENT);
+ let list = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
+ assert!(list["reports"].as_array().unwrap().iter().all(|r| r["status"] == "resolved"));
+ assert_eq!(app.get("/v1/forum/nav", Some(&moderator)).await["reports"], 0);
+
+ // A report can also be dismissed.
+ let other = app.reply(&bea, thread, "Bocsánat.", None).await["id"].as_i64().unwrap();
+ app.call("POST", &format!("/v1/forum/posts/{other}/report"), Some(&anna), json!({"kind": "rude"})).await;
+ let id = app.get("/v1/forum/mod/reports", Some(&moderator)).await["reports"][0]["id"].as_i64().unwrap();
+ let (status, _) = app
+ .call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&moderator), json!({ "action": "dismiss" }))
+ .await;
+ assert_eq!(status, StatusCode::NO_CONTENT);
+ let log = app.get("/v1/forum/mod/log", Some(&moderator)).await;
+ assert_eq!(log["entries"][0]["action"], "dismiss_report");
+ assert_eq!(log["entries"][0]["target"], "Holdfény");
+}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn private_messages_start_with_a_request(pool: PgPool) {
+ let app = TestApp::new(pool);
+ let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
+ let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
+ let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
+ let request = |from: &User, to: &str, intro: &str| {
+ let user = User { id: from.id, token: from.token.clone() };
+ let body = json!({ "to": to, "intro": intro });
+ let app = &app;
+ async move { app.call("POST", "/v1/forum/conversations", Some(&user), body).await }
+ };
+
+ // A newcomer may not start one; a seasoned member who wrote in public may.
+ let (status, _) = request(&anna, "Holdfény", "Szia, olvastam a hozzászólásodat.").await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let profile = app.get("/v1/forum/members/Holdfény", Some(&anna)).await;
+ assert_eq!(profile["relation"]["can_request"], false);
+ app.thread(&anna, "torzsasztal", "Sziasztok").await;
+ app.season(&anna, 5, 10).await;
+ assert_eq!(app.get("/v1/forum/members/Holdfény", Some(&anna)).await["relation"]["can_request"], true);
+ assert_eq!(request(&anna, "Holdfény", "Nézd: www.pelda.hu").await.0, StatusCode::BAD_REQUEST);
+ assert_eq!(request(&anna, "Csendesvíz", "Szia, én vagyok.").await.0, StatusCode::BAD_REQUEST);
+ let (status, body) = request(&anna, "holdfeny", "Szia, olvastam a hozzászólásodat :)").await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ let id = body["id"].as_i64().unwrap();
+ let (_, body) = request(&anna, "Holdfény", "Még egyszer").await;
+ assert_eq!(body["error"]["code"], "request_pending");
+
+ // Bea sees the request (and the badge); no messages before accepting.
+ assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
+ let list = app.get("/v1/forum/conversations", Some(&bea)).await;
+ assert_eq!(list["conversations"][0]["state"], "incoming");
+ assert_eq!(list["conversations"][0]["intro"], "Szia, olvastam a hozzászólásodat 🙂");
+ let (status, _) =
+ app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó"})).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&anna), Value::Null).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "only the recipient accepts");
+ let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/accept"), Some(&bea), Value::Null).await;
+ assert_eq!(status, StatusCode::NO_CONTENT);
+
+ // Messages both ways; unread counts; no read receipts.
+ let (status, msg) = app
+ .call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó <3"}))
+ .await;
+ assert_eq!(status, StatusCode::CREATED);
+ assert_eq!(msg["body"], "Hahó 🤍");
+ assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
+ let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await;
+ assert_eq!(shown["conversation"]["state"], "accepted");
+ assert_eq!(shown["messages"][0]["mine"], false);
+ app.call("POST", &format!("/v1/forum/conversations/{id}/read"), Some(&bea), json!({"message_id": msg["id"]})).await;
+ assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 0);
+ let reply = app
+ .call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&bea), json!({"body": "Szia!"}))
+ .await
+ .1;
+ // Nobody else sees the conversation.
+ let (status, _) = app.call("GET", &format!("/v1/forum/conversations/{id}"), Some(&cili), Value::Null).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+
+ // A reported message is what moderators see, with the messages before it.
+ let moderator = app.member("mod@example.com", "Őrangyal", &["moderator"]).await;
+ let (status, _) = app
+ .call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&cili), json!({"kind": "rude"}))
+ .await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "only a participant may report it");
+ let (status, _) = app
+ .call("POST", &format!("/v1/forum/messages/{}/report", reply["id"]), Some(&anna), json!({"kind": "rude"}))
+ .await;
+ assert_eq!(status, StatusCode::CREATED);
+ let reports = app.get("/v1/forum/mod/reports", Some(&moderator)).await;
+ let context = reports["reports"][0]["target"]["messages"].as_array().unwrap().clone();
+ assert_eq!(context.len(), 2);
+ assert_eq!(context[1]["reported"], true);
+ assert_eq!(context[0]["sender"]["nickname"], "Csendesvíz");
+
+ // A decline is silent: Cili's request just stays "sent" for her.
+ app.thread(&cili, "torzsasztal", "Én is itt vagyok").await;
+ app.season(&cili, 5, 10).await;
+ let (_, body) = request(&cili, "Holdfény", "Szia, beszélgetnénk?").await;
+ let second = body["id"].as_i64().unwrap();
+ app.call("POST", &format!("/v1/forum/conversations/{second}/decline"), Some(&bea), Value::Null).await;
+ let list = app.get("/v1/forum/conversations", Some(&cili)).await;
+ assert_eq!(list["conversations"][0]["state"], "outgoing");
+ assert!(
+ app.get("/v1/forum/conversations", Some(&bea)).await["conversations"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|c| c["id"] != second)
+ );
+ let (_, body) = request(&cili, "Holdfény", "Újra én").await;
+ assert_eq!(body["error"]["code"], "request_pending");
+
+ // Blocking stops the conversation; unblocking is the blocker's.
+ let (status, _) = app.call("POST", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await;
+ assert_eq!(status, StatusCode::NO_CONTENT);
+ let (status, _) =
+ app.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "?"})).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(
+ app.get(&format!("/v1/forum/conversations/{id}"), Some(&anna)).await["conversation"]["state"],
+ "outgoing"
+ );
+ assert_eq!(
+ app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await["conversation"]["state"],
+ "blocked_by_me"
+ );
+ let (status, _) =
+ app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&anna), Value::Null).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ let (status, _) = app.call("DELETE", &format!("/v1/forum/conversations/{id}/block"), Some(&bea), Value::Null).await;
+ assert_eq!(status, StatusCode::NO_CONTENT);
+}
diff --git a/services/frontend/src/app/forum/forum.css b/services/frontend/src/app/forum/forum.css
index 7868f19..24659a2 100644
--- a/services/frontend/src/app/forum/forum.css
+++ b/services/frontend/src/app/forum/forum.css
@@ -445,3 +445,56 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
.fmodlog { list-style: none; margin: 0; }
.fmodlog li { display: flex; flex-direction: column; gap: 2px; padding: 12px 16px; }
.fmodlog li + li { border-top: 1px solid var(--line); }
+
+/* --- reports --- */
+.frep { flex-basis: 100%; display: flex; flex-direction: column; gap: 10px; margin-top: 6px; padding: 14px; border: 1px solid var(--line-2); border-radius: 12px; background: var(--panel); }
+.frep-kind { display: flex; align-items: center; gap: 10px; min-height: 40px; font-size: 15px; cursor: pointer; }
+.frep-kind input { accent-color: var(--gold); width: 18px; height: 18px; flex: none; }
+.frep-crisis { padding: 10px 12px; border-radius: 10px; background: var(--f-blue-tint); color: var(--ink); font-size: 15px; line-height: 1.45; }
+.frep-crisis strong { color: var(--harmonic); }
+.forum-modchip {
+ display: inline-flex; align-items: center; min-height: 36px; padding: 0 12px; border-radius: 999px;
+ background: var(--f-red-tint); border: 1px solid var(--danger); color: var(--danger); font-size: 14px; font-weight: 600;
+ text-decoration: none; white-space: nowrap;
+}
+.forum-modchip:hover { color: var(--danger); background: var(--f-tint); }
+@media (max-width: 759px) { .forum-bar { flex-wrap: wrap; } .forum-modchip { order: 3; } }
+
+/* --- moderation page --- */
+.fmod-tabs { display: flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); align-self: flex-start; }
+.fmod-tabs a { min-height: 40px; display: inline-flex; align-items: center; padding: 0 16px; border-radius: 9px; color: var(--ink-2); text-decoration: none; font-weight: 500; }
+.fmod-tabs a[aria-current="page"] { background: var(--f-tint-strong); color: var(--gold); }
+.fmod-report { display: flex; flex-direction: column; gap: 10px; }
+.fmod-crisis { border-color: var(--harmonic); box-shadow: 0 0 0 1px var(--harmonic); }
+.fmod-report-head { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; flex-wrap: wrap; }
+.fmod-note { color: var(--ink-2); font-style: italic; }
+.fmod-target { display: flex; flex-direction: column; gap: 6px; padding: 12px 14px; border-radius: 10px; background: var(--panel-2); border: 1px solid var(--line); }
+.fmod-target .fp-body { font-size: 15px; }
+.fmod-chat { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 15px; }
+.fmod-chat-reported { padding: 4px 8px; border-radius: 6px; background: var(--f-red-tint); }
+
+/* --- private messages --- */
+.fmsg-h { font-family: var(--font-body) !important; font-size: 16px; font-weight: 600; color: var(--ink-2); }
+.fmsg-request { display: flex; flex-direction: column; gap: 12px; }
+.fmsg-intro { font-style: italic; color: var(--ink-2); }
+.fmsg-actions { display: flex; gap: 8px; flex-wrap: wrap; }
+.ft-row.fmsg-row { display: flex; }
+.fmsg-when { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; font-size: 13px; color: var(--muted); flex: none; }
+.freq { display: flex; flex-direction: column; gap: 8px; align-self: stretch; }
+.freq label { font-size: 14px; font-weight: 500; }
+.fchat { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 820px; margin: 0 auto; }
+.fchat-head { display: flex; align-items: center; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--line); }
+.fchat-who { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; flex: 1; min-width: 0; }
+.fchat-intro { font-size: 15px; color: var(--ink-2); font-style: italic; }
+.fchat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
+.fchat-msg { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; max-width: 86%; }
+.fchat-mine { align-self: flex-end; align-items: flex-end; }
+.fchat-bubble { padding: 10px 14px; border-radius: 16px 16px 16px 4px; background: var(--panel); border: 1px solid var(--line); }
+.fchat-mine .fchat-bubble { border-radius: 16px 16px 4px 16px; background: var(--f-tint-strong); border-color: transparent; }
+.fchat-bubble .fp-body { font-size: 16px; line-height: 1.5; }
+.fchat-meta { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
+.fchat-report { min-height: 32px; padding: 0 6px; border: 0; background: none; color: var(--muted); font: 400 12px var(--font-body); cursor: pointer; }
+.fchat-report:hover { color: var(--danger); }
+.fchat-msg .frep { width: min(420px, 86vw); }
+.fchat-compose { display: flex; flex-direction: column; gap: 6px; padding-top: 12px; border-top: 1px solid var(--line); }
+@media (min-width: 760px) { .forum-nav .fn-item { padding: 0 12px; } }
diff --git a/services/frontend/src/app/forum/layout.tsx b/services/frontend/src/app/forum/layout.tsx
index 83d111d..776e0ab 100644
--- a/services/frontend/src/app/forum/layout.tsx
+++ b/services/frontend/src/app/forum/layout.tsx
@@ -6,7 +6,7 @@ import { notFound } from "next/navigation";
import { ForumNav } from "@/components/forum/ForumNav";
import { ThemeToggle } from "@/components/forum/ThemeToggle";
import { PublicHeader } from "@/components/SiteHeader";
-import { FORUM_THEME_COOKIE, type ForumTheme, type ForumViewer } from "@/lib/forum";
+import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
import { forumEnabled, forumGet } from "@/lib/forumServer";
import "./forum.css";
@@ -23,10 +23,7 @@ export const metadata: Metadata = {
*/
export default async function ForumLayout({ children }: { children: React.ReactNode }) {
if (!forumEnabled()) notFound();
- const [nav, jar] = await Promise.all([
- forumGet<{ viewer: ForumViewer; followed: { new_replies: number } | null }>("/v1/forum/nav"),
- cookies(),
- ]);
+ const [nav, jar] = await Promise.all([forumGet("/v1/forum/nav"), cookies()]);
const viewer = nav.ok ? nav.data.viewer : null;
const theme: ForumTheme = jar.get(FORUM_THEME_COOKIE)?.value === "dark" ? "dark" : "light";
return (
@@ -42,7 +39,13 @@ export default async function ForumLayout({ children }: { children: React.ReactN
member={viewer?.member?.nickname ?? null}
loggedIn={viewer?.logged_in ?? false}
unread={nav.ok ? (nav.data.followed?.new_replies ?? 0) : 0}
+ messages={nav.ok ? (nav.data.messages ?? 0) : 0}
/>
+ {nav.ok && nav.data.reports ? (
+
+ Jelentés: {nav.data.reports}
+
+ ) : null}
{children}
diff --git a/services/frontend/src/app/forum/moderalas/ReportsList.tsx b/services/frontend/src/app/forum/moderalas/ReportsList.tsx
new file mode 100644
index 0000000..64faea1
--- /dev/null
+++ b/services/frontend/src/app/forum/moderalas/ReportsList.tsx
@@ -0,0 +1,154 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { PostBody } from "@/components/forum/PostBody";
+import { api, errorText } from "@/lib/api";
+import { REPORT_KINDS, type ReportEntry, ago, memberHref, threadHref } from "@/lib/forum";
+
+const STATUS: Record = { resolved: "Lezárva", dismissed: "Alaptalan" };
+
+/** The reports: open ones first (a possible crisis on top), with what was reported and the actions. */
+export function ReportsList({ initial }: { initial: ReportEntry[] }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(null);
+ const [error, setError] = useState(null);
+ const open = initial.filter((r) => r.status === "open");
+ const handled = initial.filter((r) => r.status !== "open");
+
+ async function act(r: ReportEntry, work: () => Promise) {
+ setBusy(r.id);
+ setError(null);
+ try {
+ await work();
+ router.refresh();
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ function removePost(r: ReportEntry) {
+ if (r.target?.type !== "post") return;
+ const reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik.");
+ if (!reason) return;
+ const id = r.target.id;
+ void act(r, () => api(`/forum/posts/${id}`, { method: "DELETE", body: { reason } }));
+ }
+
+ const card = (r: ReportEntry) => {
+ const kind = REPORT_KINDS.find((k) => k.kind === r.kind)?.label ?? r.kind;
+ const t = r.target;
+ return (
+
+
+ {kind}
+
+ {r.reporter} ·{" "}
+
+ {ago(r.created_at)}
+
+ {r.open_reports_of_target > 1 && r.status === "open" && ` · ${r.open_reports_of_target} jelentés`}
+
+
+ {r.note && „{r.note}”
}
+ {r.kind === "crisis" && r.status === "open" && (
+
+ Lehet, hogy valaki bajban van. Ha a hozzászólás közvetlen veszélyre utal, ne csak moderálj: írj neki
+ kedvesen, és mutasd meg a 116-123-as lelki elsősegély-számot.
+
+ )}
+ {t?.type === "post" && (
+
+
+ Hozzászólás:{" "}
+ {t.author ? {t.author.nickname} : "törölt tag"} ·{" "}
+ {t.thread.title}
+ {t.deleted && " · már eltávolítva"}
+
+
+
+ )}
+ {t?.type === "message" && (
+
+
Privát üzenet, az előzményeivel (csak a jelentés miatt látod):
+
+ {t.messages.map((m) => (
+
+ {m.sender?.nickname ?? "Törölt tag"}: {m.body}
+
+ ))}
+
+
+ )}
+ {r.status === "open" ? (
+
+ {t?.type === "post" && !t.deleted && (
+ removePost(r)}
+ >
+ Eltávolítás
+
+ )}
+ act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "resolve" } }))}
+ >
+ Kezeltem, lezárom
+
+ act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "dismiss" } }))}
+ >
+ Alaptalan
+
+
+ ) : (
+
+ {STATUS[r.status]}
+ {r.handled_by && ` · ${r.handled_by}`}
+
+ )}
+
+ );
+ };
+
+ return (
+ <>
+ {error && (
+
+ {error}
+
+ )}
+
+
+ Nyitott jelentések ({open.length})
+
+ {open.length === 0 ? Nincs nyitott jelentés.
: open.map(card)}
+
+ {handled.length > 0 && (
+
+
+ Az elmúlt 30 nap lezárt jelentései
+
+ {handled.map(card)}
+
+ )}
+ >
+ );
+}
diff --git a/services/frontend/src/app/forum/moderalas/page.tsx b/services/frontend/src/app/forum/moderalas/page.tsx
index a434fdb..dc3770b 100644
--- a/services/frontend/src/app/forum/moderalas/page.tsx
+++ b/services/frontend/src/app/forum/moderalas/page.tsx
@@ -1,10 +1,12 @@
import Link from "next/link";
import { notFound } from "next/navigation";
-import { type ModLogEntry, banText, memberHref, threadHref } from "@/lib/forum";
+import { type ModLogEntry, type ReportEntry, banText, memberHref, threadHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
-export const metadata = { title: "Moderálási napló", robots: { index: false } };
+import { ReportsList } from "./ReportsList";
+
+export const metadata = { title: "Moderálás", robots: { index: false } };
const ACTIONS: Record = {
delete_post: "hozzászólást távolított el",
@@ -17,48 +19,70 @@ const ACTIONS: Record = {
unlock: "feloldotta a szálat",
pin: "kitűzte a szálat",
unpin: "levette a kitűzést",
+ resolve_report: "lezárt egy jelentést",
+ dismiss_report: "alaptalannak ítélt egy jelentést",
};
-/** Every moderation step: who, what, why (moderators only). */
-export default async function ModLogPage() {
- const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
- if (!res.ok) notFound();
+type Props = { searchParams: Promise<{ nezet?: string }> };
+
+/** Moderators: the open reports, and the log of every moderation step. */
+export default async function ModerationPage({ searchParams }: Props) {
+ const log = (await searchParams).nezet === "naplo";
return (
-
Moderálási napló
- {res.data.entries.length === 0 ? (
-
Még nem volt moderálás.
- ) : (
-
- {res.data.entries.map((e) => (
-
-
- {new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
- {e.actor_kind === "ai" && " · AI"}
-
-
- {e.actor ?? "?"} {ACTIONS[e.action] ?? e.action}
- {e.target && (
- <>
- {" "}
- ( {e.target})
- >
- )}
- {e.thread && (
- <>
- {": "}
-
- {e.thread.title ?? `#${e.thread.id}`}
-
- >
- )}
- {e.until && ` · ${banText(e.until)}`}
-
- {e.reason && Ok: {e.reason} }
-
- ))}
-
- )}
+
Moderálás
+
+
+ Jelentések
+
+
+ Napló
+
+
+ {log ?
:
}
);
}
+
+async function ReportsView() {
+ const res = await forumGet<{ reports: ReportEntry[] }>("/v1/forum/mod/reports");
+ if (!res.ok) notFound();
+ return ;
+}
+
+async function LogView() {
+ const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
+ if (!res.ok) notFound();
+ if (res.data.entries.length === 0) return Még nem volt moderálás.
;
+ return (
+
+ {res.data.entries.map((e) => (
+
+
+ {new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
+ {e.actor_kind === "ai" && " · AI"}
+
+
+ {e.actor ?? "?"} {ACTIONS[e.action] ?? e.action}
+ {e.target && (
+ <>
+ {" "}
+ ( {e.target})
+ >
+ )}
+ {e.thread && (
+ <>
+ {": "}
+
+ {e.thread.title ?? `#${e.thread.id}`}
+
+ >
+ )}
+ {e.until && ` · ${banText(e.until)}`}
+
+ {e.reason && Ok: {e.reason} }
+
+ ))}
+
+ );
+}
diff --git a/services/frontend/src/app/forum/page.tsx b/services/frontend/src/app/forum/page.tsx
index c751195..83cc23d 100644
--- a/services/frontend/src/app/forum/page.tsx
+++ b/services/frontend/src/app/forum/page.tsx
@@ -235,7 +235,7 @@ export default async function ForumHomePage() {
)}
{viewer.moderator && (
- Moderálási napló
+ Moderálás: jelentések és napló
)}
diff --git a/services/frontend/src/app/forum/tag/[nev]/RequestPanel.tsx b/services/frontend/src/app/forum/tag/[nev]/RequestPanel.tsx
new file mode 100644
index 0000000..af7cbfb
--- /dev/null
+++ b/services/frontend/src/app/forum/tag/[nev]/RequestPanel.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+import type { MemberRelation } from "@/lib/forum";
+
+const INTRO_MAX = 200;
+
+/**
+ * Starting a private conversation from a profile: a request with a short
+ * introduction. Shows instead where things stand (sent, open, waiting for
+ * the viewer's answer), or why the viewer cannot start one yet.
+ */
+export function RequestPanel({ nickname, relation }: { nickname: string; relation: MemberRelation }) {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [intro, setIntro] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const id = relation.conversation_id;
+
+ if (relation.state === "accepted" && id) {
+ return (
+
+ Üzenetek
+
+ );
+ }
+ if (relation.state === "incoming" && id) {
+ return (
+
+ Beszélgetni szeretne veled: válaszolj
+
+ );
+ }
+ if (relation.state === "outgoing") return Beszélgetési kérésed elküldve, válaszra vár.
;
+ if (relation.state === "blocked_by_me")
+ return Letiltottad. A tiltást az üzeneteidnél oldhatod fel.
;
+ if (!relation.eligible) {
+ return Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba.
;
+ }
+ if (!relation.can_request) return null;
+
+ async function submit(e: React.FormEvent) {
+ e.preventDefault();
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await api<{ id: number }>("/forum/conversations", { body: { to: nickname, intro } });
+ router.push(`/forum/uzenetek/${res.id}`);
+ router.refresh();
+ } catch (err) {
+ setError(errorText(err));
+ setBusy(false);
+ }
+ }
+
+ if (!open) {
+ return (
+ setOpen(true)}>
+ Beszélgetést kezdeményezek
+
+ );
+ }
+ return (
+
+ );
+}
diff --git a/services/frontend/src/app/forum/tag/[nev]/page.tsx b/services/frontend/src/app/forum/tag/[nev]/page.tsx
index a76879e..5760cdc 100644
--- a/services/frontend/src/app/forum/tag/[nev]/page.tsx
+++ b/services/frontend/src/app/forum/tag/[nev]/page.tsx
@@ -9,6 +9,7 @@ import { type MemberProfile, ago, banText, threadHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer";
import { BanPanel } from "./BanPanel";
+import { RequestPanel } from "./RequestPanel";
type Props = { params: Promise<{ nev: string }> };
@@ -60,6 +61,7 @@ export default async function MemberPage({ params }: Props) {
Eltiltva ({banText(member.banned_until)}).{member.ban_reason && ` Indok: ${member.ban_reason}`}
)}
+ {res.data.relation && }
{member.own && (
Profil szerkesztése
diff --git a/services/frontend/src/app/forum/uzenetek/Conversations.tsx b/services/frontend/src/app/forum/uzenetek/Conversations.tsx
new file mode 100644
index 0000000..084b426
--- /dev/null
+++ b/services/frontend/src/app/forum/uzenetek/Conversations.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { AuthorLine } from "@/components/forum/AuthorLine";
+import { Avatar } from "@/components/forum/Avatar";
+import { api, errorText } from "@/lib/api";
+import { type ConversationItem, ago } from "@/lib/forum";
+
+export function Conversations({ initial }: { initial: ConversationItem[] }) {
+ const router = useRouter();
+ const [items, setItems] = useState(initial);
+ const [busy, setBusy] = useState(null);
+ const [error, setError] = useState(null);
+
+ async function answer(c: ConversationItem, action: "accept" | "decline" | "block" | "unblock") {
+ setBusy(c.id);
+ setError(null);
+ try {
+ await api(`/forum/conversations/${c.id}/${action === "unblock" ? "block" : action}`, {
+ method: action === "unblock" ? "DELETE" : "POST",
+ });
+ if (action === "accept") {
+ router.push(`/forum/uzenetek/${c.id}`);
+ router.refresh();
+ return;
+ }
+ setItems((list) => list.filter((x) => x.id !== c.id));
+ router.refresh();
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ const incoming = items.filter((c) => c.state === "incoming");
+ const open = items.filter((c) => c.state === "accepted");
+ const sent = items.filter((c) => c.state === "outgoing" || c.state === "expired");
+ const blocked = items.filter((c) => c.state === "blocked_by_me");
+
+ return (
+ <>
+ {error && (
+
+ {error}
+
+ )}
+
+ {incoming.length > 0 && (
+
+
+ Kérések
+
+ {incoming.map((c) => (
+
+
+ „{c.intro}”
+
+ answer(c, "accept")}
+ >
+ Elfogadom
+
+ answer(c, "decline")}
+ >
+ Nem most
+
+ window.confirm("Letiltod? Nem küldhet neked több kérést.") && answer(c, "block")}
+ >
+ Letiltom
+
+
+
+ ))}
+
+ )}
+
+
+
+ Beszélgetések
+
+ {open.length === 0 ? (
+
+ Még nincs beszélgetésed. Egy tag profilján kezdeményezhetsz egyet, ha már elérted a Kereső rangot.
+
+ ) : (
+
+ {open.map((c) => (
+
+
+
+
+ {c.other?.nickname ?? "Törölt tag"}
+
+ {c.last_message
+ ? `${c.last_message.mine ? "Te: " : ""}${c.last_message.excerpt}`
+ : "Még nincs üzenet."}
+
+
+
+ {c.last_message_at && (
+
+ {ago(c.last_message_at)}
+
+ )}
+ {c.unread > 0 && {c.unread} új }
+
+
+
+ ))}
+
+ )}
+
+
+ {sent.length > 0 && (
+
+
+ Elküldött kérések
+
+
+ {sent.map((c) => (
+
+
+
+ {c.other?.nickname ?? "Törölt tag"}
+ „{c.intro}”
+
+ {c.state === "expired" ? "Lejárt" : "Válaszra vár"}
+
+ ))}
+
+
+ )}
+
+ {blocked.length > 0 && (
+
+
+ Letiltottak
+
+
+ {blocked.map((c) => (
+
+
+
+ {c.other?.nickname ?? "Törölt tag"}
+
+ answer(c, "unblock")}
+ >
+ Tiltás feloldása
+
+
+ ))}
+
+
+ )}
+ >
+ );
+}
diff --git a/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx b/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx
new file mode 100644
index 0000000..eab6026
--- /dev/null
+++ b/services/frontend/src/app/forum/uzenetek/[id]/Chat.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { Avatar } from "@/components/forum/Avatar";
+import { Composer } from "@/components/forum/Composer";
+import { PostBody } from "@/components/forum/PostBody";
+import { ReportButton } from "@/components/forum/ReportButton";
+import { api, errorText } from "@/lib/api";
+import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
+
+/** How often an open conversation looks for new messages (while in front). */
+const POLL_MS = 15_000;
+
+function when(iso: string) {
+ return new Date(iso).toLocaleString("hu-HU", {
+ timeZone: "Europe/Budapest",
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+}
+
+/** One private conversation: the request (to answer, or waiting), then the messages. */
+export function Chat({ initial }: { initial: ConversationPage }) {
+ const router = useRouter();
+ const [page, setPage] = useState(initial);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const bottom = useRef(null);
+ const { conversation: c, messages } = page;
+ const base = `/forum/conversations/${c.id}`;
+ const lastId = messages.length ? messages[messages.length - 1].id : 0;
+ const other = c.other?.nickname ?? "Törölt tag";
+
+ useEffect(() => {
+ if (lastId) api(`${base}/read`, { body: { message_id: lastId } }).catch(() => {});
+ bottom.current?.scrollIntoView({ block: "end" });
+ }, [base, lastId]);
+
+ const refresh = useCallback(async () => {
+ try {
+ setPage(await api(base));
+ } catch {
+ /* retried on the next round */
+ }
+ }, [base]);
+
+ useEffect(() => {
+ if (c.state !== "accepted") return;
+ const timer = window.setInterval(() => {
+ if (document.visibilityState === "visible") void refresh();
+ }, POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [c.state, refresh]);
+
+ async function run(work: () => Promise) {
+ setBusy(true);
+ setError(null);
+ try {
+ await work();
+ return true;
+ } catch (e) {
+ setError(errorText(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function send(text: string) {
+ setBusy(true);
+ setError(null);
+ try {
+ const msg = await api(`${base}/messages`, { body: { body: text } });
+ setPage((p) => ({ ...p, messages: [...p.messages, msg] }));
+ return true;
+ } catch (e) {
+ setError(errorText(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function answer(action: "accept" | "decline" | "block" | "unblock") {
+ const ok = await run(() =>
+ api(`${base}/${action === "unblock" ? "block" : action}`, { method: action === "unblock" ? "DELETE" : "POST" }),
+ );
+ if (!ok) return;
+ if (action === "decline") {
+ router.push("/forum/uzenetek");
+ router.refresh();
+ return;
+ }
+ await refresh();
+ router.refresh();
+ }
+
+ return (
+
+
+ Üzenetek
+
+
+
+
+ {c.requested_by_me ? "A kérésed" : `${other} kérése`}: „{c.intro}”
+
+
+ {c.state === "incoming" && (
+
+
{other} szeretne beszélgetni veled.
+
+ answer("accept")}>
+ Elfogadom
+
+ answer("decline")}>
+ Nem most
+
+ answer("block")}>
+ Letiltom
+
+
+
+ )}
+ {(c.state === "outgoing" || c.state === "expired") && (
+
+ {c.state === "expired"
+ ? "A kérésedre nem jött válasz, és lejárt."
+ : `A kérésedet elküldtük. Ha ${other} elfogadja, itt tudtok beszélgetni.`}
+
+ )}
+
+ {messages.length > 0 && (
+
+ {messages.map((m) => (
+
+
+
+
+ {when(m.created_at)}
+
+ {!m.mine && }
+
+
+ ))}
+
+ )}
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {c.state === "accepted" && (
+
+
+
+ Csak szöveg és emoji. A linkek nem kattinthatók. A moderátorok csak jelentett üzenetet látnak.
+
+
+ )}
+ {c.state === "blocked_by_me" && (
+
+
Letiltottad. Nem írhat neked, és te sem neki.
+
answer("unblock")}>
+ Tiltás feloldása
+
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/forum/uzenetek/[id]/page.tsx b/services/frontend/src/app/forum/uzenetek/[id]/page.tsx
new file mode 100644
index 0000000..8ac4693
--- /dev/null
+++ b/services/frontend/src/app/forum/uzenetek/[id]/page.tsx
@@ -0,0 +1,21 @@
+import { notFound, redirect } from "next/navigation";
+
+import type { ConversationPage } from "@/lib/forum";
+import { forumGet } from "@/lib/forumServer";
+
+import { Chat } from "./Chat";
+
+export const metadata = { title: "Beszélgetés", robots: { index: false } };
+
+type Props = { params: Promise<{ id: string }> };
+
+export default async function ConversationView({ params }: Props) {
+ const { id } = await params;
+ if (!/^\d{1,15}$/.test(id)) notFound();
+ const res = await forumGet(`/v1/forum/conversations/${id}`);
+ if (!res.ok) {
+ if (res.status === 401) redirect(`/belepes?vissza=/forum/uzenetek/${id}`);
+ notFound();
+ }
+ return ;
+}
diff --git a/services/frontend/src/app/forum/uzenetek/page.tsx b/services/frontend/src/app/forum/uzenetek/page.tsx
new file mode 100644
index 0000000..ffc6e2e
--- /dev/null
+++ b/services/frontend/src/app/forum/uzenetek/page.tsx
@@ -0,0 +1,24 @@
+import { redirect } from "next/navigation";
+
+import type { ConversationItem } from "@/lib/forum";
+import { forumGet } from "@/lib/forumServer";
+
+import { Conversations } from "./Conversations";
+
+export const metadata = { title: "Üzenetek", robots: { index: false } };
+
+/** Private messages: requests to answer, conversations, requests sent. */
+export default async function MessagesPage() {
+ const res = await forumGet<{ conversations: ConversationItem[] }>("/v1/forum/conversations");
+ if (!res.ok) redirect("/belepes?vissza=/forum/uzenetek");
+ return (
+
+
Üzenetek
+
+ Privát beszélgetés csak kéréssel indulhat. A kérést elfogadhatod, csendben elutasíthatod (a küldő ezt nem
+ látja), vagy letilthatod a küldőt.
+
+
+
+ );
+}
diff --git a/services/frontend/src/components/forum/ForumNav.tsx b/services/frontend/src/components/forum/ForumNav.tsx
index 36e73de..def7a27 100644
--- a/services/frontend/src/components/forum/ForumNav.tsx
+++ b/services/frontend/src/components/forum/ForumNav.tsx
@@ -22,7 +22,7 @@ function usePresence(member: boolean) {
}, [member]);
}
-function Icon({ name }: { name: "forum" | "followed" | "new" | "profile" }) {
+function Icon({ name }: { name: "forum" | "followed" | "new" | "messages" | "profile" }) {
return (
{name === "forum" && (
@@ -43,6 +43,12 @@ function Icon({ name }: { name: "forum" | "followed" | "new" | "profile" }) {
>
)}
+ {name === "messages" && (
+ <>
+
+
+ >
+ )}
{name === "profile" && (
<>
@@ -57,7 +63,17 @@ function Icon({ name }: { name: "forum" | "followed" | "new" | "profile" }) {
* The forum's own menu: a bar at the bottom of the screen on phones, tabs
* above the content on wider screens. `unread`: new replies in followed threads.
*/
-export function ForumNav({ member, loggedIn, unread }: { member: string | null; loggedIn: boolean; unread: number }) {
+export function ForumNav({
+ member,
+ loggedIn,
+ unread,
+ messages,
+}: {
+ member: string | null;
+ loggedIn: boolean;
+ unread: number;
+ messages: number;
+}) {
const path = usePathname();
usePresence(member !== null);
const items = [
@@ -80,6 +96,17 @@ export function ForumNav({ member, loggedIn, unread }: { member: string | null;
icon: "new" as const,
current: path.startsWith("/forum/uj"),
},
+ {
+ href: member
+ ? "/forum/uzenetek"
+ : loggedIn
+ ? "/forum/beallitasok?vissza=/forum/uzenetek"
+ : "/belepes?vissza=/forum/uzenetek",
+ label: "Üzenetek",
+ icon: "messages" as const,
+ current: path.startsWith("/forum/uzenetek"),
+ badge: messages,
+ },
{
href: member
? `/forum/tag/${encodeURIComponent(member)}`
diff --git a/services/frontend/src/components/forum/ReportButton.tsx b/services/frontend/src/components/forum/ReportButton.tsx
new file mode 100644
index 0000000..eb18135
--- /dev/null
+++ b/services/frontend/src/components/forum/ReportButton.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+import { REPORT_KINDS, type ReportKind } from "@/lib/forum";
+
+/** What to do when someone may be in danger: shown right after a crisis report. */
+export function CrisisHelp() {
+ return (
+
+ Ha azonnali veszélyt látsz, hívd a 112 -t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal
+ hívható száma: 116-123 .
+
+ );
+}
+
+/**
+ * "Jelentés" on a post or a private message: what the problem is, an
+ * optional note, and a thank-you (with the helpline for a crisis report).
+ */
+export function ReportButton({ path, className = "fp-tool" }: { path: string; className?: string }) {
+ const [open, setOpen] = useState(false);
+ const [kind, setKind] = useState("");
+ const [note, setNote] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const [done, setDone] = useState<{ crisis: boolean } | null>(null);
+
+ async function submit(e: React.FormEvent) {
+ e.preventDefault();
+ if (!kind) return;
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await api<{ crisis: boolean }>(path, { body: { kind, note } });
+ setDone(res);
+ } catch (err) {
+ setError(errorText(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ if (done) {
+ return (
+
+
Köszönjük, a moderátorok megnézik.
+ {done.crisis &&
}
+
+ );
+ }
+ if (!open) {
+ return (
+ setOpen(true)}>
+ Jelentés
+
+ );
+ }
+ return (
+
+
+ Mi a gond?
+ {REPORT_KINDS.map((k) => (
+
+ setKind(k.kind)} />
+ {k.label}
+
+ ))}
+
+ {kind === "crisis" && }
+
+ Megjegyzés
+
+ setNote(e.target.value)}
+ placeholder={kind === "other" ? "Írd le röviden, mi a gond." : "Megjegyzés (nem kötelező)"}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ setOpen(false)}>
+ Mégse
+
+
+ {busy ? "Küldés…" : "Jelentés küldése"}
+
+
+
+ );
+}
diff --git a/services/frontend/src/components/forum/ThreadView.tsx b/services/frontend/src/components/forum/ThreadView.tsx
index 7067415..e1f8a99 100644
--- a/services/frontend/src/components/forum/ThreadView.tsx
+++ b/services/frontend/src/components/forum/ThreadView.tsx
@@ -10,6 +10,7 @@ import { AuthorLine, signsText } from "./AuthorLine";
import { Avatar } from "./Avatar";
import { Composer } from "./Composer";
import { PostBody } from "./PostBody";
+import { ReportButton } from "./ReportButton";
/** How often the open thread looks for new replies (while the page is in front). */
const POLL_MS = 30_000;
@@ -294,6 +295,7 @@ function PostCard({
Törlés
)}
+ {viewer.logged_in && !post.own && }
{viewer.moderator && !post.own && (
actions.remove(post)}>
Eltávolítás
diff --git a/services/frontend/src/lib/forum.ts b/services/frontend/src/lib/forum.ts
index b3a6c5b..35296b5 100644
--- a/services/frontend/src/lib/forum.ts
+++ b/services/frontend/src/lib/forum.ts
@@ -142,6 +142,7 @@ export interface ForumMe {
export interface MemberProfile {
viewer: ForumViewer;
+ relation: MemberRelation | null;
member: {
author: ForumAuthor;
bio: string;
@@ -257,3 +258,91 @@ export function banText(until: string | null): string {
if (until === "infinity") return "véglegesen";
return `eddig: ${new Date(until).toLocaleString("hu-HU", { timeZone: "Europe/Budapest", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit" })}`;
}
+
+/** The viewer's relation to a member (profile page). */
+export interface MemberRelation {
+ conversation_id: number | null;
+ state: ConversationState | null;
+ can_request: boolean;
+ eligible: boolean;
+}
+
+export type ConversationState = "accepted" | "incoming" | "outgoing" | "expired" | "blocked_by_me" | "closed";
+
+export interface ConversationItem {
+ id: number;
+ other: ForumAuthor | null;
+ state: ConversationState;
+ intro: string;
+ created_at: string;
+ last_message_at: string | null;
+ last_message: { excerpt: string; mine: boolean } | null;
+ unread: number;
+}
+
+export interface ChatMessage {
+ id: number;
+ mine: boolean;
+ body: string;
+ created_at: string;
+}
+
+export interface ConversationPage {
+ viewer: ForumViewer;
+ conversation: {
+ id: number;
+ other: ForumAuthor | null;
+ state: ConversationState;
+ intro: string;
+ requested_by_me: boolean;
+ created_at: string;
+ };
+ messages: ChatMessage[];
+}
+
+export type ReportKind = "spam" | "ad" | "rude" | "crisis" | "illegal" | "other";
+
+export const REPORT_KINDS: { kind: ReportKind; label: string }[] = [
+ { kind: "rude", label: "Bántó, kioktató vagy sértő" },
+ { kind: "ad", label: "Szolgáltatást hirdet (jóslás, gyógyítás, tanfolyam)" },
+ { kind: "spam", label: "Kéretlen reklám, spam" },
+ { kind: "crisis", label: "Aggódom érte: lelki krízisben lehet" },
+ { kind: "illegal", label: "Jogsértő tartalom" },
+ { kind: "other", label: "Más (írd le)" },
+];
+
+export interface ReportEntry {
+ id: number;
+ kind: ReportKind;
+ note: string;
+ reporter: string;
+ status: "open" | "resolved" | "dismissed";
+ handled_by: string | null;
+ handled_at: string | null;
+ created_at: string;
+ open_reports_of_target: number;
+ target:
+ | {
+ type: "post";
+ id: number;
+ thread: { id: number; title: string; slug: string };
+ author: ForumAuthor | null;
+ body: string;
+ deleted: boolean;
+ }
+ | {
+ type: "message";
+ id: number;
+ conversation_id: number | null;
+ messages: { id: number; sender: ForumAuthor | null; body: string; created_at: string; reported: boolean }[];
+ }
+ | null;
+}
+
+/** The forum menu's counts. */
+export interface ForumNavData {
+ viewer: ForumViewer;
+ followed: { new_replies: number } | null;
+ messages: number | null;
+ reports: number | null;
+}
diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs
index ae81d67..41e7082 100644
--- a/services/worker/src/main.rs
+++ b/services/worker/src/main.rs
@@ -159,9 +159,10 @@ async fn main() -> anyhow::Result<()> {
match (&config.telegram_bot_token, &config.telegram_chat_id) {
_ if !tasks.notify => {}
(Some(token), Some(chat)) => {
- tracing::info!("purchase notices enabled (Telegram)");
+ tracing::info!("purchase and forum report notices enabled (Telegram)");
let telegram = telegram::Telegram::new(&config.telegram_api_url, token, chat);
- jobs.spawn(notify::run(pool.clone(), telegram, config.poll_interval, stop.clone()));
+ let base = config.public_base_url.clone();
+ jobs.spawn(notify::run(pool.clone(), telegram, base, config.poll_interval, stop.clone()));
}
_ => tracing::info!("TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set: no purchase notices"),
}
diff --git a/services/worker/src/notify.rs b/services/worker/src/notify.rs
index b926b70..8c8c09b 100644
--- a/services/worker/src/notify.rs
+++ b/services/worker/src/notify.rs
@@ -1,6 +1,7 @@
//! The `notify` task: a Telegram notice to the operator about every paid
//! checkout ("Páros csomag, 6 000 Ft"), once. It runs on its own, apart from
-//! invoicing, and carries no personal data of the buyer.
+//! invoicing, and carries no personal data of the buyer. Also every new forum
+//! report (what kind, and the moderators' page), a possible crisis first.
//!
//! A purchase counts as notified when Telegram took the message, or refused
//! it for good (a wrong token or chat: logged as an error); after an outage
@@ -65,11 +66,63 @@ pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result) {
+/// The notice of a forum report: its kind only (nothing of the post or the
+/// people), and where moderators handle it.
+fn report_text(kind: &str, base_url: Option<&str>) -> String {
+ let what = match kind {
+ "crisis" => "⚠️ LELKI KRÍZIS lehet: valaki aggódik egy tagért",
+ "illegal" => "🚩 Jogsértő tartalom",
+ "rude" => "🚩 Bántó, sértő hozzászólás",
+ "ad" => "🚩 Szolgáltatás hirdetése",
+ "spam" => "🚩 Spam",
+ _ => "🚩 Egyéb",
+ };
+ let link = base_url.map(|b| format!("\n{}/forum/moderalas", b.trim_end_matches('/'))).unwrap_or_default();
+ format!("Fórumjelentés: {what}{link}")
+}
+
+/// Sends the notices of the forum reports not notified yet (crisis ones first).
+pub async fn reports_once(db: &PgPool, telegram: &Telegram, base_url: Option<&str>) -> Result {
+ let mut tx = db.begin().await?;
+ let due: Vec<(i64, String)> = sqlx::query_as(
+ "SELECT id, kind FROM forum.reports WHERE notified_at IS NULL \
+ ORDER BY kind <> 'crisis', created_at LIMIT $1 FOR UPDATE SKIP LOCKED",
+ )
+ .bind(BATCH)
+ .fetch_all(&mut *tx)
+ .await?;
+ let mut sent = 0;
+ for (id, kind) in due {
+ match telegram.send(&report_text(&kind, base_url)).await {
+ Ok(()) => sent += 1,
+ Err(e) if e.permanent => {
+ tracing::error!(report = id, error = %e.message, "telegram refused the report notice; check TELEGRAM_*");
+ }
+ Err(e) => {
+ tracing::warn!(report = id, error = %e.message, "report notice not sent yet");
+ break;
+ }
+ }
+ sqlx::query("UPDATE forum.reports SET notified_at = now() WHERE id = $1").bind(id).execute(&mut *tx).await?;
+ }
+ tx.commit().await?;
+ Ok(sent)
+}
+
+pub async fn run(
+ db: PgPool,
+ telegram: Telegram,
+ base_url: Option,
+ interval: Duration,
+ stop: watch::Receiver,
+) {
loop {
if let Err(e) = run_once(&db, &telegram).await {
tracing::error!(error = %e, "purchase notices");
}
+ if let Err(e) = reports_once(&db, &telegram, base_url.as_deref()).await {
+ tracing::error!(error = %e, "forum report notices");
+ }
tokio::select! {
() = tokio::time::sleep(interval) => {}
() = crate::stopped(stop.clone()) => break,
@@ -128,6 +181,56 @@ mod tests {
id
}
+ #[test]
+ fn report_texts() {
+ assert_eq!(
+ report_text("crisis", Some("https://sorsfonalak.hu/")),
+ "Fórumjelentés: ⚠️ LELKI KRÍZIS lehet: valaki aggódik egy tagért\nhttps://sorsfonalak.hu/forum/moderalas"
+ );
+ assert_eq!(report_text("ad", None), "Fórumjelentés: 🚩 Szolgáltatás hirdetése");
+ }
+
+ #[sqlx::test(migrator = "db::MIGRATOR")]
+ async fn report_notices_go_out_once(pool: PgPool) {
+ let fake = Arc::new(Fake::default());
+ let url = fake_telegram(fake.clone()).await;
+ let telegram = Telegram::new(&url, "TOKEN", "42");
+ let user = uuid::Uuid::now_v7();
+ sqlx::query("INSERT INTO users (id, email) VALUES ($1, 'a@example.com')")
+ .bind(user)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let thread: i64 = sqlx::query_scalar(
+ "INSERT INTO forum.threads (topic_id, author_id, title) VALUES (2, $1, 'Teszt') RETURNING id",
+ )
+ .bind(user)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ let post: i64 = sqlx::query_scalar(
+ "INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'x') RETURNING id",
+ )
+ .bind(thread)
+ .bind(user)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ for kind in ["spam", "crisis"] {
+ sqlx::query("INSERT INTO forum.reports (post_id, kind) VALUES ($1, $2)")
+ .bind(post)
+ .bind(kind)
+ .execute(&pool)
+ .await
+ .unwrap();
+ }
+ assert_eq!(reports_once(&pool, &telegram, None).await.unwrap(), 2);
+ assert_eq!(reports_once(&pool, &telegram, None).await.unwrap(), 0);
+ let messages = fake.messages.lock().unwrap();
+ assert!(messages[0]["text"].as_str().unwrap().contains("KRÍZIS"), "the crisis one first");
+ assert!(messages[1]["text"].as_str().unwrap().contains("Spam"));
+ }
+
#[test]
fn notice_texts() {
assert_eq!(
diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs
index 886e71f..3583c32 100644
--- a/services/worker/src/tests.rs
+++ b/services/worker/src/tests.rs
@@ -829,7 +829,10 @@ mod analyses {
assert_eq!(body["response_format"]["json_schema"]["name"], "question_answer");
let user = body["messages"][1]["content"].as_str().unwrap();
assert!(user.contains("- Sun: Pisces") && user.contains("# Csendes erő"), "chart data and analysis");
- assert!(user.contains("Kérdés:\n\nMi az erősségem?\n \nVálasz: A kitartásod."), "earlier answers");
+ assert!(
+ user.contains("Kérdés:\n\nMi az erősségem?\n \nVálasz: A kitartásod."),
+ "earlier answers"
+ );
assert!(user.contains("\nÉs a munkában?\n ") && user.contains("legfeljebb 250 szóban"));
for secret in ["1990", "14:30", "Szeged"] {
assert!(!user.contains(secret), "{secret} leaked");