Files
sorsfonalak/services/forum/src/routes/mod.rs
T
fecoandClaude Opus 5.5 de629a068d
CI / test (push) Successful in 3m10s
CI / build (push) Skipped
CI / deploy (push) Skipped
Forum photos, a one-row bottom menu, and the site's own question windows
Photos in posts and replies: a "Fotó" button in the new thread form and the
reply boxes. The browser makes the picture small before uploading it (1600
pixels at most, WebP, JPEG where WebP cannot be made); the forum checks it
is a still picture, strips its metadata and makes a square preview
(forum-photos/ in the storage). Five a member a day, five a post; one taken
off before sending is deleted and does not count. Under the post a row of
square previews; a click opens a viewer paged with arrows, swipes and keys.
Seen by whoever may read the thread (long public cache only for public
topics). Unsent photos go after a day, those of removed posts after a year;
removed with the account and listed in the data export. Terms and privacy
notice updated.

The forum's bottom menu keeps its five items in one row (the fifth wrapped
to a second row). On iPhones, when the keyboard goes away without the usual
tap (a photo picker opening over it), the page is put back in place instead
of the menu floating mid-screen over an empty strip.

The browser's own confirm() and prompt() windows (23 places: deleting,
revoking, blocking, muting, moderators' reasons, admin actions) are replaced
by a question window in the site's look, following the forum's light or
dark theme, with named buttons and a text box for reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-27 00:34:59 +00:00

390 lines
16 KiB
Rust

//! 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 attachments;
mod avatars;
mod home;
mod members;
mod mentions;
mod messages;
mod moderation;
mod mutes;
mod photos;
mod posts;
mod replies;
mod reports;
mod search;
mod threads;
mod topics;
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 use photos::cleanup as photo_cleanup;
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).post(topics::create))
.route("/v1/forum/topics/{slug}", get(home::topic).patch(topics::update))
.route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave))
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
.route("/v1/forum/followed", get(home::followed))
.route("/v1/forum/latest", get(home::latest))
.route("/v1/forum/replies", get(replies::list))
.route("/v1/forum/search", get(search::search))
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
.route("/v1/forum/link-thumbs/{file}", get(crate::links::thumbnail))
.route("/v1/forum/posts/{id}/share", axum::routing::delete(posts::detach_share))
.route("/v1/forum/sitemap", get(search::sitemap))
.route("/v1/forum/replies/read", post(replies::read_all))
.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/posts/{id}/report", post(reports::report_post))
.route("/v1/forum/messages/{id}/report", post(reports::report_message))
.route("/v1/forum/conversations", get(messages::list).post(messages::request))
.route("/v1/forum/conversations/{id}", get(messages::show))
.route("/v1/forum/conversations/{id}/accept", post(messages::accept))
.route("/v1/forum/conversations/{id}/decline", post(messages::decline))
.route("/v1/forum/conversations/{id}/block", post(messages::block).delete(messages::unblock))
.route("/v1/forum/conversations/{id}/messages", post(messages::send))
.route("/v1/forum/conversations/{id}/read", post(messages::read))
.route("/v1/forum/me", get(members::me).put(members::save_me))
.route(
"/v1/forum/me/avatar",
put(avatars::upload).layer(axum::extract::DefaultBodyLimit::max(avatars::MAX_UPLOAD + 1024)),
)
.route("/v1/forum/avatars/{file}", get(avatars::serve))
.route(
"/v1/forum/photos",
post(photos::upload).layer(axum::extract::DefaultBodyLimit::max(photos::MAX_UPLOAD + 1024)),
)
.route("/v1/forum/photos/{file}", get(photos::serve).delete(photos::discard))
.route("/v1/forum/members/{nickname}/avatar-reset", post(avatars::reset))
.route("/v1/forum/nickname-check", get(members::nickname_check))
.route("/v1/forum/presence", post(members::presence))
.route("/v1/forum/unsubscribe", post(members::unsubscribe))
.route("/v1/forum/ws", get(crate::live::connect))
.route("/v1/forum/members/search", get(mentions::search))
.route("/v1/forum/members/{nickname}", get(members::profile))
.route("/v1/forum/members/{nickname}/mute", put(mutes::mute).delete(mutes::unmute))
.route("/v1/forum/members/{nickname}/founder", put(mutes::set_founder))
.route("/v1/forum/me/mutes", get(mutes::list))
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
.route("/v1/forum/mod/log", get(moderation::log))
.route("/v1/forum/mod/reports", get(reports::list))
.route("/v1/forum/mod/reports/{id}", post(reports::handle))
// The request log: masked paths, health checks only when they fail.
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
.with_state(state)
}
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 and their approved topic ids only, never
/// from input.
pub fn visible_topics(viewer: &Viewer) -> String {
if viewer.is_moderator() {
"TRUE".into()
} else if viewer.logged_in() {
let mut sql = "tp.visibility IN ('public', 'members')".to_string();
if !viewer.topics.is_empty() {
let ids: Vec<String> = viewer.topics.iter().map(|id| id.to_string()).collect();
sql.push_str(&format!(" OR tp.id IN ({})", ids.join(", ")));
}
sql
} else {
"tp.visibility = 'public'".into()
}
}
/// Whether the viewer may read a topic of this visibility (restricted: only
/// moderators and the approved members).
pub fn may_read(viewer: &Viewer, visibility: &str, topic: i16) -> bool {
match visibility {
"public" => true,
"members" => viewer.logged_in(),
_ => viewer.is_moderator() || viewer.topics.contains(&topic),
}
}
/// 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>,
/// The site's own thread (the daily sky).
pub system: bool,
pub topic_visibility: String,
/// The opening post's text (for the excerpt on the card).
pub opening: Option<String>,
}
/// `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`.
/// `col` (an author) is not muted by the viewer, `$1` (true for visitors).
pub fn not_muted(col: &str) -> String {
format!("NOT EXISTS (SELECT 1 FROM forum.mutes mu WHERE mu.user_id = $1 AND mu.muted_id = {col})")
}
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 {} \
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, \
th.system, tp.visibility AS topic_visibility, \
(SELECT p.body FROM forum.posts p WHERE p.thread_id = th.id AND p.is_opening \
AND p.deleted_at IS NULL LIMIT 1) AS opening \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.deleted_at IS NULL AND ({}) AND {}",
not_muted("p.author_id"),
visible_topics(viewer),
not_muted("th.author_id"),
)
}
/// `$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, "visibility": r.topic_visibility },
"author": r.author_id.and_then(|id| people.get(&id).cloned()),
// The start of the opening post, as much as a card shows.
"excerpt": r.opening.as_deref().map(|b| crate::text::excerpt(b, 280)),
"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,
"system": r.system,
})
})
.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>,
listener: bool,
supporter: bool,
founder: bool,
}
/// 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, m.listener, m.founder, \
m.supporter_badge AND EXISTS (SELECT 1 FROM package_orders o \
WHERE o.user_id = m.user_id AND o.source = 'stripe') AS supporter \
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,
"listener": r.listener,
"supporter": r.supporter,
"founder": r.founder,
});
(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
}