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