11.6 KiB · text History 01d6190
use axum::{
    extract::{Form, Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect, Response},
};
use axum_htmx::HxRequest;
use chrono::Utc;
use minijinja::context;
use sea_orm::{DatabaseBackend, FromQueryResult, Statement};
use sea_orm::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::error;
use uuid::Uuid;

use crate::entities::{post_reactions, posts, reaction_types, topics, users};
use crate::handlers::focus::{self, ListPage};
use crate::middleware::UserContext;
use crate::timeutil::{abs, rel};
use crate::AppState;

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

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))
}

/// One reaction option as shown under a post: its emoji, current count, and
/// whether the viewing user picked it.
#[derive(Serialize, Clone)]
pub struct ReactionView {
    pub key: String,
    pub emoji: String,
    pub count: i64,
    pub reacted: bool,
}

/// Active reaction types in display order.
pub async fn active_reaction_types(
    db: &DatabaseConnection,
) -> Result<Vec<reaction_types::Model>, DbErr> {
    reaction_types::Entity::find()
        .filter(reaction_types::Column::IsActive.eq(true))
        .order_by_asc(reaction_types::Column::Position)
        .order_by_asc(reaction_types::Column::Key)
        .all(db)
        .await
}

/// Build the reaction views for many posts at once (used by the topic page).
pub async fn reaction_views_for_posts(
    db: &DatabaseConnection,
    types: &[reaction_types::Model],
    post_ids: &[Uuid],
    current_user: Option<Uuid>,
) -> Result<HashMap<Uuid, Vec<ReactionView>>, DbErr> {
    let mut counts: HashMap<(Uuid, Uuid), i64> = HashMap::new();
    let mut mine: HashMap<Uuid, Uuid> = HashMap::new();
    if !post_ids.is_empty() {
        let rows = post_reactions::Entity::find()
            .filter(post_reactions::Column::PostId.is_in(post_ids.iter().copied()))
            .all(db)
            .await?;
        for r in rows {
            *counts.entry((r.post_id, r.reaction_id)).or_default() += 1;
            if Some(r.user_id) == current_user {
                mine.insert(r.post_id, r.reaction_id);
            }
        }
    }
    Ok(post_ids
        .iter()
        .map(|pid| (*pid, build_views(types, &counts, &mine, *pid)))
        .collect())
}

fn build_views(
    types: &[reaction_types::Model],
    counts: &HashMap<(Uuid, Uuid), i64>,
    mine: &HashMap<Uuid, Uuid>,
    post_id: Uuid,
) -> Vec<ReactionView> {
    types
        .iter()
        .map(|t| ReactionView {
            key: t.key.clone(),
            emoji: t.emoji.clone(),
            count: counts.get(&(post_id, t.id)).copied().unwrap_or(0),
            reacted: mine.get(&post_id) == Some(&t.id),
        })
        .collect()
}

/// Toggle the current user's reaction on a post: clicking a new reaction sets
/// it, clicking the same one removes it, clicking a different one switches.
pub async fn toggle_react(
    State(state): State<AppState>,
    Path((id, key)): Path<(Uuid, String)>,
    HxRequest(is_htmx): HxRequest,
    user: UserContext,
) -> Result<Response, StatusCode> {
    // Clicking the reaction you hold clears it; any other sets it.
    let held = crate::actions::current_reaction(&state, user.user.id, id).await?;
    let desired = (held.as_deref() != Some(key.as_str())).then_some(key.as_str());
    let views = crate::actions::set_reaction(&state, &user.user, id, desired).await?;
    let post = posts::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("reload post"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    if is_htmx {
        let html = render(&state, "forum/_reactions.html", context! {
            post => context! { id => id, reactions => views },
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/t/{}#post-{}", post.topic_id, post.post_number)).into_response())
    }
}

#[derive(Debug, FromQueryResult)]
struct ReactedAgg {
    topic_id: Uuid,
    cnt: i64,
    last: chrono::DateTime<chrono::FixedOffset>,
}

#[derive(Serialize)]
struct ReactedRow {
    topic_id: Uuid,
    title: String,
    count: i64,
    last: String,
    last_abs: String,
}

#[derive(Debug, Default, Deserialize)]
pub struct ReactedQuery {
    pub view: Option<String>,
    pub topic: Option<Uuid>,
}

/// View of all topics that have reactions, most recently reacted first.
pub async fn show_reactions(
    State(state): State<AppState>,
    Query(q): Query<ReactedQuery>,
    headers: HeaderMap,
    user: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let view = focus::view_for(&state, q.view.as_deref(), user.as_ref(), &headers);
    let aggs = ReactedAgg::find_by_statement(Statement::from_string(
        DatabaseBackend::Postgres,
        "SELECT p.topic_id AS topic_id, count(*)::bigint AS cnt, max(pr.created_at) AS last \
         FROM post_reactions pr \
         JOIN posts p ON p.id = pr.post_id \
         JOIN topics t ON t.id = p.topic_id \
         JOIN categories c ON c.id = t.category_id \
         JOIN reaction_types rt ON rt.id = pr.reaction_id \
         WHERE p.deleted_at IS NULL AND t.deleted_at IS NULL \
           AND c.reactions_enabled \
           AND (c.reaction_keys IS NULL OR rt.key = ANY(string_to_array(c.reaction_keys, ','))) \
         GROUP BY p.topic_id ORDER BY last DESC LIMIT 50",
    ))
    .all(state.db.as_ref())
    .await
    .map_err(ise("aggregate reactions"))?;

    // Only surface topics in categories the viewer can read.
    let tree = crate::category_tree::CategoryTree::load(state.db.as_ref())
        .await
        .map_err(ise("load category tree"))?;
    let vis = tree.visible_category_ids(crate::handlers::forum::viewer_of(&user));
    let mut topic_map: HashMap<Uuid, (topics::Model, Option<users::Model>)> = if aggs.is_empty() {
        HashMap::new()
    } else {
        topics::Entity::find()
            .filter(topics::Column::Id.is_in(aggs.iter().map(|a| a.topic_id)))
            .find_also_related(users::Entity)
            .all(state.db.as_ref())
            .await
            .map_err(ise("load reacted topics"))?
            .into_iter()
            .filter(|(t, _)| vis.contains(&t.category_id))
            .map(|(t, u)| (t.id, (t, u)))
            .collect()
    };
    let aggs: Vec<ReactedAgg> = aggs.into_iter().filter(|a| topic_map.contains_key(&a.topic_id)).collect();

    if view.is_focus() {
        let mut notes: HashMap<Uuid, Vec<String>> = HashMap::new();
        let list: Vec<_> = aggs
            .iter()
            .filter_map(|a| {
                notes.insert(
                    a.topic_id,
                    vec![format!(
                        "{} reaction{} · last {}",
                        a.cnt,
                        if a.cnt == 1 { "" } else { "s" },
                        rel(a.last)
                    )],
                );
                topic_map.remove(&a.topic_id)
            })
            .collect();
        let (mut tiles, reader) =
            focus::tiles_and_reader(&state, &tree, list, user.as_ref(), &headers, q.topic).await?;
        for t in &mut tiles {
            t.notes = notes.remove(&t.row.id).unwrap_or_default();
        }
        let mut page = ListPage::new("reactions", "Reactions", "/reactions");
        page.heading_icon = "fa-face-smile";
        page.subheading = Some("Topics with reactions, most recently reacted first.".into());
        page.empty = "No reactions yet.".into();
        let html = page.render(&state, tiles, reader, user.as_ref(), &headers)?;
        return Ok(view.respond(html));
    }

    let rows: Vec<ReactedRow> = aggs
        .into_iter()
        .filter_map(|a| {
            topic_map.get(&a.topic_id).map(|(t, _)| ReactedRow {
                topic_id: a.topic_id,
                title: t.title.clone(),
                count: a.cnt,
                last: rel(a.last),
                last_abs: abs(a.last),
            })
        })
        .collect();

    let page = render(&state, "reactions.html", context! {
        title => "Reactions",
        app_name => state.config.app_name,
        user => user.map(|c| c.user),
        topics => rows,
    })?;
    Ok(view.respond(page))
}

// ----------------------------------------------------------------------------
// Admin: configure the reaction set
// ----------------------------------------------------------------------------

fn require_staff(u: &UserContext) -> Result<(), StatusCode> {
    if u.user.is_staff {
        Ok(())
    } else {
        Err(StatusCode::FORBIDDEN)
    }
}

pub async fn manage_reactions(
    State(state): State<AppState>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    require_staff(&user)?;
    let types = reaction_types::Entity::find()
        .order_by_asc(reaction_types::Column::Position)
        .order_by_asc(reaction_types::Column::Key)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load reaction types"))?;
    render(&state, "admin/reactions.html", context! {
        title => "Manage reactions",
        app_name => state.config.app_name,
        user => user.user,
        reactions => types,
    })
}

#[derive(Debug, Deserialize)]
pub struct ReactionForm {
    pub key: String,
    pub emoji: String,
    pub position: Option<i32>,
}

pub async fn create_reaction(
    State(state): State<AppState>,
    user: UserContext,
    Form(form): Form<ReactionForm>,
) -> Result<Redirect, StatusCode> {
    require_staff(&user)?;
    let key: String = form
        .key
        .trim()
        .to_lowercase()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
        .collect();
    let emoji = form.emoji.trim().to_string();
    if key.is_empty() || emoji.is_empty() {
        return Err(StatusCode::BAD_REQUEST);
    }
    reaction_types::ActiveModel {
        id: Set(Uuid::now_v7()),
        key: Set(key),
        emoji: Set(emoji),
        position: Set(form.position.unwrap_or(0)),
        is_active: Set(true),
        created_at: Set(Utc::now().into()),
    }
    .insert(state.db.as_ref())
    .await
    .map_err(ise("insert reaction type"))?;
    Ok(Redirect::to("/admin/reactions"))
}

pub async fn delete_reaction(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
) -> Result<Redirect, StatusCode> {
    require_staff(&user)?;
    reaction_types::Entity::delete_by_id(id)
        .exec(state.db.as_ref())
        .await
        .map_err(ise("delete reaction type"))?;
    Ok(Redirect::to("/admin/reactions"))
}

/// Enable/disable a reaction type. Disabling hides it from the post bar but
/// keeps existing reactions of that type (unlike delete).
pub async fn toggle_reaction_active(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
) -> Result<Redirect, StatusCode> {
    require_staff(&user)?;
    let rt = reaction_types::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load reaction type"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    let active = rt.is_active;
    let mut am: reaction_types::ActiveModel = rt.into();
    am.is_active = Set(!active);
    am.update(state.db.as_ref()).await.map_err(ise("toggle reaction active"))?;
    Ok(Redirect::to("/admin/reactions"))
}