//! 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 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 = WithRejection, ApiError>; pub type IdPath = WithRejection, ApiError>; pub type St = State>; pub fn router(state: Arc) -> 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/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, 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 = 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, pub author_id: Option, 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, /// 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, } /// `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, Option) { 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) -> Result, 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, chart_share: String, roles: Vec, 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) -> Result, sqlx::Error> { let mut ids: Vec = ids.into_iter().collect(); ids.sort_unstable(); ids.dedup(); if ids.is_empty() { return Ok(HashMap::new()); } let rows: Vec = 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 = 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, 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, } 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 { 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, sqlx::Error> { if users.is_empty() { return Ok(HashMap::new()); } type Row = (Uuid, Option, Option, Option); let rows: Vec = 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 { sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM package_orders WHERE user_id = $1 AND source = 'stripe')") .bind(user) .fetch_one(db) .await }