Forum: reports for moderators and private messages by request

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 10:48:28 +00:00
co-authored by Claude Opus 5.5
parent 36b38525c3
commit 4def9569b1
28 changed files with 2322 additions and 58 deletions
+11 -1
View File
@@ -172,7 +172,17 @@ async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>
/// For the forum's menu on every page: who the viewer is, and the badge.
pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
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<Json<Value>> {
+1
View File
@@ -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,
+506
View File
@@ -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<Uuid>,
created_at: OffsetDateTime,
responded_at: Option<OffsetDateTime>,
last_message_at: Option<OffsetDateTime>,
}
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<Value> {
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<Conversation> = 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<String> {
let intro: String = raw.split_whitespace().collect::<Vec<_>>().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<NewRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<Conversation> = 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<Conversation> {
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<Uuid>,
body: String,
}
/// The viewer's conversations and requests, and how many messages are unread.
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
let me = viewer.require_member()?.user_id;
let rows: Vec<Conversation> = 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<i64> = rows.iter().map(|c| c.id).collect();
let last: Vec<LastMessage> = 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<Value> = 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<i64, sqlx::Error> {
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<Json<Value>> {
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<Uuid>, 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::<Vec<_>>(),
})))
}
/// The recipient answers a request: accept, decline (silently) or block.
pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static str) -> ApiResult<StatusCode> {
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<StatusCode> {
respond(state, viewer, path, "accept").await
}
pub async fn decline(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "decline").await
}
pub async fn block(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
respond(state, viewer, path, "block").await
}
pub async fn unblock(state: St, viewer: Viewer, path: IdPath) -> ApiResult<StatusCode> {
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<NewMessage>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<ReadMark>,
) -> ApiResult<StatusCode> {
let me = viewer.require_member()?.user_id;
own(&state.db, me, id).await?;
let last: Option<i64> = 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)
}
+13
View File
@@ -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<AppState>) -> 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)
+31 -1
View File
@@ -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<i64>,
) -> 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<i64>,
thread_title: Option<String>,
post_id: Option<i64>,
report_id: Option<i64>,
reason: Option<String>,
until: Option<OffsetDateTime>,
created_at: OffsetDateTime,
@@ -173,7 +201,8 @@ pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<LogRow> = 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<Json<Value>> {
"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),
+1
View File
@@ -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,
+341
View File
@@ -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<String>,
}
fn check(req: &ReportRequest) -> ApiResult<String> {
if !KINDS.contains(&req.kind.as_str()) {
return Err(ApiError::bad("Válaszd ki, mi a gond."));
}
let note = req.note.as_deref().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
if note.chars().count() > NOTE_MAX {
return Err(ApiError::bad(format!("A megjegyzés legfeljebb {NOTE_MAX} karakter lehet.")));
}
if req.kind == "other" && note.chars().count() < 3 {
return Err(ApiError::bad("Írd le röviden, mi a gond."));
}
Ok(note)
}
async fn within_limit(db: &PgPool, user: Uuid) -> ApiResult<()> {
let today: i64 = sqlx::query_scalar(
"SELECT count(*) FROM forum.reports WHERE reporter_id = $1 AND created_at > now() - interval '24 hours'",
)
.bind(user)
.fetch_one(db)
.await?;
if today >= PER_DAY {
return Err(ApiError::Limited("Ma már sok jelentést küldtél. Holnap újra lehet.".into()));
}
Ok(())
}
fn received(kind: &str) -> Json<Value> {
Json(json!({ "received": true, "crisis": kind == "crisis" }))
}
/// Reports a post (not one's own). A second report of the same post by the
/// same user while the first is open changes nothing.
pub async fn report_post(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let post: Option<(i64, Option<Uuid>)> =
sqlx::query_as("SELECT thread_id, author_id FROM forum.posts WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?;
let (thread_id, author) = post.ok_or(ApiError::NotFound("post"))?;
readable_thread(&state.db, &viewer, thread_id).await?;
if author == Some(user.id) {
return Err(ApiError::bad("A saját hozzászólásodat nem jelentheted."));
}
within_limit(&state.db, user.id).await?;
sqlx::query(
"INSERT INTO forum.reports (post_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
)
.bind(id)
.bind(user.id)
.bind(&req.kind)
.bind(&note)
.execute(&state.db)
.await?;
tracing::info!(post = id, kind = %req.kind, "post reported");
Ok((StatusCode::CREATED, received(&req.kind)))
}
/// Reports a private message received in one's own conversation.
pub async fn report_message(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<ReportRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let user = viewer.require_user()?;
let note = check(&req)?;
let found: Option<(Option<Uuid>,)> = sqlx::query_as(
"SELECT m.sender_id FROM forum.messages m JOIN forum.conversations c ON c.id = m.conversation_id \
WHERE m.id = $1 AND $2 IN (c.user_a, c.user_b)",
)
.bind(id)
.bind(user.id)
.fetch_optional(&state.db)
.await?;
let (sender,) = found.ok_or(ApiError::NotFound("message"))?;
if sender == Some(user.id) {
return Err(ApiError::bad("A saját üzenetedet nem jelentheted."));
}
within_limit(&state.db, user.id).await?;
sqlx::query(
"INSERT INTO forum.reports (message_id, reporter_id, kind, note) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
)
.bind(id)
.bind(user.id)
.bind(&req.kind)
.bind(&note)
.execute(&state.db)
.await?;
tracing::info!(message = id, kind = %req.kind, "message reported");
Ok((StatusCode::CREATED, received(&req.kind)))
}
#[derive(sqlx::FromRow)]
struct ReportRow {
id: i64,
post_id: Option<i64>,
message_id: Option<i64>,
reporter: Option<String>,
kind: String,
note: String,
status: String,
handled_by: Option<String>,
handled_at: Option<OffsetDateTime>,
created_at: OffsetDateTime,
}
#[derive(sqlx::FromRow)]
struct PostTarget {
id: i64,
thread_id: i64,
title: String,
author_id: Option<Uuid>,
body: String,
deleted: bool,
}
#[derive(sqlx::FromRow)]
struct MessageRow {
id: i64,
conversation_id: i64,
sender_id: Option<Uuid>,
body: String,
created_at: OffsetDateTime,
}
/// Open reports (the oldest first, crisis ones before all), and the last
/// handled ones, with what was reported.
pub async fn list(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_moderator()?;
let rows: Vec<ReportRow> = sqlx::query_as(
"SELECT r.id, r.post_id, r.message_id, COALESCE(rm.nickname, 'tag') AS reporter, r.kind, r.note, r.status, \
COALESCE(hm.nickname, hu.display_name) AS handled_by, r.handled_at, r.created_at \
FROM forum.reports r \
LEFT JOIN forum.members rm ON rm.user_id = r.reporter_id \
LEFT JOIN forum.members hm ON hm.user_id = r.handled_by \
LEFT JOIN users hu ON hu.id = r.handled_by \
WHERE r.status = 'open' OR r.handled_at > now() - interval '30 days' \
ORDER BY r.status <> 'open', r.kind <> 'crisis', \
CASE WHEN r.status = 'open' THEN r.created_at END, r.handled_at DESC \
LIMIT 200",
)
.fetch_all(&state.db)
.await?;
let post_ids: Vec<i64> = rows.iter().filter_map(|r| r.post_id).collect();
let posts: Vec<PostTarget> = sqlx::query_as(
"SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.deleted_at IS NOT NULL AS deleted \
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.id = ANY($1)",
)
.bind(&post_ids)
.fetch_all(&state.db)
.await?;
let message_ids: Vec<i64> = rows.iter().filter_map(|r| r.message_id).collect();
// Each reported message with the few before it in its conversation.
let messages: Vec<(i64, MessageRow)> = sqlx::query_as::<_, (i64, i64, i64, Option<Uuid>, String, OffsetDateTime)>(
"SELECT r.id AS reported, m.id, m.conversation_id, m.sender_id, m.body, m.created_at \
FROM forum.messages r \
JOIN LATERAL (SELECT * FROM forum.messages m WHERE m.conversation_id = r.conversation_id AND m.id <= r.id \
ORDER BY m.id DESC LIMIT $2) m ON true \
WHERE r.id = ANY($1) ORDER BY m.id",
)
.bind(&message_ids)
.bind(MESSAGE_CONTEXT)
.fetch_all(&state.db)
.await?
.into_iter()
.map(|(reported, id, conversation_id, sender_id, body, created_at)| {
(reported, MessageRow { id, conversation_id, sender_id, body, created_at })
})
.collect();
let people = authors(
&state.db,
posts.iter().filter_map(|p| p.author_id).chain(messages.iter().filter_map(|(_, m)| m.sender_id)),
)
.await?;
let open_counts: Vec<(Option<i64>, Option<i64>, i64)> =
sqlx::query_as("SELECT post_id, message_id, count(*) FROM forum.reports WHERE status = 'open' GROUP BY 1, 2")
.fetch_all(&state.db)
.await?;
let entries: Vec<Value> = rows
.into_iter()
.map(|r| {
let target = if let Some(post_id) = r.post_id {
posts.iter().find(|p| p.id == post_id).map(|p| {
json!({
"type": "post",
"id": p.id,
"thread": { "id": p.thread_id, "title": p.title, "slug": text::slug(&p.title) },
"author": p.author_id.and_then(|a| people.get(&a).cloned()),
"body": p.body,
"deleted": p.deleted,
})
})
} else {
let id = r.message_id.unwrap_or_default();
let context: Vec<Value> = messages
.iter()
.filter(|(reported, _)| *reported == id)
.map(|(_, m)| {
json!({
"id": m.id,
"sender": m.sender_id.and_then(|s| people.get(&s).cloned()),
"body": m.body,
"created_at": rfc3339(m.created_at),
"reported": m.id == id,
})
})
.collect();
let conversation =
messages.iter().find(|(reported, _)| *reported == id).map(|(_, m)| m.conversation_id);
Some(json!({ "type": "message", "id": id, "conversation_id": conversation, "messages": context }))
};
let reports = open_counts
.iter()
.find(|(p, m, _)| *p == r.post_id && *m == r.message_id)
.map(|(_, _, n)| *n)
.unwrap_or(0);
json!({
"id": r.id,
"kind": r.kind,
"note": r.note,
"reporter": r.reporter,
"status": r.status,
"handled_by": r.handled_by,
"handled_at": r.handled_at.map(rfc3339),
"created_at": rfc3339(r.created_at),
"open_reports_of_target": reports,
"target": target,
})
})
.collect();
Ok(Json(json!({ "reports": entries })))
}
#[derive(Deserialize)]
pub struct Handle {
/// `resolve`: acted on (or nothing needed beyond what was done);
/// `dismiss`: the report was unfounded.
action: String,
}
/// Closes a report, and every other open report of the same post or message.
pub async fn handle(
State(state): St,
viewer: Viewer,
WithRejection(Path(id), _): IdPath,
WithRejection(Json(req), _): Body<Handle>,
) -> ApiResult<StatusCode> {
let moderator = viewer.require_moderator()?;
let (status, action) = match req.action.as_str() {
"resolve" => ("resolved", Action::ResolveReport),
"dismiss" => ("dismissed", Action::DismissReport),
_ => return Err(ApiError::bad("Ismeretlen művelet.")),
};
let report: Option<(Option<i64>, Option<i64>)> =
sqlx::query_as("SELECT post_id, message_id FROM forum.reports WHERE id = $1")
.bind(id)
.fetch_optional(&state.db)
.await?;
let (post_id, message_id) = report.ok_or(ApiError::NotFound("report"))?;
let mut tx = state.db.begin().await?;
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<i64, sqlx::Error> {
sqlx::query_scalar("SELECT count(*) FROM forum.reports WHERE status = 'open'").fetch_one(db).await
}
+185
View File
@@ -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);
}
+53
View File
@@ -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; } }
+8 -5
View File
@@ -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<ForumNavData>("/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 ? (
<Link href="/forum/moderalas" className="forum-modchip">
Jelentés: {nav.data.reports}
</Link>
) : null}
<ThemeToggle initial={theme} />
</div>
<main className="forum-main">{children}</main>
@@ -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<string, string> = { 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<number | null>(null);
const [error, setError] = useState<string | null>(null);
const open = initial.filter((r) => r.status === "open");
const handled = initial.filter((r) => r.status !== "open");
async function act(r: ReportEntry, work: () => Promise<unknown>) {
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 (
<article
key={r.id}
className={
r.kind === "crisis" && r.status === "open" ? "fh-card fmod-report fmod-crisis" : "fh-card fmod-report"
}
>
<div className="fmod-report-head">
<strong>{kind}</strong>
<span className="hint">
{r.reporter} ·{" "}
<time suppressHydrationWarning dateTime={r.created_at}>
{ago(r.created_at)}
</time>
{r.open_reports_of_target > 1 && r.status === "open" && ` · ${r.open_reports_of_target} jelentés`}
</span>
</div>
{r.note && <p className="fmod-note">„{r.note}”</p>}
{r.kind === "crisis" && r.status === "open" && (
<p className="hint warn">
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.
</p>
)}
{t?.type === "post" && (
<div className="fmod-target">
<span className="hint">
Hozzászólás:{" "}
{t.author ? <Link href={memberHref(t.author.nickname)}>{t.author.nickname}</Link> : "törölt tag"} ·{" "}
<Link href={threadHref(t.thread, t.id)}>{t.thread.title}</Link>
{t.deleted && " · már eltávolítva"}
</span>
<PostBody text={t.body} />
</div>
)}
{t?.type === "message" && (
<div className="fmod-target">
<span className="hint">Privát üzenet, az előzményeivel (csak a jelentés miatt látod):</span>
<ol className="fmod-chat">
{t.messages.map((m) => (
<li key={m.id} className={m.reported ? "fmod-chat-reported" : undefined}>
<strong>{m.sender?.nickname ?? "Törölt tag"}:</strong> {m.body}
</li>
))}
</ol>
</div>
)}
{r.status === "open" ? (
<div className="fmsg-actions">
{t?.type === "post" && !t.deleted && (
<button
type="button"
className="btn btn-sm btn-danger"
disabled={busy === r.id}
onClick={() => removePost(r)}
>
Eltávolítás
</button>
)}
<button
type="button"
className="btn btn-sm"
disabled={busy === r.id}
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "resolve" } }))}
>
Kezeltem, lezárom
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
disabled={busy === r.id}
onClick={() => act(r, () => api(`/forum/mod/reports/${r.id}`, { body: { action: "dismiss" } }))}
>
Alaptalan
</button>
</div>
) : (
<p className="hint">
{STATUS[r.status]}
{r.handled_by && ` · ${r.handled_by}`}
</p>
)}
</article>
);
};
return (
<>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<section className="fh-section" aria-labelledby="fmod-open">
<h2 id="fmod-open" className="fmsg-h">
Nyitott jelentések ({open.length})
</h2>
{open.length === 0 ? <p className="fh-card fh-empty">Nincs nyitott jelentés.</p> : open.map(card)}
</section>
{handled.length > 0 && (
<section className="fh-section" aria-labelledby="fmod-done">
<h2 id="fmod-done" className="fmsg-h">
Az elmúlt 30 nap lezárt jelentései
</h2>
{handled.map(card)}
</section>
)}
</>
);
}
@@ -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<string, string> = {
delete_post: "hozzászólást távolított el",
@@ -17,48 +19,70 @@ const ACTIONS: Record<string, string> = {
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 (
<div className="fh">
<h1 className="fpage-title">Moderálási napló</h1>
{res.data.entries.length === 0 ? (
<p className="fh-card fh-empty">Még nem volt moderálás.</p>
) : (
<ul className="fh-card fh-flush fmodlog">
{res.data.entries.map((e) => (
<li key={e.id}>
<span className="hint">
{new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
{e.actor_kind === "ai" && " · AI"}
</span>
<span>
<strong>{e.actor ?? "?"}</strong> {ACTIONS[e.action] ?? e.action}
{e.target && (
<>
{" "}
(<Link href={memberHref(e.target)}>{e.target}</Link>)
</>
)}
{e.thread && (
<>
{": "}
<Link href={threadHref({ id: e.thread.id, slug: "" }, e.post_id ?? undefined)}>
{e.thread.title ?? `#${e.thread.id}`}
</Link>
</>
)}
{e.until && ` · ${banText(e.until)}`}
</span>
{e.reason && <span className="hint">Ok: {e.reason}</span>}
</li>
))}
</ul>
)}
<h1 className="fpage-title">Moderálás</h1>
<nav className="fmod-tabs" aria-label="Moderálás">
<Link href="/forum/moderalas" aria-current={log ? undefined : "page"}>
Jelentések
</Link>
<Link href="/forum/moderalas?nezet=naplo" aria-current={log ? "page" : undefined}>
Napló
</Link>
</nav>
{log ? <LogView /> : <ReportsView />}
</div>
);
}
async function ReportsView() {
const res = await forumGet<{ reports: ReportEntry[] }>("/v1/forum/mod/reports");
if (!res.ok) notFound();
return <ReportsList initial={res.data.reports} />;
}
async function LogView() {
const res = await forumGet<{ entries: ModLogEntry[] }>("/v1/forum/mod/log");
if (!res.ok) notFound();
if (res.data.entries.length === 0) return <p className="fh-card fh-empty">Még nem volt moderálás.</p>;
return (
<ul className="fh-card fh-flush fmodlog">
{res.data.entries.map((e) => (
<li key={e.id}>
<span className="hint">
{new Date(e.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
{e.actor_kind === "ai" && " · AI"}
</span>
<span>
<strong>{e.actor ?? "?"}</strong> {ACTIONS[e.action] ?? e.action}
{e.target && (
<>
{" "}
(<Link href={memberHref(e.target)}>{e.target}</Link>)
</>
)}
{e.thread && (
<>
{": "}
<Link href={threadHref({ id: e.thread.id, slug: "" }, e.post_id ?? undefined)}>
{e.thread.title ?? `#${e.thread.id}`}
</Link>
</>
)}
{e.until && ` · ${banText(e.until)}`}
</span>
{e.reason && <span className="hint">Ok: {e.reason}</span>}
</li>
))}
</ul>
);
}
+1 -1
View File
@@ -235,7 +235,7 @@ export default async function ForumHomePage() {
)}
{viewer.moderator && (
<Link href="/forum/moderalas" className="fh-side-link o-8">
Moderálási napló
Moderálás: jelentések és napló
</Link>
)}
</aside>
@@ -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<string | null>(null);
const id = relation.conversation_id;
if (relation.state === "accepted" && id) {
return (
<Link href={`/forum/uzenetek/${id}`} className="btn btn-sm">
Üzenetek
</Link>
);
}
if (relation.state === "incoming" && id) {
return (
<Link href={`/forum/uzenetek/${id}`} className="btn btn-sm btn-primary">
Beszélgetni szeretne veled: válaszolj
</Link>
);
}
if (relation.state === "outgoing") return <p className="hint">Beszélgetési kérésed elküldve, válaszra vár.</p>;
if (relation.state === "blocked_by_me")
return <p className="hint">Letiltottad. A tiltást az üzeneteidnél oldhatod fel.</p>;
if (!relation.eligible) {
return <p className="hint">Beszélgetést a Kereső rangtól kezdeményezhetsz, ha már írtál a fórumba.</p>;
}
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 (
<button type="button" className="btn btn-sm" onClick={() => setOpen(true)}>
Beszélgetést kezdeményezek
</button>
);
}
return (
<form className="freq" onSubmit={submit}>
<label htmlFor="freq-intro">Pár szó magadról és arról, miért írnál neki</label>
<textarea
id="freq-intro"
className="fc-text"
rows={3}
maxLength={INTRO_MAX}
value={intro}
onChange={(e) => setIntro(e.target.value)}
placeholder="Szia! Olvastam a hozzászólásodat a…"
/>
<span className="hint">
{intro.length}/{INTRO_MAX} · link nélkül. Ha elfogadja, beszélgethettek; ha nem, erről nem kapsz értesítést.
</span>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="fc-actions">
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)}>
Mégse
</button>
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || intro.trim().length < 3}>
{busy ? "Küldés…" : "Kérés küldése"}
</button>
</div>
</form>
);
}
@@ -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}`}
</p>
)}
{res.data.relation && <RequestPanel nickname={a.nickname} relation={res.data.relation} />}
{member.own && (
<Link href="/forum/beallitasok" className="btn btn-sm">
Profil szerkesztése
@@ -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<number | null>(null);
const [error, setError] = useState<string | null>(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 && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{incoming.length > 0 && (
<section className="fh-section" aria-labelledby="fmsg-in">
<h2 id="fmsg-in" className="fmsg-h">
Kérések
</h2>
{incoming.map((c) => (
<article key={c.id} className="fh-card fmsg-request">
<AuthorLine author={c.other} time={c.created_at} />
<p className="fmsg-intro">„{c.intro}”</p>
<div className="fmsg-actions">
<button
type="button"
className="btn btn-primary btn-sm"
disabled={busy === c.id}
onClick={() => answer(c, "accept")}
>
Elfogadom
</button>
<button
type="button"
className="btn btn-sm"
disabled={busy === c.id}
onClick={() => answer(c, "decline")}
>
Nem most
</button>
<button
type="button"
className="btn btn-ghost btn-sm"
disabled={busy === c.id}
onClick={() => window.confirm("Letiltod? Nem küldhet neked több kérést.") && answer(c, "block")}
>
Letiltom
</button>
</div>
</article>
))}
</section>
)}
<section className="fh-section" aria-labelledby="fmsg-open">
<h2 id="fmsg-open" className="fmsg-h">
Beszélgetések
</h2>
{open.length === 0 ? (
<p className="fh-card fh-empty">
Még nincs beszélgetésed. Egy tag profilján kezdeményezhetsz egyet, ha már elérted a Kereső rangot.
</p>
) : (
<ul className="fh-card fh-flush ft-list">
{open.map((c) => (
<li key={c.id}>
<Link href={`/forum/uzenetek/${c.id}`} className="ft-row fmsg-row">
<Avatar avatar={c.other?.avatar} size={40} online={c.other?.online} />
<span className="ft-main">
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
<span className="ft-excerpt">
{c.last_message
? `${c.last_message.mine ? "Te: " : ""}${c.last_message.excerpt}`
: "Még nincs üzenet."}
</span>
</span>
<span className="fmsg-when">
{c.last_message_at && (
<time suppressHydrationWarning dateTime={c.last_message_at}>
{ago(c.last_message_at)}
</time>
)}
{c.unread > 0 && <span className="ft-new">{c.unread} új</span>}
</span>
</Link>
</li>
))}
</ul>
)}
</section>
{sent.length > 0 && (
<section className="fh-section" aria-labelledby="fmsg-sent">
<h2 id="fmsg-sent" className="fmsg-h">
Elküldött kérések
</h2>
<ul className="fh-card fh-flush ft-list">
{sent.map((c) => (
<li key={c.id} className="ft-row fmsg-row">
<Avatar avatar={c.other?.avatar} size={32} />
<span className="ft-main">
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
<span className="ft-excerpt">„{c.intro}”</span>
</span>
<span className="hint">{c.state === "expired" ? "Lejárt" : "Válaszra vár"}</span>
</li>
))}
</ul>
</section>
)}
{blocked.length > 0 && (
<section className="fh-section" aria-labelledby="fmsg-blocked">
<h2 id="fmsg-blocked" className="fmsg-h">
Letiltottak
</h2>
<ul className="fh-card fh-flush ft-list">
{blocked.map((c) => (
<li key={c.id} className="ft-row fmsg-row">
<Avatar avatar={c.other?.avatar} size={32} />
<span className="ft-main">
<span className="ft-title">{c.other?.nickname ?? "Törölt tag"}</span>
</span>
<button
type="button"
className="btn btn-sm"
disabled={busy === c.id}
onClick={() => answer(c, "unblock")}
>
Tiltás feloldása
</button>
</li>
))}
</ul>
</section>
)}
</>
);
}
@@ -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<string | null>(null);
const bottom = useRef<HTMLDivElement>(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<ConversationPage>(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<unknown>) {
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<ChatMessage>(`${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 (
<div className="fchat">
<nav className="forum-crumbs" aria-label="Morzsamenü">
<Link href="/forum/uzenetek">Üzenetek</Link>
</nav>
<header className="fchat-head">
<Avatar avatar={c.other?.avatar} size={44} online={c.other?.online} />
<div className="fchat-who">
{c.other ? (
<Link href={memberHref(c.other.nickname)} className="fa-name">
{other}
</Link>
) : (
<span className="fa-name muted">{other}</span>
)}
{c.other && <span className="fa-rank">{c.other.rank_name}</span>}
</div>
{c.state === "accepted" && (
<details className="ftv-mod">
<summary className="btn btn-sm btn-ghost">Továbbiak</summary>
<div className="ftv-mod-menu">
<button
type="button"
className="danger"
onClick={() => window.confirm(`Letiltod ${other} tagot? Nem írhat neked többet.`) && answer("block")}
>
Letiltás
</button>
</div>
</details>
)}
</header>
<p className="fchat-intro">
<span className="hint">{c.requested_by_me ? "A kérésed" : `${other} kérése`}:</span> „{c.intro}”
</p>
{c.state === "incoming" && (
<div className="fh-card fmsg-request">
<p>{other} szeretne beszélgetni veled.</p>
<div className="fmsg-actions">
<button type="button" className="btn btn-primary btn-sm" disabled={busy} onClick={() => answer("accept")}>
Elfogadom
</button>
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => answer("decline")}>
Nem most
</button>
<button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={() => answer("block")}>
Letiltom
</button>
</div>
</div>
)}
{(c.state === "outgoing" || c.state === "expired") && (
<p className="fh-card fh-empty">
{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.`}
</p>
)}
{messages.length > 0 && (
<ol className="fchat-list">
{messages.map((m) => (
<li key={m.id} className={m.mine ? "fchat-msg fchat-mine" : "fchat-msg"}>
<div className="fchat-bubble">
<PostBody text={m.body} />
</div>
<span className="fchat-meta">
<time suppressHydrationWarning dateTime={m.created_at}>
{when(m.created_at)}
</time>
{!m.mine && <ReportButton path={`/forum/messages/${m.id}/report`} className="fchat-report" />}
</span>
</li>
))}
</ol>
)}
<div ref={bottom} />
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{c.state === "accepted" && (
<div className="fchat-compose">
<Composer id="uzenet" label="Üzeneted" placeholder="Írj üzenetet…" rows={2} busy={busy} onSubmit={send} />
<p className="hint">
Csak szöveg és emoji. A linkek nem kattinthatók. A moderátorok csak jelentett üzenetet látnak.
</p>
</div>
)}
{c.state === "blocked_by_me" && (
<div className="fh-card">
<p>Letiltottad. Nem írhat neked, és te sem neki.</p>
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => answer("unblock")}>
Tiltás feloldása
</button>
</div>
)}
</div>
);
}
@@ -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<ConversationPage>(`/v1/forum/conversations/${id}`);
if (!res.ok) {
if (res.status === 401) redirect(`/belepes?vissza=/forum/uzenetek/${id}`);
notFound();
}
return <Chat initial={res.data} />;
}
@@ -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 (
<div className="fh fmsg-page">
<h1 className="fpage-title">Üzenetek</h1>
<p className="muted">
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.
</p>
<Conversations initial={res.data.conversations} />
</div>
);
}
@@ -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 (
<svg viewBox="0 0 24 24" aria-hidden="true" className="fn-icon">
{name === "forum" && (
@@ -43,6 +43,12 @@ function Icon({ name }: { name: "forum" | "followed" | "new" | "profile" }) {
<path d="M12 8v8M8 12h8" />
</>
)}
{name === "messages" && (
<>
<rect x="3" y="5.5" width="18" height="13" rx="2" />
<path d="M3.5 7l8.5 6 8.5-6" />
</>
)}
{name === "profile" && (
<>
<circle cx="12" cy="8" r="4" />
@@ -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)}`
@@ -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 (
<p className="frep-crisis" role="note">
Ha azonnali veszélyt látsz, hívd a <strong>112</strong>-t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal
hívható száma: <strong>116-123</strong>.
</p>
);
}
/**
* "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<ReportKind | "">("");
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 (
<div className="frep" role="status">
<p>Köszönjük, a moderátorok megnézik.</p>
{done.crisis && <CrisisHelp />}
</div>
);
}
if (!open) {
return (
<button type="button" className={className} onClick={() => setOpen(true)}>
Jelentés
</button>
);
}
return (
<form className="frep" onSubmit={submit}>
<fieldset className="fnew-set">
<legend>Mi a gond?</legend>
{REPORT_KINDS.map((k) => (
<label key={k.kind} className="frep-kind">
<input type="radio" name="report-kind" checked={kind === k.kind} onChange={() => setKind(k.kind)} />
<span>{k.label}</span>
</label>
))}
</fieldset>
{kind === "crisis" && <CrisisHelp />}
<label className="sr-only" htmlFor={`${path}-note`}>
Megjegyzés
</label>
<textarea
id={`${path}-note`}
className="fc-text"
rows={2}
maxLength={500}
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder={kind === "other" ? "Írd le röviden, mi a gond." : "Megjegyzés (nem kötelező)"}
/>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="fc-actions">
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)}>
Mégse
</button>
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !kind}>
{busy ? "Küldés…" : "Jelentés küldése"}
</button>
</div>
</form>
);
}
@@ -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
</button>
)}
{viewer.logged_in && !post.own && <ReportButton path={`/forum/posts/${post.id}/report`} />}
{viewer.moderator && !post.own && (
<button type="button" className="fp-tool fp-tool-mod" onClick={() => actions.remove(post)}>
Eltávolítás
+89
View File
@@ -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;
}
+3 -2
View File
@@ -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"),
}
+105 -2
View File
@@ -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<usize, sqlx::E
Ok(sent)
}
pub async fn run(db: PgPool, telegram: Telegram, interval: Duration, stop: watch::Receiver<bool>) {
/// 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<usize, sqlx::Error> {
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<String>,
interval: Duration,
stop: watch::Receiver<bool>,
) {
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!(
+4 -1
View File
@@ -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<kerdes>\nMi az erősségem?\n</kerdes>\nVálasz: A kitartásod."), "earlier answers");
assert!(
user.contains("Kérdés:\n<kerdes>\nMi az erősségem?\n</kerdes>\nVálasz: A kitartásod."),
"earlier answers"
);
assert!(user.contains("<kerdes>\nÉs a munkában?\n</kerdes>") && user.contains("legfeljebb 250 szóban"));
for secret in ["1990", "14:30", "Szeged"] {
assert!(!user.contains(secret), "{secret} leaked");