use axum::{
extract::{Form, Path, State},
http::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};
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())
}
/// Reaction views for a single post.
async fn reaction_views_for_post(
db: &DatabaseConnection,
types: &[reaction_types::Model],
post_id: Uuid,
current_user: Option<Uuid>,
) -> Result<Vec<ReactionView>, DbErr> {
let map = reaction_views_for_posts(db, types, &[post_id], current_user).await?;
Ok(map.into_values().next().unwrap_or_default())
}
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> {
let post = posts::Entity::find_by_id(id)
.one(state.db.as_ref())
.await
.map_err(ise("load post for react"))?
.ok_or(StatusCode::NOT_FOUND)?;
let rtype = reaction_types::Entity::find()
.filter(reaction_types::Column::Key.eq(&key))
.filter(reaction_types::Column::IsActive.eq(true))
.one(state.db.as_ref())
.await
.map_err(ise("load reaction type"))?
.ok_or(StatusCode::NOT_FOUND)?;
let existing = post_reactions::Entity::find()
.filter(post_reactions::Column::PostId.eq(id))
.filter(post_reactions::Column::UserId.eq(user.user.id))
.one(state.db.as_ref())
.await
.map_err(ise("query reaction"))?;
let mut newly_reacted = false;
match existing {
Some(r) if r.reaction_id == rtype.id => {
post_reactions::Entity::delete_by_id(r.id)
.exec(state.db.as_ref())
.await
.map_err(ise("remove reaction"))?;
}
Some(r) => {
let mut am: post_reactions::ActiveModel = r.into();
am.reaction_id = Set(rtype.id);
am.created_at = Set(Utc::now().into());
am.update(state.db.as_ref()).await.map_err(ise("change reaction"))?;
}
None => {
post_reactions::ActiveModel {
id: Set(Uuid::now_v7()),
post_id: Set(id),
user_id: Set(user.user.id),
reaction_id: Set(rtype.id),
created_at: Set(Utc::now().into()),
}
.insert(state.db.as_ref())
.await
.map_err(ise("add reaction"))?;
newly_reacted = true;
}
}
// Notify the post author on a brand-new reaction (best-effort).
if newly_reacted {
if let Err(e) = crate::handlers::notifications::notify_reaction(
state.db.as_ref(),
post.user_id,
user.user.id,
post.id,
post.topic_id,
)
.await
{
error!(error = %e, "notify reaction failed");
}
}
let types = active_reaction_types(state.db.as_ref())
.await
.map_err(ise("load reaction types"))?;
let views = reaction_views_for_post(state.db.as_ref(), &types, id, Some(user.user.id))
.await
.map_err(ise("build reaction views"))?;
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,
}
/// View of all topics that have reactions, most recently reacted first.
pub async fn show_reactions(
State(state): State<AppState>,
user: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
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 \
WHERE p.deleted_at IS NULL AND t.deleted_at IS NULL \
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 titles: HashMap<Uuid, String> = if aggs.is_empty() {
HashMap::new()
} else {
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));
topics::Entity::find()
.filter(topics::Column::Id.is_in(aggs.iter().map(|a| a.topic_id)))
.all(state.db.as_ref())
.await
.map_err(ise("load reacted topics"))?
.into_iter()
.filter(|t| vis.contains(&t.category_id))
.map(|t| (t.id, t.title))
.collect()
};
let rows: Vec<ReactedRow> = aggs
.into_iter()
.filter_map(|a| {
titles.get(&a.topic_id).map(|title| ReactedRow {
topic_id: a.topic_id,
title: title.clone(),
count: a.cnt,
last: rel(a.last),
last_abs: abs(a.last),
})
})
.collect();
render(&state, "reactions.html", context! {
title => "Reactions",
app_name => state.config.app_name,
user => user.map(|c| c.user),
topics => rows,
})
}
// ----------------------------------------------------------------------------
// 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"))
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
11.9 KiB · text
History
2264215