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:
@@ -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>> {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(¬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<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(¬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<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
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user