Files
sorsfonalak/services/forum/src/routes/mod.rs
T

320 lines
13 KiB
Rust
Raw Normal View History

//! 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 messages;
mod moderation;
mod posts;
mod reports;
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/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/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))
.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 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
}