Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the forum schema (migration 0038, which also adds the moderator role): nicknames, profiles with shared signs, topics, threads with listening or advice intent, two-level replies, read marks and followed threads, reactions as ratings with points and ranks, newcomer limits (lifted by a purchase), moderation with reasons, bans and a log. Integration tests run in CI. The frontend's /forum pages (light by default, dark on request, phone first with a desktop layout) are switched on by FORUM_URL; the /api/v1 proxy sends /api/v1/forum/* to the forum service. Concept and status: docs/kozosseg.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
//! The forum's front page, the topics, a topic's threads, followed threads.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{CardRow, St, card_params, card_sql, cards_json, may_read, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// Threads on one page of a topic.
|
||||
const PAGE_SIZE: i64 = 30;
|
||||
/// "Pörgős most": at least this many replies in the last 24 hours.
|
||||
const HOT_MIN_REPLIES: i64 = 3;
|
||||
/// "Várják a válaszod": threads without a reply from the last two weeks.
|
||||
const UNANSWERED_DAYS: i32 = 14;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct TopicRow {
|
||||
id: i16,
|
||||
slug: String,
|
||||
name: String,
|
||||
description: String,
|
||||
visibility: String,
|
||||
listening: bool,
|
||||
thread_count: i64,
|
||||
new_count: Option<i64>,
|
||||
last_author: Option<Uuid>,
|
||||
last_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// The topics in order: counts and the latest post for those the viewer may
|
||||
/// read, the others (a members-only topic for a visitor) only by name.
|
||||
async fn topic_list(state: &St, viewer: &Viewer) -> ApiResult<Vec<Value>> {
|
||||
let (me, since) = card_params(viewer);
|
||||
let rows: Vec<TopicRow> = sqlx::query_as(
|
||||
"SELECT tp.id, tp.slug, tp.name, tp.description, tp.visibility, tp.listening, \
|
||||
(SELECT count(*) FROM forum.threads th WHERE th.topic_id = tp.id AND th.deleted_at IS NULL) AS thread_count, \
|
||||
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||
(SELECT count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
|
||||
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||
AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2::timestamptz \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS new_count, \
|
||||
last.author_id AS last_author, last.created_at AS last_at \
|
||||
FROM forum.topics tp \
|
||||
LEFT JOIN LATERAL (SELECT p.author_id, p.created_at FROM forum.posts p \
|
||||
JOIN forum.threads th ON th.id = p.thread_id \
|
||||
WHERE th.topic_id = tp.id AND th.deleted_at IS NULL AND p.deleted_at IS NULL \
|
||||
ORDER BY p.id DESC LIMIT 1) last ON true \
|
||||
ORDER BY tp.position",
|
||||
)
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let readable: Vec<bool> = rows.iter().map(|r| may_read(viewer, &r.visibility)).collect();
|
||||
let people =
|
||||
super::authors(&state.db, rows.iter().zip(&readable).filter(|(_, ok)| **ok).filter_map(|(r, _)| r.last_author))
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.zip(readable)
|
||||
.filter(|(r, _)| r.visibility != "restricted" || viewer.is_moderator())
|
||||
.map(|(r, readable)| {
|
||||
let mut topic = json!({
|
||||
"id": r.id,
|
||||
"slug": r.slug,
|
||||
"name": r.name,
|
||||
"description": r.description,
|
||||
"visibility": r.visibility,
|
||||
"listening": r.listening,
|
||||
"readable": readable,
|
||||
});
|
||||
if readable {
|
||||
topic["thread_count"] = json!(r.thread_count);
|
||||
topic["new_count"] = json!(r.new_count);
|
||||
topic["last"] = json!(r.last_at.map(|at| json!({
|
||||
"author": r.last_author.and_then(|id| people.get(&id).cloned()),
|
||||
"at": rfc3339(at),
|
||||
})));
|
||||
}
|
||||
topic
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What the header and the front page show about the viewer.
|
||||
pub fn viewer_json(viewer: &Viewer) -> Value {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
json!({
|
||||
"logged_in": viewer.logged_in(),
|
||||
"needs_nickname": viewer.logged_in() && viewer.member.is_none(),
|
||||
"moderator": viewer.is_moderator(),
|
||||
"member": viewer.member.as_ref().map(|m| {
|
||||
let rank = m.rank(now);
|
||||
json!({
|
||||
"nickname": m.nickname,
|
||||
"avatar": m.avatar,
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"banned": m.banned(now),
|
||||
})
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// The front page: the viewer, new replies in followed threads, the topics,
|
||||
/// threads waiting for a first reply, and the busiest threads of the day.
|
||||
pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let (me, since) = card_params(&viewer);
|
||||
let topics = topic_list(&state, &viewer).await?;
|
||||
|
||||
let followed = followed_counts(&state, &viewer).await?;
|
||||
|
||||
let unanswered: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.reply_count = 0 AND NOT th.locked AND th.author_id IS DISTINCT FROM $1 \
|
||||
AND th.created_at > now() - make_interval(days => $3) \
|
||||
ORDER BY th.created_at LIMIT 3",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(UNANSWERED_DAYS)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
let hot: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
|
||||
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
|
||||
GROUP BY thread_id HAVING count(*) >= $3) \
|
||||
{} AND th.id IN (SELECT thread_id FROM recent) \
|
||||
ORDER BY (SELECT n FROM recent WHERE recent.thread_id = th.id) DESC, th.last_post_at DESC LIMIT 5",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(HOT_MIN_REPLIES)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"followed": followed,
|
||||
"topics": topics,
|
||||
"unanswered": cards_json(&state.db, unanswered).await?,
|
||||
"hot": cards_json(&state.db, hot).await?,
|
||||
})))
|
||||
}
|
||||
|
||||
/// New replies (by others, unread) in the member's followed threads.
|
||||
async fn followed_counts(state: &St, viewer: &Viewer) -> ApiResult<Option<Value>> {
|
||||
let (Some(me), Some(since)) = card_params(viewer) else { return Ok(None) };
|
||||
let (replies, threads): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*), count(DISTINCT p.thread_id) FROM forum.follows f \
|
||||
JOIN forum.threads th ON th.id = f.thread_id AND th.deleted_at IS NULL \
|
||||
JOIN forum.posts p ON p.thread_id = f.thread_id AND p.deleted_at IS NULL \
|
||||
WHERE f.user_id = $1 AND p.author_id IS DISTINCT FROM $1 AND p.created_at > $2 \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = f.thread_id), 0)",
|
||||
)
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Some(json!({ "new_replies": replies, "threads": threads })))
|
||||
}
|
||||
|
||||
/// 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? })))
|
||||
}
|
||||
|
||||
pub async fn topics(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "topics": topic_list(&state, &viewer).await? })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PageQuery {
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
/// A topic's threads: pinned ones first, then by the latest post.
|
||||
pub async fn topic(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(slug), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let topic: Option<(i16, String, String, String, bool)> =
|
||||
sqlx::query_as("SELECT id, name, description, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||
.bind(&slug)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (id, name, description, visibility, listening) = topic.ok_or(ApiError::NotFound("topic"))?;
|
||||
if !may_read(&viewer, &visibility) {
|
||||
// A members-only topic asks for a login; a restricted one stays hidden.
|
||||
return Err(if visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("topic") });
|
||||
}
|
||||
let page = q.page.unwrap_or(1).clamp(1, 10_000);
|
||||
let (me, since) = card_params(&viewer);
|
||||
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.topic_id = $3 ORDER BY th.pinned DESC, th.last_post_at DESC LIMIT $4 OFFSET $5",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.bind(id)
|
||||
.bind(PAGE_SIZE + 1)
|
||||
.bind((page - 1) * PAGE_SIZE)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let has_more = rows.len() as i64 > PAGE_SIZE;
|
||||
let rows = rows.into_iter().take(PAGE_SIZE as usize).collect();
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"topic": {
|
||||
"slug": slug, "name": name, "description": description,
|
||||
"visibility": visibility, "listening": listening,
|
||||
},
|
||||
"threads": cards_json(&state.db, rows).await?,
|
||||
"page": page,
|
||||
"has_more": has_more,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The threads the member follows, the latest activity first, with what is unread.
|
||||
pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
viewer.require_member()?;
|
||||
let (me, since) = card_params(&viewer);
|
||||
let rows: Vec<CardRow> = sqlx::query_as(&format!(
|
||||
"{} AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1) \
|
||||
ORDER BY th.last_post_at DESC LIMIT 50",
|
||||
card_sql(&viewer)
|
||||
))
|
||||
.bind(me)
|
||||
.bind(since)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "viewer": viewer_json(&viewer), "threads": cards_json(&state.db, rows).await? })))
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Members: one's own forum profile (nickname first), the nickname check
|
||||
//! while typing, the online heartbeat, and a member's public profile.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::home::viewer_json;
|
||||
use super::{Body, St, authors, online, rfc3339, shared_signs, visible_topics};
|
||||
use crate::auth::{self, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
/// A nickname may change once in this many days (spelling fixes that keep the
|
||||
/// same folded form any time).
|
||||
const NICKNAME_CHANGE_DAYS: i64 = 30;
|
||||
/// A nickname given up stays reserved this long.
|
||||
const NICKNAME_RESERVED_DAYS: i64 = 90;
|
||||
|
||||
/// The viewer's own forum profile, and what each chart sharing level would show.
|
||||
pub async fn me(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let member = viewer.member.as_ref().map(|m| {
|
||||
let rank = m.rank(now);
|
||||
let change_after = m.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||
json!({
|
||||
"nickname": m.nickname,
|
||||
"avatar": m.avatar,
|
||||
"bio": m.bio,
|
||||
"chart_share": m.chart_share,
|
||||
"invisible": m.invisible,
|
||||
"points": m.points,
|
||||
"post_count": m.post_count,
|
||||
"created_at": rfc3339(m.created_at),
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"next_rank": rank.next().map(|(r, points, days)| json!({
|
||||
"rank": r, "name": r.name(), "points": points, "days": days,
|
||||
})),
|
||||
"nickname_change_after": (change_after > now).then(|| rfc3339(change_after)),
|
||||
"banned_until": m.banned_until.filter(|u| *u > now).map(|u| {
|
||||
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||
}),
|
||||
"ban_reason": m.ban_reason.as_ref().filter(|_| m.banned(now)),
|
||||
})
|
||||
});
|
||||
let signs = shared_signs(&state.db, &[user.id]).await?.remove(&user.id);
|
||||
let chart = signs.map(|s| json!({ "sun": s.share("sun"), "big3": s.share("big3"), "planets": s.share("planets") }));
|
||||
Ok(Json(json!({ "viewer": viewer_json(&viewer), "member": member, "chart": chart })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SaveMe {
|
||||
nickname: String,
|
||||
#[serde(default)]
|
||||
avatar: Option<String>,
|
||||
#[serde(default)]
|
||||
bio: Option<String>,
|
||||
#[serde(default)]
|
||||
chart_share: Option<String>,
|
||||
#[serde(default)]
|
||||
invisible: Option<bool>,
|
||||
}
|
||||
|
||||
/// Whether someone else has (or recently had) this folded nickname.
|
||||
async fn nickname_taken(db: &sqlx::PgPool, key: &str, me: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM forum.members WHERE nickname_key = $1 AND user_id <> $2) \
|
||||
OR EXISTS (SELECT 1 FROM forum.retired_nicknames \
|
||||
WHERE nickname_key = $1 AND user_id <> $2 AND until > now())",
|
||||
)
|
||||
.bind(key)
|
||||
.bind(me)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
|
||||
fn taken() -> ApiError {
|
||||
ApiError::conflict("nickname_taken", "Ezt az álnevet már más használja. Válassz másikat.")
|
||||
}
|
||||
|
||||
/// Creates the forum profile (choosing a nickname is the first step) or changes it.
|
||||
pub async fn save_me(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<SaveMe>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let nickname = text::nickname(&req.nickname)?;
|
||||
let key = text::nickname_key(&nickname);
|
||||
let avatar = req.avatar.as_deref().map(text::avatar).transpose()?;
|
||||
let bio = req.bio.as_deref().map(text::bio).transpose()?;
|
||||
let chart_share = match req.chart_share.as_deref() {
|
||||
None => None,
|
||||
Some(level @ ("none" | "sun" | "big3" | "planets")) => Some(level.to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen megosztási szint.")),
|
||||
};
|
||||
if nickname_taken(&state.db, &key, user.id).await? {
|
||||
return Err(taken());
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut tx = state.db.begin().await?;
|
||||
let result = match &viewer.member {
|
||||
None => {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, bio, chart_share, invisible) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(&nickname)
|
||||
.bind(&key)
|
||||
.bind(avatar.unwrap_or_else(|| text::default_avatar(&key)))
|
||||
.bind(bio.unwrap_or_default())
|
||||
.bind(chart_share.unwrap_or_else(|| "none".into()))
|
||||
.bind(req.invisible.unwrap_or(false))
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
}
|
||||
Some(member) => {
|
||||
let old_key = text::nickname_key(&member.nickname);
|
||||
let renamed = old_key != key;
|
||||
if renamed {
|
||||
let allowed = member.nickname_changed_at + time::Duration::days(NICKNAME_CHANGE_DAYS);
|
||||
if allowed > now {
|
||||
return Err(ApiError::conflict(
|
||||
"nickname_too_soon",
|
||||
format!("Az álneved {NICKNAME_CHANGE_DAYS} naponta egyszer változtathatod meg."),
|
||||
));
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.retired_nicknames (nickname_key, user_id, until) \
|
||||
VALUES ($1, $2, now() + make_interval(days => $3)) \
|
||||
ON CONFLICT (nickname_key) DO UPDATE SET user_id = EXCLUDED.user_id, until = EXCLUDED.until",
|
||||
)
|
||||
.bind(&old_key)
|
||||
.bind(user.id)
|
||||
.bind(NICKNAME_RESERVED_DAYS as i32)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Taking back one's own earlier name.
|
||||
sqlx::query("DELETE FROM forum.retired_nicknames WHERE nickname_key = $1 AND user_id = $2")
|
||||
.bind(&key)
|
||||
.bind(user.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET nickname = $2, nickname_key = $3, \
|
||||
avatar = COALESCE($4, avatar), bio = COALESCE($5, bio), \
|
||||
chart_share = COALESCE($6, chart_share), invisible = COALESCE($7, invisible), \
|
||||
nickname_changed_at = CASE WHEN $8 THEN now() ELSE nickname_changed_at END \
|
||||
WHERE user_id = $1",
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(&nickname)
|
||||
.bind(&key)
|
||||
.bind(avatar)
|
||||
.bind(bio)
|
||||
.bind(chart_share)
|
||||
.bind(req.invisible)
|
||||
.bind(renamed)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(_) => {}
|
||||
// Someone took it in the same moment.
|
||||
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => return Err(taken()),
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
tx.commit().await?;
|
||||
let viewer = Viewer { member: auth::load_member(&state.db, user.id).await?, ..viewer };
|
||||
me(State(state), viewer).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NameQuery {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// While typing: is this nickname valid and free?
|
||||
pub async fn nickname_check(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<NameQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = viewer.require_user()?;
|
||||
let nickname = match text::nickname(&q.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return Ok(Json(json!({ "ok": false, "message": e.to_string() }))),
|
||||
};
|
||||
if nickname_taken(&state.db, &text::nickname_key(&nickname), user.id).await? {
|
||||
return Ok(Json(json!({ "ok": false, "message": taken().to_string() })));
|
||||
}
|
||||
Ok(Json(json!({ "ok": true, "nickname": nickname })))
|
||||
}
|
||||
|
||||
/// The page is open: keeps the online dot (the viewer extractor does the work).
|
||||
pub async fn presence(_viewer: Viewer) -> StatusCode {
|
||||
StatusCode::NO_CONTENT
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ProfileRow {
|
||||
user_id: Uuid,
|
||||
bio: String,
|
||||
created_at: OffsetDateTime,
|
||||
post_count: i32,
|
||||
invisible: bool,
|
||||
last_seen_at: Option<OffsetDateTime>,
|
||||
banned_until: Option<OffsetDateTime>,
|
||||
ban_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RecentRow {
|
||||
id: i64,
|
||||
thread_id: i64,
|
||||
title: String,
|
||||
topic_slug: String,
|
||||
topic_name: String,
|
||||
created_at: OffsetDateTime,
|
||||
excerpt: String,
|
||||
is_opening: bool,
|
||||
}
|
||||
|
||||
/// A member's public profile: nickname, avatar, rank, shared signs, bio,
|
||||
/// activity (coarsely), and recent posts from the topics the viewer may read.
|
||||
pub async fn profile(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row: ProfileRow = sqlx::query_as(
|
||||
"SELECT user_id, bio, created_at, post_count, invisible, last_seen_at, banned_until, ban_reason \
|
||||
FROM forum.members WHERE nickname_key = $1",
|
||||
)
|
||||
.bind(text::nickname_key(&nickname))
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("member"))?;
|
||||
let brief = authors(&state.db, [row.user_id]).await?.remove(&row.user_id).ok_or(ApiError::NotFound("member"))?;
|
||||
let recent: Vec<RecentRow> = sqlx::query_as(&format!(
|
||||
"SELECT p.id, p.thread_id, th.title, tp.slug AS topic_slug, tp.name AS topic_name, p.created_at, \
|
||||
left(p.body, 200) AS excerpt, p.is_opening \
|
||||
FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE p.author_id = $1 AND p.deleted_at IS NULL AND th.deleted_at IS NULL AND ({}) \
|
||||
ORDER BY p.id DESC LIMIT 10",
|
||||
visible_topics(&viewer)
|
||||
))
|
||||
.bind(row.user_id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let thread_count: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM forum.threads WHERE author_id = $1 AND deleted_at IS NULL")
|
||||
.bind(row.user_id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let own = viewer.user_id() == Some(row.user_id);
|
||||
let last_seen = if row.invisible && !own {
|
||||
None
|
||||
} else if online(false, row.last_seen_at, now) {
|
||||
Some("online")
|
||||
} else {
|
||||
row.last_seen_at.map(|t| match now - t {
|
||||
d if d < time::Duration::days(1) => "day",
|
||||
d if d < time::Duration::days(7) => "week",
|
||||
_ => "earlier",
|
||||
})
|
||||
};
|
||||
let banned = row.banned_until.filter(|u| *u > now);
|
||||
let show_ban = own || viewer.is_moderator();
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"member": {
|
||||
"author": brief,
|
||||
"bio": row.bio,
|
||||
"created_at": rfc3339(row.created_at),
|
||||
"post_count": row.post_count,
|
||||
"thread_count": thread_count,
|
||||
"last_seen": last_seen,
|
||||
"own": own,
|
||||
"banned_until": banned.filter(|_| show_ban).map(|u| {
|
||||
if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }
|
||||
}),
|
||||
"ban_reason": row.ban_reason.filter(|_| show_ban && banned.is_some()),
|
||||
},
|
||||
"recent": recent.into_iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"thread_id": r.thread_id,
|
||||
"thread_slug": text::slug(&r.title),
|
||||
"thread_title": r.title,
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"excerpt": r.excerpt,
|
||||
"is_opening": r.is_opening,
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! HTTP routes, all under `/v1/forum`.
|
||||
//!
|
||||
//! Reading is open (members-only topics need a login); writing needs a
|
||||
//! nickname ([`Viewer::require_writer`]); moderation the moderator or admin
|
||||
//! role. A thread in a topic the viewer may not read answers 404, so its
|
||||
//! existence is not revealed.
|
||||
|
||||
mod home;
|
||||
mod members;
|
||||
mod moderation;
|
||||
mod posts;
|
||||
mod threads;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::routing::{get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::auth::{ONLINE_MINUTES, Viewer};
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub type Body<T> = WithRejection<Json<T>, ApiError>;
|
||||
pub type IdPath = WithRejection<Path<i64>, ApiError>;
|
||||
pub type St = State<Arc<AppState>>;
|
||||
|
||||
pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
.route("/v1/forum/home", get(home::home))
|
||||
.route("/v1/forum/nav", get(home::nav))
|
||||
.route("/v1/forum/topics", get(home::topics))
|
||||
.route("/v1/forum/topics/{slug}", get(home::topic))
|
||||
.route("/v1/forum/followed", get(home::followed))
|
||||
.route("/v1/forum/threads", post(threads::create))
|
||||
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
|
||||
.route("/v1/forum/threads/{id}/restore", post(threads::restore))
|
||||
.route("/v1/forum/threads/{id}/posts", post(threads::reply))
|
||||
.route("/v1/forum/threads/{id}/read", post(threads::mark_read))
|
||||
.route("/v1/forum/threads/{id}/follow", put(threads::follow).delete(threads::unfollow))
|
||||
.route("/v1/forum/posts/{id}", axum::routing::patch(posts::edit).delete(posts::remove))
|
||||
.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/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))
|
||||
// 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)
|
||||
}
|
||||
|
||||
async fn health(State(state): St) -> Result<Json<Value>, ApiError> {
|
||||
sqlx::query("SELECT 1").execute(&state.db).await?;
|
||||
Ok(Json(json!({ "status": "ok" })))
|
||||
}
|
||||
|
||||
/// The topics the viewer may read, as an SQL condition on `tp` (forum.topics).
|
||||
/// Built from the viewer's flags only, never from input.
|
||||
pub fn visible_topics(viewer: &Viewer) -> &'static str {
|
||||
if viewer.is_moderator() {
|
||||
"TRUE"
|
||||
} else if viewer.logged_in() {
|
||||
"tp.visibility IN ('public', 'members')"
|
||||
} else {
|
||||
"tp.visibility = 'public'"
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the viewer may read a topic of this visibility.
|
||||
pub fn may_read(viewer: &Viewer, visibility: &str) -> bool {
|
||||
match visibility {
|
||||
"public" => true,
|
||||
"members" => viewer.logged_in(),
|
||||
_ => viewer.is_moderator(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread in a list: what the cards on the forum pages show.
|
||||
#[derive(sqlx::FromRow)]
|
||||
pub struct CardRow {
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub last_post_at: OffsetDateTime,
|
||||
pub reply_count: i32,
|
||||
pub pinned: bool,
|
||||
pub locked: bool,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub participants: i64,
|
||||
/// Posts by others the member has not read; `None` for visitors.
|
||||
pub unread: Option<i64>,
|
||||
}
|
||||
|
||||
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
|
||||
/// the member's user id and `$2` when they joined (both NULL for a visitor),
|
||||
/// so the caller's own parameters start at `$3`. Append `AND …`, `ORDER BY`, `LIMIT`.
|
||||
pub fn card_sql(viewer: &Viewer) -> String {
|
||||
format!(
|
||||
"SELECT th.id, th.title, th.intent, th.author_id, th.created_at, th.last_post_at, th.reply_count, \
|
||||
th.pinned, th.locked, tp.slug AS topic_slug, tp.name AS topic_name, \
|
||||
(SELECT count(DISTINCT p.author_id) FROM forum.posts p \
|
||||
WHERE p.thread_id = th.id AND p.deleted_at IS NULL) AS participants, \
|
||||
CASE WHEN $1::uuid IS NULL THEN NULL ELSE \
|
||||
(SELECT count(*) FROM forum.posts p \
|
||||
WHERE p.thread_id = th.id AND p.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
|
||||
AND p.created_at > $2::timestamptz \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE th.deleted_at IS NULL AND ({})",
|
||||
visible_topics(viewer)
|
||||
)
|
||||
}
|
||||
|
||||
/// `$1` and `$2` of [`card_sql`].
|
||||
pub fn card_params(viewer: &Viewer) -> (Option<Uuid>, Option<OffsetDateTime>) {
|
||||
match &viewer.member {
|
||||
Some(m) => (Some(m.user_id), Some(m.created_at)),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, sqlx::Error> {
|
||||
let people = authors(db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"id": r.id,
|
||||
"slug": crate::text::slug(&r.title),
|
||||
"title": r.title,
|
||||
"intent": r.intent,
|
||||
"topic": { "slug": r.topic_slug, "name": r.topic_name },
|
||||
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"last_post_at": rfc3339(r.last_post_at),
|
||||
"reply_count": r.reply_count,
|
||||
"participants": r.participants,
|
||||
"pinned": r.pinned,
|
||||
"locked": r.locked,
|
||||
"unread": r.unread,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct AuthorRow {
|
||||
user_id: Uuid,
|
||||
nickname: String,
|
||||
avatar: String,
|
||||
points: i32,
|
||||
created_at: OffsetDateTime,
|
||||
invisible: bool,
|
||||
last_seen_at: Option<OffsetDateTime>,
|
||||
chart_share: String,
|
||||
roles: Vec<String>,
|
||||
}
|
||||
|
||||
/// How members appear next to what they wrote: nickname, avatar, rank,
|
||||
/// moderator badge, online dot, and the signs they chose to share.
|
||||
pub async fn authors(db: &PgPool, ids: impl IntoIterator<Item = Uuid>) -> Result<HashMap<Uuid, Value>, sqlx::Error> {
|
||||
let mut ids: Vec<Uuid> = ids.into_iter().collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
let rows: Vec<AuthorRow> = sqlx::query_as(
|
||||
"SELECT m.user_id, m.nickname, m.avatar, m.points, m.created_at, m.invisible, m.last_seen_at, \
|
||||
m.chart_share, u.roles \
|
||||
FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.user_id = ANY($1)",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let sharing: Vec<Uuid> = rows.iter().filter(|r| r.chart_share != "none").map(|r| r.user_id).collect();
|
||||
let signs = shared_signs(db, &sharing).await?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let rank = Rank::of(r.points, r.created_at, now);
|
||||
let moderator = r.roles.iter().any(|role| role == "moderator" || role == "admin");
|
||||
let shown = signs.get(&r.user_id).map(|chart| chart.share(&r.chart_share));
|
||||
let value = json!({
|
||||
"nickname": r.nickname,
|
||||
"avatar": r.avatar,
|
||||
"rank": rank,
|
||||
"rank_name": rank.name(),
|
||||
"moderator": moderator,
|
||||
"online": online(r.invisible, r.last_seen_at, now),
|
||||
"signs": shown,
|
||||
});
|
||||
(r.user_id, value)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn online(invisible: bool, last_seen_at: Option<OffsetDateTime>, now: OffsetDateTime) -> bool {
|
||||
!invisible && last_seen_at.is_some_and(|t| now - t < time::Duration::minutes(ONLINE_MINUTES))
|
||||
}
|
||||
|
||||
/// The signs of a member's own chart (never degrees: they would give away the
|
||||
/// birth date and time).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ChartSigns {
|
||||
/// Planet id → sign id, in the chart's order.
|
||||
pub planets: Vec<(String, String)>,
|
||||
/// Only when the birth time is known.
|
||||
pub ascendant: Option<String>,
|
||||
}
|
||||
|
||||
const PLANETS: [&str; 10] =
|
||||
["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
|
||||
impl ChartSigns {
|
||||
fn sign(&self, id: &str) -> Option<&str> {
|
||||
self.planets.iter().find(|(p, _)| p == id).map(|(_, s)| s.as_str())
|
||||
}
|
||||
|
||||
/// What a sharing level shows; `None` for "none".
|
||||
pub fn share(&self, level: &str) -> Option<Value> {
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut put = |key: &str, sign: Option<&str>| {
|
||||
if let Some(sign) = sign {
|
||||
out.insert(key.to_string(), json!(sign));
|
||||
}
|
||||
};
|
||||
match level {
|
||||
"sun" => put("sun", self.sign("sun")),
|
||||
"big3" => {
|
||||
put("sun", self.sign("sun"));
|
||||
put("moon", self.sign("moon"));
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
"planets" => {
|
||||
for planet in PLANETS {
|
||||
put(planet, self.sign(planet));
|
||||
}
|
||||
put("ascendant", self.ascendant.as_deref());
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
if out.is_empty() { None } else { Some(Value::Object(out)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The signs of each user's own chart (the current one first).
|
||||
pub async fn shared_signs(db: &PgPool, users: &[Uuid]) -> Result<HashMap<Uuid, ChartSigns>, sqlx::Error> {
|
||||
if users.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
type Row = (Uuid, Option<Value>, Option<String>, Option<bool>);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT DISTINCT ON (owner_id) owner_id, result->'points', result->'angles'->'ascendant'->>'sign', \
|
||||
(result->'time'->>'time_known')::boolean \
|
||||
FROM charts WHERE owner_id = ANY($1) AND kind = 'own' ORDER BY owner_id, is_primary DESC, created_at",
|
||||
)
|
||||
.bind(users)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(owner, points, ascendant, time_known)| {
|
||||
let planets = points
|
||||
.as_ref()
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| Some((p["id"].as_str()?.to_string(), p["sign"].as_str()?.to_string())))
|
||||
.filter(|(id, _)| PLANETS.contains(&id.as_str()))
|
||||
.collect();
|
||||
let ascendant = ascendant.filter(|_| time_known.unwrap_or(false));
|
||||
(owner, ChartSigns { planets, ascendant })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: OffsetDateTime) -> String {
|
||||
t.format(&time::format_description::well_known::Rfc3339).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the user bought a package (lifts the newcomer limits).
|
||||
pub async fn has_purchase(db: &PgPool, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')")
|
||||
.bind(user)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Moderation: bans and the log of every moderation step (who, what, why;
|
||||
//! a person or, later, the AI). Removing posts and threads is in their modules.
|
||||
|
||||
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 time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St, rfc3339};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::text;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Action {
|
||||
DeletePost,
|
||||
RestorePost,
|
||||
DeleteThread,
|
||||
RestoreThread,
|
||||
Ban,
|
||||
Unban,
|
||||
Lock,
|
||||
Unlock,
|
||||
Pin,
|
||||
Unpin,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Action::DeletePost => "delete_post",
|
||||
Action::RestorePost => "restore_post",
|
||||
Action::DeleteThread => "delete_thread",
|
||||
Action::RestoreThread => "restore_thread",
|
||||
Action::Ban => "ban",
|
||||
Action::Unban => "unban",
|
||||
Action::Lock => "lock",
|
||||
Action::Unlock => "unlock",
|
||||
Action::Pin => "pin",
|
||||
Action::Unpin => "unpin",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one line of the moderation log (a person's step).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn record(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
actor: Uuid,
|
||||
action: Action,
|
||||
target_user: Option<Uuid>,
|
||||
thread_id: Option<i64>,
|
||||
post_id: Option<i64>,
|
||||
reason: Option<&str>,
|
||||
until: Option<OffsetDateTime>,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
|
||||
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(actor)
|
||||
.bind(action.as_str())
|
||||
.bind(target_user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.bind(reason)
|
||||
.bind(until)
|
||||
.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");
|
||||
time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc()
|
||||
}
|
||||
|
||||
/// The longest temporary ban, in hours (a year); longer is a ban for good.
|
||||
const MAX_BAN_HOURS: i64 = 24 * 365;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct BanRequest {
|
||||
/// Hours; missing or `null`: for good.
|
||||
#[serde(default)]
|
||||
hours: Option<i64>,
|
||||
#[serde(default)]
|
||||
reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The member behind a nickname, and whether they are a moderator or admin.
|
||||
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
|
||||
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
|
||||
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
|
||||
)
|
||||
.bind(text::nickname_key(nickname))
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
|
||||
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
|
||||
}
|
||||
|
||||
/// A moderator bans a member for some hours or for good: they may still
|
||||
/// read, not write. Moderators and admins cannot be banned this way.
|
||||
pub async fn ban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<BanRequest>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, protected) = target(&state.db, &nickname).await?;
|
||||
if protected {
|
||||
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let until = match req.hours {
|
||||
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
|
||||
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
|
||||
None => forever(),
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.bind(until)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
|
||||
Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } })))
|
||||
}
|
||||
|
||||
pub async fn unban(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let (user, _) = target(&state.db, &nickname).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
|
||||
.bind(user)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct LogRow {
|
||||
id: i64,
|
||||
actor: Option<String>,
|
||||
actor_kind: String,
|
||||
action: String,
|
||||
target: Option<String>,
|
||||
thread_id: Option<i64>,
|
||||
thread_title: Option<String>,
|
||||
post_id: Option<i64>,
|
||||
reason: Option<String>,
|
||||
until: Option<OffsetDateTime>,
|
||||
created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// The latest moderation steps, for moderators.
|
||||
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 \
|
||||
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 \
|
||||
LEFT JOIN forum.members tm ON tm.user_id = l.target_user \
|
||||
LEFT JOIN forum.threads th ON th.id = l.thread_id \
|
||||
ORDER BY l.id DESC LIMIT 200",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"entries": rows.into_iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"actor": r.actor,
|
||||
"actor_kind": r.actor_kind,
|
||||
"action": r.action,
|
||||
"target": r.target,
|
||||
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
|
||||
"post_id": r.post_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),
|
||||
})).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! A post: editing one's own, removal (one's own, or a moderator's with a
|
||||
//! reason), the admin's restore, reactions and the "Ez segített" mark.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::moderation::{self, Action};
|
||||
use super::threads::{POST_COLUMNS, PostRow, REACTIONS, Reason, ThreadRow, open_thread, posts_json, readable_thread};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::HELPED_POINTS;
|
||||
use crate::text;
|
||||
|
||||
/// A post and its thread, both readable by the viewer.
|
||||
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("post"))?;
|
||||
let thread = readable_thread(db, viewer, post.thread_id).await?;
|
||||
Ok((post, thread))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Edit {
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// The author changes their post (while the thread is open).
|
||||
pub async fn edit(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Edit>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.author_id != Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat szerkesztheted.".into()));
|
||||
}
|
||||
open_thread(&state.db, &viewer, post.thread_id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"UPDATE forum.posts SET body = $2, edited_at = now() WHERE id = $1 RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The author takes back their post, or a moderator removes it with a reason.
|
||||
/// Hidden, not erased: the admin can restore it.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let user = viewer.require_user()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let own = post.author_id == Some(user.id);
|
||||
let reason = if own {
|
||||
None
|
||||
} else if viewer.is_moderator() {
|
||||
Some(text::reason(req.reason.as_deref().unwrap_or(""))?)
|
||||
} else {
|
||||
return Err(ApiError::Forbidden("Csak a saját hozzászólásodat törölheted.".into()));
|
||||
};
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(user.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = greatest(reply_count - 1, 0) WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
if !own {
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
user.id,
|
||||
Action::DeletePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
reason.as_deref(),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.posts SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !post.is_opening {
|
||||
sqlx::query("UPDATE forum.threads SET reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(post.thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
admin.id,
|
||||
Action::RestorePost,
|
||||
post.author_id,
|
||||
Some(post.thread_id),
|
||||
Some(id),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct React {
|
||||
kind: String,
|
||||
}
|
||||
|
||||
fn points_of(kind: &str) -> i32 {
|
||||
if kind == "down" { -1 } else { 1 }
|
||||
}
|
||||
|
||||
/// Gives (or changes) the viewer's one reaction to a post. A newcomer's
|
||||
/// reaction shows but moves no points; the ⌄ needs the Kereső rank and is
|
||||
/// not offered in listening topics.
|
||||
pub async fn react(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<React>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if post.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("post"));
|
||||
}
|
||||
open_thread(&state.db, &viewer, thread.id).await?;
|
||||
if post.author_id == Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("A saját hozzászólásodra nem reagálhatsz.".into()));
|
||||
}
|
||||
let kind = req.kind.as_str();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let rank = member.rank(now);
|
||||
if kind == "down" {
|
||||
if thread.listening {
|
||||
return Err(ApiError::Forbidden("Ebben a témában nincs ⌄.".into()));
|
||||
}
|
||||
if !rank.may_downvote() {
|
||||
return Err(ApiError::Forbidden("A ⌄ a Kereső rangtól használható.".into()));
|
||||
}
|
||||
} else if !REACTIONS.contains(&kind) {
|
||||
return Err(ApiError::bad("Ismeretlen reakció."));
|
||||
}
|
||||
let counted = !rank.is_newcomer();
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let previous: Option<(String, bool)> =
|
||||
sqlx::query_as("SELECT kind, counted FROM forum.reactions WHERE post_id = $1 AND user_id = $2 FOR UPDATE")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let mut delta = if counted { points_of(kind) } else { 0 };
|
||||
if let Some((old, true)) = &previous {
|
||||
delta -= points_of(old);
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reactions (post_id, user_id, kind, counted) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT (post_id, user_id) DO UPDATE SET kind = EXCLUDED.kind, counted = EXCLUDED.counted, created_at = now()",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(kind)
|
||||
.bind(counted)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
add_points(&mut tx, post.author_id, delta).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, _) = load(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let removed: Option<(String, bool)> =
|
||||
sqlx::query_as("DELETE FROM forum.reactions WHERE post_id = $1 AND user_id = $2 RETURNING kind, counted")
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some((kind, true)) = removed {
|
||||
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
async fn add_points(tx: &mut sqlx::PgConnection, author: Option<uuid::Uuid>, delta: i32) -> Result<(), sqlx::Error> {
|
||||
if let (Some(author), true) = (author, delta != 0) {
|
||||
sqlx::query("UPDATE forum.members SET points = points + $2 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.bind(delta)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The thread's author marks a reply that helped (worth more than a reaction).
|
||||
pub async fn mark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, true).await
|
||||
}
|
||||
|
||||
pub async fn unmark_helped(state: St, viewer: Viewer, path: IdPath) -> ApiResult<Json<Value>> {
|
||||
set_helped(state, viewer, path, false).await
|
||||
}
|
||||
|
||||
async fn set_helped(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
on: bool,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_writer()?;
|
||||
let (post, thread) = load(&state.db, &viewer, id).await?;
|
||||
if thread.author_id != Some(member.user_id) {
|
||||
return Err(ApiError::Forbidden("Ezt csak a szál indítója jelölheti.".into()));
|
||||
}
|
||||
if post.is_opening || post.author_id == Some(member.user_id) || post.deleted_at.is_some() {
|
||||
return Err(ApiError::bad("Ezt a hozzászólást nem jelölheted."));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
let changed: Option<i64> = if on {
|
||||
sqlx::query_scalar("UPDATE forum.posts SET helped_at = now() WHERE id = $1 AND helped_at IS NULL RETURNING id")
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"UPDATE forum.posts SET helped_at = NULL WHERE id = $1 AND helped_at IS NOT NULL RETURNING id",
|
||||
)
|
||||
}
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if changed.is_some() {
|
||||
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Threads: reading one, starting one, replying, read marks, following, and
|
||||
//! the moderators' lock, pin, removal and the admin's restore.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
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::home::viewer_json;
|
||||
use super::moderation::{self, Action};
|
||||
use super::{Body, IdPath, St, authors, has_purchase, may_read, rfc3339};
|
||||
use crate::AppState;
|
||||
use crate::auth::{Member, Viewer};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::{self, COLLAPSE_SCORE};
|
||||
use crate::text;
|
||||
|
||||
/// The positive reactions; each is +1, the ⌄ (`down`) is -1.
|
||||
pub const REACTIONS: [&str; 4] = ["with_you", "thanks", "me_too", "insight"];
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ThreadRow {
|
||||
pub id: i64,
|
||||
pub topic_slug: String,
|
||||
pub topic_name: String,
|
||||
pub visibility: String,
|
||||
pub listening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub title: String,
|
||||
pub intent: Option<String>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub locked: bool,
|
||||
pub pinned: bool,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub delete_reason: Option<String>,
|
||||
}
|
||||
|
||||
const THREAD_SELECT: &str = "SELECT th.id, tp.slug AS topic_slug, tp.name AS topic_name, tp.visibility, \
|
||||
tp.listening, th.author_id, th.title, th.intent, th.created_at, th.locked, th.pinned, th.deleted_at, \
|
||||
th.delete_reason \
|
||||
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id";
|
||||
|
||||
/// A thread the viewer may read (deleted ones too): 404 when it does not
|
||||
/// exist or sits in a hidden topic, 401 in a members-only topic for a visitor.
|
||||
pub async fn readable_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread: ThreadRow = sqlx::query_as(&format!("{THREAD_SELECT} WHERE th.id = $1"))
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("thread"))?;
|
||||
if !may_read(viewer, &thread.visibility) {
|
||||
return Err(if thread.visibility == "members" { ApiError::Unauthorized } else { ApiError::NotFound("thread") });
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
/// A thread that can take new posts and reactions: not removed, and not
|
||||
/// locked (moderators may still write in a locked one).
|
||||
pub async fn open_thread(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<ThreadRow> {
|
||||
let thread = readable_thread(db, viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Err(ApiError::NotFound("thread"));
|
||||
}
|
||||
if thread.locked && !viewer.is_moderator() {
|
||||
return Err(ApiError::Forbidden("Ez a szál le van zárva.".into()));
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct PostRow {
|
||||
pub id: i64,
|
||||
pub thread_id: i64,
|
||||
pub parent_id: Option<i64>,
|
||||
pub is_opening: bool,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub body: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub edited_at: Option<OffsetDateTime>,
|
||||
pub helped_at: Option<OffsetDateTime>,
|
||||
pub deleted_at: Option<OffsetDateTime>,
|
||||
pub deleted_by: Option<Uuid>,
|
||||
pub delete_reason: Option<String>,
|
||||
}
|
||||
|
||||
pub const POST_COLUMNS: &str = "id, thread_id, parent_id, is_opening, author_id, body, created_at, edited_at, helped_at, deleted_at, deleted_by, \
|
||||
delete_reason";
|
||||
|
||||
/// Posts as the thread page shows them: authors, reactions, the viewer's own
|
||||
/// reaction. A removed post keeps its place with the reason; only
|
||||
/// moderators still see its text.
|
||||
pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiResult<Vec<Value>> {
|
||||
let ids: Vec<i64> = posts.iter().map(|p| p.id).collect();
|
||||
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let mut by_post: HashMap<i64, HashMap<String, i64>> = HashMap::new();
|
||||
for (post, kind, n) in counts {
|
||||
by_post.entry(post).or_default().insert(kind, n);
|
||||
}
|
||||
let mine: HashMap<i64, String> = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
sqlx::query_as("SELECT post_id, kind FROM forum.reactions WHERE post_id = ANY($1) AND user_id = $2")
|
||||
.bind(&ids)
|
||||
.bind(me)
|
||||
.fetch_all(db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let moderator = viewer.is_moderator();
|
||||
Ok(posts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let counts = by_post.remove(&p.id).unwrap_or_default();
|
||||
let positive: i64 = REACTIONS.iter().map(|k| counts.get(*k).copied().unwrap_or(0)).sum();
|
||||
let down = counts.get("down").copied().unwrap_or(0);
|
||||
let score = positive - down;
|
||||
let deleted = p.deleted_at.map(|_| {
|
||||
json!({
|
||||
"by_moderator": p.deleted_by.is_some() && p.deleted_by != p.author_id,
|
||||
"reason": p.delete_reason,
|
||||
})
|
||||
});
|
||||
let mut post = json!({
|
||||
"id": p.id,
|
||||
"parent_id": p.parent_id,
|
||||
"is_opening": p.is_opening,
|
||||
"author": p.author_id.and_then(|id| people.get(&id).cloned()),
|
||||
"own": p.author_id.is_some() && p.author_id == viewer.user_id(),
|
||||
"body": if p.deleted_at.is_none() || moderator { Some(&p.body) } else { None },
|
||||
"deleted": deleted,
|
||||
"created_at": rfc3339(p.created_at),
|
||||
"edited_at": p.edited_at.map(rfc3339),
|
||||
"helped": p.helped_at.is_some(),
|
||||
"reactions": REACTIONS.iter().map(|k| (k.to_string(), json!(counts.get(*k).copied().unwrap_or(0))))
|
||||
.collect::<serde_json::Map<_, _>>(),
|
||||
"score": score,
|
||||
"collapsed": score <= COLLAPSE_SCORE,
|
||||
"mine": mine.get(&p.id),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
}
|
||||
post
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// A thread with all its posts, oldest first.
|
||||
pub async fn show(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let people = authors(&state.db, thread.author_id).await?;
|
||||
let moderator = viewer.is_moderator();
|
||||
let mut out = json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"thread": thread_json(&thread, thread.author_id.and_then(|a| people.get(&a).cloned())),
|
||||
});
|
||||
if thread.deleted_at.is_some() && !moderator {
|
||||
out["posts"] = json!([]);
|
||||
return Ok(Json(out));
|
||||
}
|
||||
let posts: Vec<PostRow> =
|
||||
sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE thread_id = $1 ORDER BY id"))
|
||||
.bind(id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
out["posts"] = json!(posts_json(&state.db, &viewer, &posts).await?);
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let (following, last_read) = match viewer.user_id() {
|
||||
Some(me) => {
|
||||
let following: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.follows WHERE user_id = $1 AND thread_id = $2)")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let last_read: Option<i64> =
|
||||
sqlx::query_scalar("SELECT last_post_id FROM forum.reads WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(me)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
(following, last_read)
|
||||
}
|
||||
None => (false, None),
|
||||
};
|
||||
let writer = viewer.member.as_ref().filter(|m| !m.banned(now));
|
||||
let open = thread.deleted_at.is_none() && (!thread.locked || moderator);
|
||||
out["access"] = json!({
|
||||
"can_reply": open && (writer.is_some() || !viewer.logged_in() || viewer.member.is_none()),
|
||||
"can_downvote": !thread.listening && writer.is_some_and(|m| m.rank(now).may_downvote()),
|
||||
"is_thread_author": thread.author_id.is_some() && thread.author_id == viewer.user_id(),
|
||||
"following": following,
|
||||
"last_read_post_id": last_read,
|
||||
});
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
fn thread_json(thread: &ThreadRow, author: Option<Value>) -> Value {
|
||||
json!({
|
||||
"id": thread.id,
|
||||
"slug": text::slug(&thread.title),
|
||||
"title": thread.title,
|
||||
"intent": thread.intent,
|
||||
"topic": {
|
||||
"slug": thread.topic_slug, "name": thread.topic_name,
|
||||
"visibility": thread.visibility, "listening": thread.listening,
|
||||
},
|
||||
"author": author,
|
||||
"created_at": rfc3339(thread.created_at),
|
||||
"locked": thread.locked,
|
||||
"pinned": thread.pinned,
|
||||
"deleted": thread.deleted_at.map(|_| json!({ "reason": thread.delete_reason })),
|
||||
})
|
||||
}
|
||||
|
||||
/// Too fast, or past a newcomer's daily limit (lifted by a purchase and for moderators).
|
||||
async fn check_limits(state: &AppState, viewer: &Viewer, member: &Member, new_thread: bool) -> ApiResult<()> {
|
||||
let db = &state.db;
|
||||
let recent: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - make_interval(secs => $2))",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.bind(f64::from(state.flood_secs))
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if recent {
|
||||
return Err(ApiError::Limited("Várj pár másodpercet a következő hozzászólással.".into()));
|
||||
}
|
||||
if viewer.is_moderator() || !member.rank(OffsetDateTime::now_utc()).is_newcomer() {
|
||||
return Ok(());
|
||||
}
|
||||
let (threads, posts): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*) FILTER (WHERE is_opening), count(*) FROM forum.posts \
|
||||
WHERE author_id = $1 AND created_at > now() - interval '24 hours'",
|
||||
)
|
||||
.bind(member.user_id)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
let over =
|
||||
if new_thread { threads >= rank::NEWCOMER_THREADS_PER_DAY } else { posts >= rank::NEWCOMER_POSTS_PER_DAY };
|
||||
if over && !has_purchase(db, member.user_id).await? {
|
||||
return Err(ApiError::Limited(if new_thread {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} szálat nyithatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_THREADS_PER_DAY
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Új tagként naponta legfeljebb {} hozzászólást írhatsz. Holnap újra lehet.",
|
||||
rank::NEWCOMER_POSTS_PER_DAY
|
||||
)
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateThread {
|
||||
topic: String,
|
||||
title: String,
|
||||
body: String,
|
||||
#[serde(default)]
|
||||
intent: Option<String>,
|
||||
}
|
||||
|
||||
/// Starts a thread with its opening post; the author follows it.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Json(req), _): Body<CreateThread>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
let topic: Option<(i16, String, bool)> =
|
||||
sqlx::query_as("SELECT id, visibility, listening FROM forum.topics WHERE slug = $1")
|
||||
.bind(&req.topic)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (topic_id, visibility, listening) = topic.ok_or_else(|| ApiError::bad("Ismeretlen téma."))?;
|
||||
if !may_read(&viewer, &visibility) {
|
||||
return Err(ApiError::bad("Ismeretlen téma."));
|
||||
}
|
||||
let title = text::title(&req.title)?;
|
||||
let body = text::body(&req.body)?;
|
||||
let intent = match req.intent.as_deref() {
|
||||
Some(i @ ("listen" | "advice")) => Some(i.to_string()),
|
||||
None | Some("") => listening.then(|| "listen".to_string()),
|
||||
Some(_) => return Err(ApiError::bad("Ismeretlen szándék.")),
|
||||
};
|
||||
check_limits(&state, &viewer, member, true).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let thread_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title, intent) VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
)
|
||||
.bind(topic_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&title)
|
||||
.bind(&intent)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let post_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, $3) RETURNING id",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(member.user_id)
|
||||
.bind(&body)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, thread_id, post_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
|
||||
}
|
||||
|
||||
/// After a post: the author's count, following the thread, and the read mark
|
||||
/// up to their own post.
|
||||
async fn after_post(
|
||||
tx: &mut sqlx::PgConnection,
|
||||
author: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE forum.members SET post_count = post_count + 1 WHERE user_id = $1")
|
||||
.bind(author)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(author)
|
||||
.bind(thread_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
upsert_read(&mut *tx, author, thread_id, post_id).await
|
||||
}
|
||||
|
||||
async fn upsert_read(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
user: Uuid,
|
||||
thread_id: i64,
|
||||
post_id: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(thread_id)
|
||||
.bind(post_id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reply {
|
||||
body: String,
|
||||
/// The post answered; a reply to a reply goes under the same first-level
|
||||
/// post (two levels at most), a reply to the opening post is first-level.
|
||||
#[serde(default)]
|
||||
parent_id: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn reply(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reply>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let member = viewer.require_writer()?;
|
||||
open_thread(&state.db, &viewer, id).await?;
|
||||
let body = text::body(&req.body)?;
|
||||
let parent = match req.parent_id {
|
||||
None => None,
|
||||
Some(parent_id) => {
|
||||
let parent: Option<(Option<i64>, bool, bool)> = sqlx::query_as(
|
||||
"SELECT parent_id, is_opening, deleted_at IS NOT NULL FROM forum.posts WHERE id = $1 AND thread_id = $2",
|
||||
)
|
||||
.bind(parent_id)
|
||||
.bind(id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (grandparent, is_opening, deleted) = parent.ok_or_else(|| ApiError::bad("Ismeretlen hozzászólás."))?;
|
||||
if deleted {
|
||||
return Err(ApiError::bad("Törölt hozzászólásra nem lehet válaszolni."));
|
||||
}
|
||||
if is_opening { None } else { Some(grandparent.unwrap_or(parent_id)) }
|
||||
}
|
||||
};
|
||||
check_limits(&state, &viewer, member, false).await?;
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
let post: PostRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, $4) RETURNING {POST_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(member.user_id)
|
||||
.bind(parent)
|
||||
.bind(&body)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE forum.threads SET last_post_at = now(), reply_count = reply_count + 1 WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||
tx.commit().await?;
|
||||
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||
Ok((StatusCode::CREATED, Json(post)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReadMark {
|
||||
post_id: i64,
|
||||
}
|
||||
|
||||
/// Read up to that post (never backwards).
|
||||
pub async fn mark_read(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ReadMark>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
let last: Option<i64> = sqlx::query_scalar("SELECT max(id) FROM forum.posts WHERE thread_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let Some(last) = last else { return Ok(StatusCode::NO_CONTENT) };
|
||||
upsert_read(&state.db, member.user_id, id, req.post_id.min(last)).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn follow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
readable_thread(&state.db, &viewer, id).await?;
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2) ON CONFLICT DO NOTHING")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn unfollow(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query("DELETE FROM forum.follows WHERE user_id = $1 AND thread_id = $2")
|
||||
.bind(member.user_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ThreadChange {
|
||||
#[serde(default)]
|
||||
locked: Option<bool>,
|
||||
#[serde(default)]
|
||||
pinned: Option<bool>,
|
||||
}
|
||||
|
||||
/// Moderators lock (no more replies) or pin (first in its topic) a thread.
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<ThreadChange>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
if let Some(locked) = req.locked.filter(|l| *l != thread.locked) {
|
||||
sqlx::query("UPDATE forum.threads SET locked = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(locked)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if locked { Action::Lock } else { Action::Unlock };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
if let Some(pinned) = req.pinned.filter(|p| *p != thread.pinned) {
|
||||
sqlx::query("UPDATE forum.threads SET pinned = $2 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(pinned)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let action = if pinned { Action::Pin } else { Action::Unpin };
|
||||
moderation::record(&mut *tx, moderator.id, action, thread.author_id, Some(id), None, None, None).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Reason {
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// A moderator removes a whole thread; its place keeps the reason.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<Reason>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let moderator = viewer.require_moderator()?;
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_some() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now(), deleted_by = $2, delete_reason = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(moderator.id)
|
||||
.bind(&reason)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(
|
||||
&mut *tx,
|
||||
moderator.id,
|
||||
Action::DeleteThread,
|
||||
thread.author_id,
|
||||
Some(id),
|
||||
None,
|
||||
Some(&reason),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = id, moderator = %moderator.id, "thread removed");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The admin undoes a thread's removal.
|
||||
pub async fn restore(State(state): St, viewer: Viewer, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
||||
let admin = viewer.require_user()?;
|
||||
if !viewer.is_admin() {
|
||||
return Err(ApiError::Forbidden("Visszaállítani csak az admin tud.".into()));
|
||||
}
|
||||
let thread = readable_thread(&state.db, &viewer, id).await?;
|
||||
if thread.deleted_at.is_none() {
|
||||
return Ok(StatusCode::NO_CONTENT);
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = NULL, deleted_by = NULL, delete_reason = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
moderation::record(&mut *tx, admin.id, Action::RestoreThread, thread.author_id, Some(id), None, None, None).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
Reference in New Issue
Block a user