45.1 KiB · text History 01d6190
use axum::{
    extract::{Form, Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect},
};
use axum_htmx::HxRequest;
use chrono::Utc;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use tracing::error;
use uuid::Uuid;

/// A given viewer bumps a topic's view count at most once per this window.
const VIEW_WINDOW: Duration = Duration::from_secs(600); // 10 minutes

/// Topic-list ordering. Pinned topics always sort first; this controls the
/// order among the rest (and among pinned).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TopicSort {
    Latest,
    Top,
    Bottom,
    Hot,
}

impl TopicSort {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "latest" => Some(Self::Latest),
            "top" => Some(Self::Top),
            "bottom" => Some(Self::Bottom),
            "hot" => Some(Self::Hot),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Latest => "latest",
            Self::Top => "top",
            Self::Bottom => "bottom",
            Self::Hot => "hot",
        }
    }
}

/// "Hotness": engagement (posts) decayed by how long since the last reply.
/// Higher = hotter.
fn hot_score(t: &topics::Model, now: chrono::DateTime<chrono::Utc>) -> f64 {
    let hours = (now - t.bumped_at.with_timezone(&chrono::Utc))
        .num_seconds()
        .max(0) as f64
        / 3600.0;
    (t.posts_count.max(0) as f64) / (hours + 2.0).powf(1.5)
}

/// Sort topics in place: pinned first, then by the chosen order.
pub(crate) fn sort_topics(rows: &mut [(topics::Model, Option<users::Model>)], sort: TopicSort) {
    let now = Utc::now();
    rows.sort_by(|(a, _), (b, _)| {
        b.is_pinned.cmp(&a.is_pinned).then_with(|| match sort {
            TopicSort::Latest => b.bumped_at.cmp(&a.bumped_at),
            TopicSort::Top => b.views.cmp(&a.views).then(b.bumped_at.cmp(&a.bumped_at)),
            TopicSort::Bottom => a.views.cmp(&b.views).then(b.bumped_at.cmp(&a.bumped_at)),
            TopicSort::Hot => hot_score(b, now)
                .partial_cmp(&hot_score(a, now))
                .unwrap_or(std::cmp::Ordering::Equal),
        })
    });
}

/// The client address for throttling anonymous viewers: the one the
/// trusted-proxy layer resolved ([`crate::client_ip::RESOLVED_HEADER`]),
/// never a client-supplied X-Forwarded-For / X-Real-IP, so a visitor can't
/// mint fresh views by forging those. Unknown: one shared bucket.
fn client_ip(headers: &HeaderMap) -> String {
    headers
        .get(crate::client_ip::RESOLVED_HEADER)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "anon".to_string())
}

use crate::category_tree::{color_widget_css, CategoryTree, Viewer};
use crate::entities::{
    bookmarks, categories, category_watches, post_flags, posts, tags, topic_reads, topic_tags, topics, users,
};
use crate::handlers::reactions::{active_reaction_types, reaction_views_for_posts, ReactionView};
use crate::middleware::UserContext;
use crate::timeutil::{abs, rel};
use crate::AppState;

pub(crate) fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
    move |e| {
        error!(error = %e, "{ctx}");
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

#[derive(Serialize)]
struct SubRow {
    name: String,
    slug: String,
    depth: i32,
    topic_count: u64,
    /// CSS `background` for the lineage widget (full circle / halves / thirds).
    widget_bg: String,
}

#[derive(Serialize)]
struct CategoryRow {
    name: String,
    slug: String,
    description: Option<String>,
    topic_count: u64,
    widget_bg: String,
    subcategories: Vec<SubRow>,
}

#[derive(Serialize)]
struct Crumb {
    name: String,
    slug: String,
}

#[derive(Serialize)]
struct ChipRow {
    name: String,
    slug: String,
    widget_bg: String,
}

#[derive(Serialize, Clone)]
pub struct TagChip {
    pub name: String,
    pub slug: String,
}

#[derive(Serialize, Clone)]
pub struct TopicRow {
    pub(crate) id: Uuid,
    pub(crate) title: String,
    pub(crate) is_pinned: bool,
    pub(crate) is_closed: bool,
    pub(crate) posts_count: i32,
    pub(crate) views: i32,
    pub(crate) bumped_at: String,
    pub(crate) bumped_at_abs: String,
    pub(crate) author: String,
    pub(crate) author_id: Uuid,
    pub(crate) author_has_avatar: bool,
    /// The topic's own category widget (lineage circle), shown to the left of
    /// the title; links to that category.
    pub(crate) cat_widget_bg: String,
    pub(crate) cat_name: String,
    pub(crate) cat_slug: String,
    pub(crate) tags: Vec<TagChip>,
    /// Instants for the API (templates use the strings above).
    #[serde(skip)]
    pub(crate) created: chrono::DateTime<chrono::FixedOffset>,
    #[serde(skip)]
    pub(crate) bumped: chrono::DateTime<chrono::FixedOffset>,
    #[serde(skip)]
    pub(crate) category_id: Uuid,
}

/// Read-capability of an optional viewer.
pub fn viewer_of(uc: &Option<UserContext>) -> Viewer {
    Viewer {
        level: uc.as_ref().map(|c| c.user.trust_level),
        staff: uc.as_ref().is_some_and(|c| c.user.is_staff),
    }
}

pub(crate) fn viewer_user(u: &UserContext) -> Viewer {
    Viewer {
        level: Some(u.user.trust_level),
        staff: u.user.is_staff,
    }
}

/// 404 unless the viewer can read `category_id`.
pub async fn ensure_category_visible(
    state: &AppState,
    category_id: Uuid,
    uc: &Option<UserContext>,
) -> Result<(), StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    if tree.can_view(category_id, viewer_of(uc)) {
        Ok(())
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

/// 404 unless the viewer can read the topic's category.
pub async fn ensure_topic_visible(
    state: &AppState,
    topic_id: Uuid,
    uc: &Option<UserContext>,
) -> Result<(), StatusCode> {
    let topic = topics::Entity::find_by_id(topic_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for visibility"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    ensure_category_visible(state, topic.category_id, uc).await
}

/// Slugify a tag name (lowercase alphanumerics; runs of other chars → `-`).
fn tag_slug(s: &str) -> String {
    let mut out = String::new();
    let mut dash = false;
    for ch in s.trim().chars() {
        if ch.is_alphanumeric() {
            out.extend(ch.to_lowercase());
            dash = false;
        } else if !out.is_empty() && !dash {
            out.push('-');
            dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    out
}

/// Tag chips for a single topic.
pub(crate) async fn tags_for_topic(state: &AppState, topic_id: Uuid) -> Result<Vec<TagChip>, StatusCode> {
    Ok(topic_tags::Entity::find()
        .filter(topic_tags::Column::TopicId.eq(topic_id))
        .find_also_related(tags::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load topic tags"))?
        .into_iter()
        .filter_map(|(_, t)| t.map(|t| TagChip { name: t.name, slug: t.slug }))
        .collect())
}

/// Maximum number of tags on one topic.
const MAX_TAGS: usize = 5;

/// Parse a comma-separated tag list into `(name, slug)` pairs: trimmed,
/// slugified, deduplicated by slug, at most [`MAX_TAGS`].
fn parse_tag_list(raw: &str) -> Vec<(String, String)> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for piece in raw.split(',') {
        let name = piece.trim();
        if name.is_empty() || name.chars().count() > 64 {
            continue;
        }
        let slug = tag_slug(name);
        if slug.is_empty() || !seen.insert(slug.clone()) {
            continue;
        }
        out.push((name.to_string(), slug));
        if out.len() >= MAX_TAGS {
            break;
        }
    }
    out
}

/// Attach the tags in `raw` to a topic. Existing tags are reused; brand-new
/// tags are only minted when `user` meets the trust gate (others are silently
/// skipped). Does not remove tags already on the topic.
pub(crate) async fn apply_tags(
    state: &AppState,
    topic_id: Uuid,
    raw: &str,
    user: &users::Model,
) -> Result<(), StatusCode> {
    let may_create_tags = crate::trust::can_create_tags(user, state.config.min_trust_to_create_tag);
    let now = Utc::now();
    for (name, slug) in parse_tag_list(raw) {
        let tag = match tags::Entity::find()
            .filter(tags::Column::Slug.eq(&slug))
            .one(state.db.as_ref())
            .await
            .map_err(ise("look up tag"))?
        {
            Some(t) => Some(t),
            None if may_create_tags => tags::ActiveModel {
                id: Set(Uuid::now_v7()),
                name: Set(name),
                slug: Set(slug),
                created_at: Set(now.into()),
            }
            .insert(state.db.as_ref())
            .await
            .ok(),
            None => None, // not allowed to mint new tags
        };
        if let Some(tag) = tag {
            let already = topic_tags::Entity::find()
                .filter(topic_tags::Column::TopicId.eq(topic_id))
                .filter(topic_tags::Column::TagId.eq(tag.id))
                .one(state.db.as_ref())
                .await
                .map_err(ise("check topic tag"))?
                .is_some();
            if !already {
                topic_tags::ActiveModel {
                    id: Set(Uuid::now_v7()),
                    topic_id: Set(topic_id),
                    tag_id: Set(tag.id),
                }
                .insert(state.db.as_ref())
                .await
                .map_err(ise("insert topic tag"))?;
            }
        }
    }
    Ok(())
}

/// Build display rows for a set of loaded topics (category circle, author,
/// tags). Reused by category, tag, and search listings.
pub async fn build_topic_rows(
    state: &AppState,
    tree: &CategoryTree,
    loaded: Vec<(topics::Model, Option<users::Model>)>,
) -> Result<Vec<TopicRow>, StatusCode> {
    let topic_ids: Vec<Uuid> = loaded.iter().map(|(t, _)| t.id).collect();

    // Batch-load tags for all topics.
    let mut tag_map: std::collections::HashMap<Uuid, Vec<TagChip>> = std::collections::HashMap::new();
    if !topic_ids.is_empty() {
        let links = topic_tags::Entity::find()
            .filter(topic_tags::Column::TopicId.is_in(topic_ids.iter().copied()))
            .find_also_related(tags::Entity)
            .all(state.db.as_ref())
            .await
            .map_err(ise("load tags"))?;
        for (link, tag) in links {
            if let Some(t) = tag {
                tag_map
                    .entry(link.topic_id)
                    .or_default()
                    .push(TagChip { name: t.name, slug: t.slug });
            }
        }
    }

    Ok(loaded
        .into_iter()
        .map(|(t, u)| {
            let (cat_widget_bg, cat_name, cat_slug) = match tree.get(t.category_id) {
                Some(c) => (
                    color_widget_css(&tree.widget_colors(t.category_id)),
                    c.name.clone(),
                    c.slug.clone(),
                ),
                None => (color_widget_css(&[]), String::new(), String::new()),
            };
            TopicRow {
                tags: tag_map.remove(&t.id).unwrap_or_default(),
                created: t.created_at,
                bumped: t.bumped_at,
                category_id: t.category_id,
                id: t.id,
                title: t.title,
                is_pinned: t.is_pinned,
                is_closed: t.is_closed,
                posts_count: t.posts_count,
                views: t.views,
                bumped_at: rel(t.bumped_at),
                bumped_at_abs: abs(t.bumped_at),
                author: author_name(&u),
                author_id: t.user_id,
                author_has_avatar: u.as_ref().is_some_and(|u| u.avatar_content_type.is_some()),
                cat_widget_bg,
                cat_name,
                cat_slug,
            }
        })
        .collect())
}

/// Count non-deleted topics across a set of category ids.
async fn count_topics_in(state: &AppState, ids: &[Uuid]) -> Result<u64, StatusCode> {
    if ids.is_empty() {
        return Ok(0);
    }
    topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(ids.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .count(state.db.as_ref())
        .await
        .map_err(ise("count topics"))
}

#[derive(Serialize)]
pub(crate) struct PostRow {
    pub(crate) id: Uuid,
    pub(crate) post_number: i32,
    pub(crate) cooked: String,
    pub(crate) created_at: String,
    pub(crate) created_at_abs: String,
    pub(crate) author: String,
    pub(crate) author_id: Uuid,
    pub(crate) author_has_avatar: bool,
    pub(crate) edited: bool,
    pub(crate) deleted: bool,
    pub(crate) deleted_by: Option<String>,
    pub(crate) can_edit: bool,
    pub(crate) can_restore: bool,
    pub(crate) bookmarked: bool,
    pub(crate) reactions: Vec<ReactionView>,
    /// The body is a staff note ("staff: …"), by `moderated_by`.
    pub(crate) moderated: bool,
    pub(crate) moderated_by: Option<String>,
    /// Hidden pending staff review. `cooked` is empty unless the viewer is
    /// staff or the author (`show_hidden`).
    pub(crate) hidden: bool,
    pub(crate) show_hidden: bool,
    pub(crate) can_react: bool,
    pub(crate) can_bookmark: bool,
    pub(crate) can_flag: bool,
    /// This viewer has flagged it.
    pub(crate) flagged: bool,
    /// Staff: moderation controls, and how many flags await review.
    pub(crate) can_moderate: bool,
    pub(crate) pending_flags: u64,
    #[serde(skip)]
    pub(crate) moderated_at: Option<chrono::DateTime<chrono::FixedOffset>>,
    #[serde(skip)]
    pub(crate) created: chrono::DateTime<chrono::FixedOffset>,
    #[serde(skip)]
    pub(crate) edited_at: Option<chrono::DateTime<chrono::FixedOffset>>,
}

fn author_name(user: &Option<users::Model>) -> String {
    user.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".to_string())
}

async fn username_of(state: &AppState, id: Option<Uuid>) -> Option<String> {
    let id = id?;
    users::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .ok()
        .flatten()
        .map(|u| u.username)
}


/// The categories page (`/c/`): every visible category with its
/// subcategories and topic counts, or category tiles in Focus. This was the
/// landing page; `/` is now [`super::landing::home`].
pub async fn categories_index(
    State(state): State<AppState>,
    Query(q): Query<HomeQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<axum::response::Response, StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let view = super::focus::view_for(&state, q.view.as_deref(), user_context.as_ref(), &headers);
    if view.mode == super::focus::ViewMode::Focus {
        let page =
            super::focus::home_focus(&state, &tree, viewer_of(&user_context), user_context.as_ref()).await?;
        return Ok(view.respond(page));
    }
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let only_visible = |ids: Vec<Uuid>| -> Vec<Uuid> {
        ids.into_iter().filter(|i| vis.contains(i)).collect()
    };

    let mut rows = Vec::with_capacity(tree.roots().len());
    for &root in tree.roots() {
        if !vis.contains(&root) {
            continue;
        }
        let Some(c) = tree.get(root) else { continue };
        let topic_count =
            count_topics_in(&state, &only_visible(tree.self_and_descendants(root))).await?;

        let mut subcategories = Vec::new();
        for (id, depth) in tree.descendants_with_depth(root) {
            if !vis.contains(&id) {
                continue;
            }
            if let Some(sub) = tree.get(id) {
                subcategories.push(SubRow {
                    name: sub.name.clone(),
                    slug: sub.slug.clone(),
                    depth,
                    topic_count: count_topics_in(&state, &only_visible(tree.self_and_descendants(id)))
                        .await?,
                    widget_bg: color_widget_css(&tree.widget_colors(id)),
                });
            }
        }

        rows.push(CategoryRow {
            name: c.name.clone(),
            slug: c.slug.clone(),
            description: c.description.clone(),
            topic_count,
            widget_bg: color_widget_css(&tree.widget_colors(root)),
            subcategories,
        });
    }

    let page = render(&state, "forum/home.html", context! {
        title => "Home",
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        categories => rows,
    })?;
    Ok(view.respond(page))
}

#[derive(Debug, Deserialize)]
pub struct HomeQuery {
    /// `list` or `focus`; see [`super::focus::resolve_view`].
    pub view: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryQuery {
    pub sort: Option<String>,
    /// `list` or `focus` (visual mode). Explicit = remembered (see
    /// [`super::focus::resolve_view`]).
    pub view: Option<String>,
    /// Visual mode: open the reader at this topic.
    pub topic: Option<Uuid>,
}

/// Effective sort: explicit `?sort=` wins, else the signed-in user's saved
/// preference, else latest. An explicit choice updates that preference.
pub(crate) async fn resolve_sort(state: &AppState, requested: Option<&str>, uc: Option<&UserContext>) -> TopicSort {
    let requested = requested.and_then(TopicSort::parse);
    let sort = requested
        .or_else(|| uc.and_then(|c| TopicSort::parse(&c.user.preferred_sort)))
        .unwrap_or(TopicSort::Latest);
    if let (Some(req), Some(ctx)) = (requested, uc) {
        if ctx.user.preferred_sort != req.as_str() {
            let mut am: users::ActiveModel = ctx.user.clone().into();
            am.preferred_sort = Set(req.as_str().to_string());
            let _ = am.update(state.db.as_ref()).await;
        }
    }
    sort
}

/// List the topics within a category.
pub async fn category_show(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    Query(q): Query<CategoryQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<axum::response::Response, StatusCode> {
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let viewer = viewer_of(&user_context);
    if !tree.can_view(category.id, viewer) {
        return Err(StatusCode::NOT_FOUND);
    }
    let vis = tree.visible_category_ids(viewer);

    // Effective sort: explicit ?sort= wins, else the signed-in user's saved
    // preference, else latest. An explicit choice updates that preference.
    let sort = resolve_sort(&state, q.sort.as_deref(), user_context.as_ref()).await;
    let view = super::focus::view_for(&state, q.view.as_deref(), user_context.as_ref(), &headers);
    if view.mode == super::focus::ViewMode::Focus {
        let page = super::focus::category_focus(
            &state,
            &tree,
            &category,
            viewer,
            sort,
            user_context.as_ref(),
            &headers,
            q.topic,
        )
        .await?;
        return Ok(view.respond(page));
    }

    // Topics from this category AND every VISIBLE descendant roll up here.
    let loaded = super::focus::category_topics(&state, &tree, &vis, category.id, sort).await?;
    let rows = build_topic_rows(&state, &tree, loaded).await?;

    let ancestors: Vec<Crumb> = tree
        .ancestors(category.id)
        .into_iter()
        .filter_map(|id| tree.get(id).map(|c| Crumb { name: c.name.clone(), slug: c.slug.clone() }))
        .collect();

    let subcategories: Vec<ChipRow> = tree
        .children(category.id)
        .iter()
        .filter(|id| vis.contains(id))
        .filter_map(|&id| tree.get(id).map(|c| ChipRow {
            name: c.name.clone(),
            slug: c.slug.clone(),
            widget_bg: color_widget_css(&tree.widget_colors(id)),
        }))
        .collect();

    let category_widget_bg = color_widget_css(&tree.widget_colors(category.id));

    let watching = match user_context.as_ref() {
        Some(c) => category_watches::Entity::find()
            .filter(category_watches::Column::UserId.eq(c.user.id))
            .filter(category_watches::Column::CategoryId.eq(category.id))
            .one(state.db.as_ref())
            .await
            .map_err(ise("query watch"))?
            .is_some(),
        None => false,
    };

    let (can_create_topic, create_block) =
        crate::actions::create_caps(&state, user_context.as_ref().map(|c| &c.user), &category);
    let page = render(&state, "forum/category.html", context! {
        can_create_topic => can_create_topic,
        create_block => create_block,
        rules => posting_badges(&category),
        title => category.name,
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        category => category,
        category_widget_bg => category_widget_bg,
        ancestors => ancestors,
        subcategories => subcategories,
        topics => rows,
        current_sort => sort.as_str(),
        slug => category.slug,
        watching => watching,
    })?;
    Ok(view.respond(page))
}

/// Badges for a category's posting rules ("Staff start topics", "TL3+
/// reply"), shown beside its name.
pub(crate) fn posting_badges(c: &categories::Model) -> Vec<String> {
    let mut out = Vec::new();
    if let Some(b) = crate::policy::topic_rule(c).badge() {
        out.push(format!("{b} start topics"));
    }
    if let Some(b) = crate::policy::reply_rule(c).badge() {
        out.push(format!("{b} reply"));
    }
    if let Some(b) = crate::policy::ReactionRule::of(c).badge(|_| None) {
        out.push(b);
    }
    out
}

#[derive(Serialize)]
struct ParticipantRow {
    id: Uuid,
    name: String,
    has_avatar: bool,
    count: i64,
}

/// Show a single topic with its posts.
pub async fn topic_show(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Query(q): Query<TopicQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<axum::response::Response, StatusCode> {
    let view = super::focus::view_for(&state, q.view.as_deref(), user_context.as_ref(), &headers);
    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let category = categories::Entity::find_by_id(topic.category_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic category"))?;

    // Category read gating: hidden topics 404 for non-permitted viewers.
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    if !tree.can_view(topic.category_id, viewer_of(&user_context)) {
        return Err(StatusCode::NOT_FOUND);
    }

    // (current user id, is_staff) for per-post + topic controls.
    let current = user_context.as_ref().map(|c| (c.user.id, c.user.is_staff));
    let is_staff = current.is_some_and(|(_, staff)| staff);
    let topic_deleted = topic.deleted_at.is_some();

    // A deleted topic still resolves (so links don't 404), but non-staff only
    // see a tombstone — never the content.
    if topic_deleted && !is_staff {
        let page = render(&state, "forum/topic_deleted.html", context! {
            title => "Topic removed",
            app_name => state.config.app_name,
            user => user_context.map(|c| c.user),
            category => category,
        })?;
        return Ok(view.respond(page));
    }

    let can_delete_topic =
        !topic_deleted && current.is_some_and(|(uid, staff)| staff || uid == topic.user_id);
    let can_restore_topic = topic_deleted && is_staff;

    // Views and read state, shared with the visual-mode reader.
    if !topic_deleted {
        record_topic_view(&state, &topic, current.map(|(uid, _)| uid), &headers).await;
    }

    let loaded = load_posts(&state, topic.id).await?;

    // Top other repliers in the thread (excludes the opening poster, most posts
    // first) — shown as a participants strip on wide screens.
    let participants: Vec<ParticipantRow> = {
        let mut pc: std::collections::HashMap<Uuid, (String, bool, i64)> =
            std::collections::HashMap::new();
        for (p, u) in &loaded {
            if p.deleted_at.is_some() || p.user_id == topic.user_id {
                continue;
            }
            let e = pc.entry(p.user_id).or_insert_with(|| {
                (
                    u.as_ref().map(|x| x.username.clone()).unwrap_or_else(|| "unknown".to_string()),
                    u.as_ref().is_some_and(|x| x.avatar_content_type.is_some()),
                    0,
                )
            });
            e.2 += 1;
        }
        let mut v: Vec<ParticipantRow> = pc
            .into_iter()
            .map(|(id, (name, has_avatar, count))| ParticipantRow { id, name, has_avatar, count })
            .collect();
        v.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
        v.truncate(4);
        v
    };

    let caps = crate::actions::topic_caps(
        &state,
        user_context.as_ref().map(|c| &c.user),
        tree.get(topic.category_id),
        &topic,
    );
    let rows = build_post_rows(&state, loaded, user_context.as_ref().map(|c| &c.user), &topic, &caps).await?;

    let topic_tag_chips = tags_for_topic(&state, topic.id).await?;
    // Tag editing: topic author or staff, on a live topic.
    let can_edit_tags =
        user_context.as_ref().is_some_and(|c| crate::actions::can_edit_tags(&state, &c.user, &topic));
    let may_create_tags = user_context.as_ref().is_some_and(|c| {
        crate::trust::can_create_tags(&c.user, state.config.min_trust_to_create_tag)
    });

    let ctx = context! {
        title => topic.title,
        app_name => state.config.app_name,
        user => user_context.as_ref().map(|c| c.user.clone()),
        category => category,
        topic => topic,
        posts => rows,
        tags => topic_tag_chips,
        can_edit_tags => can_edit_tags,
        may_create_tags => may_create_tags,
        min_trust => state.config.min_trust_to_create_tag,
        participants => participants,
        topic_deleted => topic_deleted,
        can_delete_topic => can_delete_topic,
        can_restore_topic => can_restore_topic,
        caps => caps,
        flag_reasons => crate::policy::FLAG_REASONS,
    };
    if !view.is_focus() {
        let page = render(&state, "forum/topic.html", ctx)?;
        return Ok(view.respond(page));
    }

    // Focus: the same page full screen, with the rail of the category's
    // siblings and a filmstrip of the category's topics (the topic was just
    // marked read above, so it shows read in the strip).
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let sort = resolve_sort(&state, None, user_context.as_ref()).await;
    let mut focus_ctx = context! { rail => Vec::<minijinja::Value>::new() };
    if let Some(cat) = category.as_ref() {
        let counts = super::focus::topic_counts(&state).await?;
        let (up, rail) = super::focus::category_rail(&tree, &vis, &counts, cat, sort);
        let list = super::focus::category_topics(&state, &tree, &vis, cat.id, sort).await?;
        let tiles = super::focus::decorate(&state, &tree, list, user_context.as_ref().map(|c| c.user.id)).await?;
        let position = tiles.iter().position(|t| t.row.id == topic.id).map(|i| {
            context! {
                index => i + 1,
                count => tiles.len(),
                prev => i.checked_sub(1).map(|j| tiles[j].row.id),
                next => tiles.get(i + 1).map(|t| t.row.id),
            }
        });
        let ancestors: Vec<minijinja::Value> = tree
            .ancestors(cat.id)
            .into_iter()
            .chain(std::iter::once(cat.id))
            .filter_map(|id| {
                tree.get(id).map(|c| context! { name => c.name.clone(), href => super::focus::focus_url(&c.slug, sort) })
            })
            .collect();
        focus_ctx = context! {
            up => up,
            rail => rail,
            rail_label => "Other categories",
            strip => super::focus::strip(&tiles, topic.id),
            position => position,
            ancestors => ancestors,
            // Escape: back to the category in focus.
            close_href => super::focus::focus_url(&cat.slug, sort),
            watching => match user_context.as_ref() {
                Some(c) => category_watches::Entity::find()
                    .filter(category_watches::Column::UserId.eq(c.user.id))
                    .filter(category_watches::Column::CategoryId.eq(cat.id))
                    .one(state.db.as_ref())
                    .await
                    .map_err(ise("query watch"))?
                    .is_some(),
                None => false,
            },
        };
    }
    let page = render(&state, "forum/topic_focus.html", context! { ..focus_ctx, ..ctx })?;
    Ok(view.respond(page))
}

#[derive(Debug, Default, Deserialize)]
pub struct TopicQuery {
    /// `classic` / `focus` override (see `focus::resolve_view`).
    pub view: Option<String>,
}


/// A topic's posts with their authors, in order.
pub(crate) async fn load_posts(
    state: &AppState,
    topic_id: Uuid,
) -> Result<Vec<(posts::Model, Option<users::Model>)>, StatusCode> {
    posts::Entity::find()
        .filter(posts::Column::TopicId.eq(topic_id))
        .order_by_asc(posts::Column::PostNumber)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load posts"))
}

/// Display rows for a topic's posts: bookmarks, reactions, and what the
/// viewer may do with each one (`caps`, from [`crate::actions::topic_caps`],
/// plus the per-post rules: edit, flag, moderation). Used by the topic page,
/// the Focus reader and the API.
pub(crate) async fn build_post_rows(
    state: &AppState,
    loaded: Vec<(posts::Model, Option<users::Model>)>,
    viewer: Option<&users::Model>,
    topic: &topics::Model,
    caps: &crate::actions::TopicCaps,
) -> Result<Vec<PostRow>, StatusCode> {
    let uid = viewer.map(|u| u.id);
    let is_staff = viewer.is_some_and(|u| u.is_staff);
    let links = crate::links::Links::from_config(&state.config);
    let post_ids: Vec<Uuid> = loaded.iter().map(|(p, _)| p.id).collect();
    // Which of these posts the current user has bookmarked, and flagged.
    let (bookmarked_ids, flagged_ids): (std::collections::HashSet<Uuid>, std::collections::HashSet<Uuid>) =
        match uid {
            Some(uid) if !post_ids.is_empty() => (
                bookmarks::Entity::find()
                    .filter(bookmarks::Column::UserId.eq(uid))
                    .filter(bookmarks::Column::PostId.is_in(post_ids.iter().copied()))
                    .all(state.db.as_ref())
                    .await
                    .map_err(ise("load bookmarks"))?
                    .into_iter()
                    .map(|b| b.post_id)
                    .collect(),
                post_flags::Entity::find()
                    .filter(post_flags::Column::UserId.eq(uid))
                    .filter(post_flags::Column::PostId.is_in(post_ids.iter().copied()))
                    .all(state.db.as_ref())
                    .await
                    .map_err(ise("load flags"))?
                    .into_iter()
                    .map(|f| f.post_id)
                    .collect(),
            ),
            _ => Default::default(),
        };
    // Staff see how many flags wait on each post (shadowbanned flaggers'
    // excluded, as in the queue).
    let mut pending: std::collections::HashMap<Uuid, u64> = std::collections::HashMap::new();
    if is_staff && !post_ids.is_empty() {
        let rows: Vec<Uuid> = post_flags::Entity::find()
            .select_only()
            .column(post_flags::Column::PostId)
            .filter(post_flags::Column::PostId.is_in(post_ids.iter().copied()))
            .filter(post_flags::Column::ResolvedAt.is_null())
            .inner_join(users::Entity)
            .filter(users::Column::FlagsIgnoredAt.is_null())
            .into_tuple()
            .all(state.db.as_ref())
            .await
            .map_err(ise("count flags"))?;
        for p in rows {
            *pending.entry(p).or_default() += 1;
        }
    }

    // Reaction bars for all posts in one shot: only the types the
    // category offers (none when its reactions are off; the rows stay).
    let rtypes = crate::actions::offered_types(
        active_reaction_types(state.db.as_ref()).await.map_err(ise("load reaction types"))?,
        &caps.reactions,
    );
    let mut reaction_map = reaction_views_for_posts(state.db.as_ref(), &rtypes, &post_ids, uid)
        .await
        .map_err(ise("load reactions"))?;

    let mut rows = Vec::with_capacity(loaded.len());
    for (p, u) in loaded {
        let deleted = p.deleted_at.is_some();
        let own = uid == Some(p.user_id);
        let can_edit = viewer.is_some_and(|v| crate::actions::edit_block(state, v, &p, topic).is_none());
        let can_restore = deleted && is_staff;
        let deleted_by = if deleted { username_of(state, p.deleted_by_id).await } else { None };
        let moderated_by = if p.moderated_at.is_some() { username_of(state, p.moderated_by_id).await } else { None };
        let hidden = p.hidden_at.is_some() && !deleted;
        let show_hidden = is_staff || own;
        rows.push(PostRow {
            id: p.id,
            post_number: p.post_number,
            cooked: if deleted || (hidden && !show_hidden) { String::new() } else { links.display(&p.cooked, false) },
            created_at: rel(p.created_at),
            created_at_abs: abs(p.created_at),
            author: author_name(&u),
            author_id: p.user_id,
            author_has_avatar: u.as_ref().is_some_and(|u| u.avatar_content_type.is_some()),
            edited: p.edit_count > 0,
            deleted,
            deleted_by,
            can_edit,
            can_restore,
            bookmarked: bookmarked_ids.contains(&p.id),
            reactions: reaction_map.remove(&p.id).unwrap_or_default(),
            moderated: p.moderated_at.is_some(),
            moderated_by,
            hidden,
            show_hidden,
            can_react: caps.can_react && !deleted && (!hidden || is_staff),
            can_bookmark: caps.can_bookmark && !deleted,
            can_flag: caps.can_flag && !deleted && !own && !flagged_ids.contains(&p.id),
            flagged: flagged_ids.contains(&p.id),
            can_moderate: is_staff && !deleted,
            pending_flags: pending.get(&p.id).copied().unwrap_or(0),
            moderated_at: p.moderated_at,
            created: p.created_at,
            edited_at: p.edited_at,
        });
    }

    Ok(rows)
}

/// Count a view (at most once per viewer per [`VIEW_WINDOW`], keyed by user
/// id when signed in, else best-effort client IP) and, for a signed-in
/// viewer, remember they've read up to the last post. The topic page and the
/// visual-mode reader both call this, so they count the same way.
pub(crate) async fn record_topic_view(
    state: &AppState,
    topic: &topics::Model,
    user_id: Option<Uuid>,
    headers: &HeaderMap,
) {
    let viewer = user_id
        .map(|uid| format!("u:{uid}"))
        .unwrap_or_else(|| format!("ip:{}", client_ip(headers)));
    let should_bump = {
        let mut cache = state.view_throttle.lock().unwrap();
        let now = Instant::now();
        let key = (topic.id, viewer);
        let bump = cache
            .get(&key)
            .map(|&last| now.duration_since(last) >= VIEW_WINDOW)
            .unwrap_or(true);
        if bump {
            cache.insert(key, now);
            // Opportunistic prune so the map can't grow unbounded.
            if cache.len() > 50_000 {
                cache.retain(|_, &mut last| now.duration_since(last) < VIEW_WINDOW);
            }
        }
        bump
    };
    if should_bump {
        let mut t: topics::ActiveModel = topic.clone().into();
        t.views = Set(topic.views + 1);
        let _ = t.update(state.db.as_ref()).await;
    }
    if let Some(uid) = user_id {
        let row = topic_reads::ActiveModel {
            user_id: Set(uid),
            topic_id: Set(topic.id),
            last_read_post_number: Set(topic.posts_count),
            updated_at: Set(Utc::now().into()),
        };
        let res = topic_reads::Entity::insert(row)
            .on_conflict(
                sea_orm::sea_query::OnConflict::columns([topic_reads::Column::UserId, topic_reads::Column::TopicId])
                    .update_columns([topic_reads::Column::LastReadPostNumber, topic_reads::Column::UpdatedAt])
                    .to_owned(),
            )
            .exec(state.db.as_ref())
            .await;
        if let Err(e) = res {
            error!(error = %e, "record topic read failed");
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct NewTopicForm {
    pub title: String,
    pub body: String,
    /// Comma-separated free-form tags (optional).
    pub tags: Option<String>,
}

/// Render the "new topic" form (auth required).
pub async fn new_topic_form(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    user_context: UserContext,
) -> Result<Html<String>, StatusCode> {
    super::require_verified(&state, &user_context.user)?;
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    {
        let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
        if !tree.can_view(category.id, viewer_user(&user_context)) {
            return Err(StatusCode::NOT_FOUND);
        }
    }
    if let (false, Some(b)) = crate::actions::create_caps(&state, Some(&user_context.user), &category) {
        return Err(crate::actions::ActionError::from(b).into());
    }

    let may_create_tags =
        crate::trust::can_create_tags(&user_context.user, state.config.min_trust_to_create_tag);
    render(&state, "forum/new_topic.html", context! {
        title => "New topic",
        app_name => state.config.app_name,
        user => user_context.user,
        category => category,
        may_create_tags => may_create_tags,
        min_trust => state.config.min_trust_to_create_tag,
    })
}

/// Create a topic and its opening post (auth required). The rules and the
/// follow-on work live in [`crate::actions::create_topic`], shared with the API.
pub async fn create_topic(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    ip: crate::client_ip::ClientIp,
    user_context: UserContext,
    Form(form): Form<NewTopicForm>,
) -> Result<Redirect, StatusCode> {
    let topic = crate::actions::create_topic(
        &state,
        &user_context.user,
        &slug,
        &form.title,
        &form.body,
        form.tags.as_deref().unwrap_or(""),
    )
    .await?;
    crate::ips::record(state.db.as_ref(), user_context.user.id, ip.0, crate::ips::Seen::Post).await;
    Ok(Redirect::to(&format!("/t/{}", topic.id)))
}

#[derive(Debug, Deserialize)]
pub struct ReplyForm {
    pub body: String,
}

/// Add a reply to a topic (auth required). Returns the rendered post fragment
/// for htmx, or redirects back to the topic for a plain form submit.
pub async fn create_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    ip: crate::client_ip::ClientIp,
    user_context: UserContext,
    Form(form): Form<ReplyForm>,
) -> Result<axum::response::Response, StatusCode> {
    let post = crate::actions::reply(&state, &user_context.user, id, &form.body).await?;
    crate::ips::record(state.db.as_ref(), user_context.user.id, ip.0, crate::ips::Seen::Post).await;
    let topic_id = post.topic_id;

    if is_htmx {
        let (topic, tree) = crate::actions::visible_topic(&state, viewer_user(&user_context), topic_id).await?;
        let caps = crate::actions::topic_caps(&state, Some(&user_context.user), tree.get(topic.category_id), &topic);
        let row = build_post_rows(&state, vec![(post, Some(user_context.user.clone()))], Some(&user_context.user), &topic, &caps)
            .await?
            .pop()
            .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
        let html = render(&state, "forum/_post.html", context! {
            post => row,
            user => user_context.user.clone(),
            flag_reasons => crate::policy::FLAG_REASONS,
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/t/{topic_id}")).into_response())
    }
}

#[derive(Debug, Deserialize)]
pub struct TopicTagsForm {
    /// Comma-separated tag names; replaces the topic's current tags.
    #[serde(default)]
    pub tags: String,
}

/// Replace a topic's tags (topic author or staff). Same rules as at creation:
/// up to 5, slug-deduplicated, and minting brand-new tags needs the trust gate
/// (existing tags can always be applied). htmx gets the re-rendered tag bar;
/// plain form posts redirect back to the topic.
pub async fn update_topic_tags(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    user_context: UserContext,
    Form(form): Form<TopicTagsForm>,
) -> Result<axum::response::Response, StatusCode> {
    let tag_chips = crate::actions::set_topic_tags(&state, &user_context.user, id, &form.tags).await?;

    if is_htmx {
        let topic = topics::Entity::find_by_id(id)
            .one(state.db.as_ref())
            .await
            .map_err(ise("reload topic"))?
            .ok_or(StatusCode::NOT_FOUND)?;
        let may_create_tags =
            crate::trust::can_create_tags(&user_context.user, state.config.min_trust_to_create_tag);
        let html = render(&state, "forum/_topic_tags.html", context! {
            topic => topic,
            tags => tag_chips,
            can_edit_tags => true,
            may_create_tags => may_create_tags,
            min_trust => state.config.min_trust_to_create_tag,
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/t/{id}")).into_response())
    }
}

/// Soft-delete a topic (author or staff). The row stays so `/t/{id}` keeps
/// resolving; it just drops out of listings and shows a tombstone.
pub async fn delete_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    let topic = crate::moderation::delete_topic(&state, &user_context.user, id).await?;
    // Send them back to the category listing.
    let slug = categories::Entity::find_by_id(topic.category_id)
        .one(state.db.as_ref())
        .await
        .ok()
        .flatten()
        .map(|c| c.slug)
        .unwrap_or_default();
    Ok(Redirect::to(&format!("/c/{slug}")))
}

/// Restore a soft-deleted topic — staff only.
pub async fn restore_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    crate::moderation::restore_topic(&state, crate::moderation::Actor::web(&user_context.user), id).await?;
    Ok(Redirect::to(&format!("/t/{id}")))
}

#[derive(Debug, Deserialize)]
pub struct LockForm {
    pub reason: Option<String>,
}

/// Lock a topic (staff), with an optional reason.
pub async fn lock_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
    Form(form): Form<LockForm>,
) -> Result<Redirect, StatusCode> {
    crate::moderation::set_locked(&state, crate::moderation::Actor::web(&user_context.user), id, true, form.reason.as_deref())
        .await?;
    Ok(Redirect::to(&format!("/t/{id}")))
}

/// Unlock a topic (staff).
pub async fn unlock_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    crate::moderation::set_locked(&state, crate::moderation::Actor::web(&user_context.user), id, false, None).await?;
    Ok(Redirect::to(&format!("/t/{id}")))
}

/// Pin a topic (staff).
pub async fn pin_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    crate::moderation::set_pinned(&state, crate::moderation::Actor::web(&user_context.user), id, true).await?;
    Ok(Redirect::to(&format!("/t/{id}")))
}

/// Unpin a topic (staff).
pub async fn unpin_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    crate::moderation::set_pinned(&state, crate::moderation::Actor::web(&user_context.user), id, false).await?;
    Ok(Redirect::to(&format!("/t/{id}")))
}

/// Render a template, mapping load/render errors to 500.
fn render(
    state: &AppState,
    name: &str,
    ctx: minijinja::Value,
) -> Result<Html<String>, StatusCode> {
    let template = state
        .env
        .get_template(name)
        .map_err(|e| {
            error!(error = %e, template = name, "load template failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
    let rendered = template.render(ctx).map_err(|e| {
        error!(error = %e, template = name, "render template failed");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    Ok(Html(rendered))
}