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? })))
|
||||
}
|
||||
Reference in New Issue
Block a user