10.7 KiB · text History 2264215
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{Html, IntoResponse, Redirect, Response},
};
use axum_htmx::HxRequest;
use chrono::Utc;
use minijinja::context;
use sea_orm::prelude::Expr;
use sea_orm::*;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use tracing::error;
use uuid::Uuid;

use crate::entities::{categories, category_watches, notifications, topics, users};
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))
}

/// Create "new_topic" notifications for everyone watching the topic's category
/// or any of its ancestors (so watching a parent catches subcategory topics),
/// except the author. Best-effort: callers log errors but don't fail the post.
pub async fn notify_new_topic(
    db: &DatabaseConnection,
    topic_id: Uuid,
    actor_id: Uuid,
    category_ids: &[Uuid],
) -> Result<(), DbErr> {
    if category_ids.is_empty() {
        return Ok(());
    }
    let watchers = category_watches::Entity::find()
        .filter(category_watches::Column::CategoryId.is_in(category_ids.iter().copied()))
        .all(db)
        .await?;

    let recipients: HashSet<Uuid> = watchers
        .into_iter()
        .map(|w| w.user_id)
        .filter(|uid| *uid != actor_id)
        .collect();
    if recipients.is_empty() {
        return Ok(());
    }

    let now = Utc::now();
    let rows: Vec<notifications::ActiveModel> = recipients
        .into_iter()
        .map(|uid| notifications::ActiveModel {
            id: Set(Uuid::now_v7()),
            user_id: Set(uid),
            kind: Set("new_topic".to_string()),
            actor_id: Set(Some(actor_id)),
            topic_id: Set(Some(topic_id)),
            post_id: Set(None),
            is_read: Set(false),
            created_at: Set(now.into()),
        })
        .collect();
    notifications::Entity::insert_many(rows).exec(db).await?;
    Ok(())
}

/// Notify a post's author that `actor` reacted, unless they're the same person
/// or the author opted out of reaction notifications.
pub async fn notify_reaction(
    db: &DatabaseConnection,
    post_author_id: Uuid,
    actor_id: Uuid,
    post_id: Uuid,
    topic_id: Uuid,
) -> Result<(), DbErr> {
    if post_author_id == actor_id {
        return Ok(());
    }
    let wants = users::Entity::find_by_id(post_author_id)
        .one(db)
        .await?
        .map(|u| u.reaction_notifications)
        .unwrap_or(false);
    if !wants {
        return Ok(());
    }
    notifications::ActiveModel {
        id: Set(Uuid::now_v7()),
        user_id: Set(post_author_id),
        kind: Set("reaction".to_string()),
        actor_id: Set(Some(actor_id)),
        topic_id: Set(Some(topic_id)),
        post_id: Set(Some(post_id)),
        is_read: Set(false),
        created_at: Set(Utc::now().into()),
    }
    .insert(db)
    .await?;
    Ok(())
}

/// Toggle watching a category for the current user.
pub async fn toggle_watch(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    HxRequest(is_htmx): HxRequest,
    user: UserContext,
) -> Result<Response, StatusCode> {
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category for watch"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let existing = category_watches::Entity::find()
        .filter(category_watches::Column::UserId.eq(user.user.id))
        .filter(category_watches::Column::CategoryId.eq(category.id))
        .one(state.db.as_ref())
        .await
        .map_err(ise("query watch"))?;

    let watching = match existing {
        Some(w) => {
            category_watches::Entity::delete_by_id(w.id)
                .exec(state.db.as_ref())
                .await
                .map_err(ise("delete watch"))?;
            false
        }
        None => {
            category_watches::ActiveModel {
                id: Set(Uuid::now_v7()),
                user_id: Set(user.user.id),
                category_id: Set(category.id),
                created_at: Set(Utc::now().into()),
            }
            .insert(state.db.as_ref())
            .await
            .map_err(ise("insert watch"))?;
            true
        }
    };

    if is_htmx {
        let html = render(&state, "forum/_watch_button.html", context! {
            slug => category.slug, watching => watching,
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/c/{}", category.slug)).into_response())
    }
}

/// htmx-loaded unread badge for the nav bell. Empty when anonymous or zero.
pub async fn unread_badge(
    State(state): State<AppState>,
    user: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
    let count = match &user {
        Some(u) => notifications::Entity::find()
            .filter(notifications::Column::UserId.eq(u.user.id))
            .filter(notifications::Column::IsRead.eq(false))
            .count(state.db.as_ref())
            .await
            .map_err(ise("count unread"))?,
        None => 0,
    };
    render(&state, "_notif_badge.html", context! { count => count })
}

#[derive(Serialize)]
struct NotifRow {
    id: Uuid,
    kind: String,
    topic_id: Option<Uuid>,
    post_id: Option<Uuid>,
    topic_title: String,
    actor: String,
    is_read: bool,
    created: String,
    created_abs: String,
}

/// Build a display row for a single notification (loads topic title + actor).
async fn one_notif_row(
    db: &DatabaseConnection,
    n: &notifications::Model,
) -> Result<NotifRow, DbErr> {
    let topic_title = match n.topic_id {
        Some(tid) => topics::Entity::find_by_id(tid)
            .one(db)
            .await?
            .map(|t| t.title)
            .unwrap_or_else(|| "(removed)".to_string()),
        None => String::new(),
    };
    let actor = match n.actor_id {
        Some(aid) => users::Entity::find_by_id(aid)
            .one(db)
            .await?
            .map(|u| u.username)
            .unwrap_or_else(|| "someone".to_string()),
        None => "someone".to_string(),
    };
    Ok(NotifRow {
        id: n.id,
        kind: n.kind.clone(),
        topic_id: n.topic_id,
        post_id: n.post_id,
        topic_title,
        actor,
        is_read: n.is_read,
        created: rel(n.created_at),
        created_abs: abs(n.created_at),
    })
}

/// The notifications page. Marks everything read after rendering this view.
pub async fn show_notifications(
    State(state): State<AppState>,
    user: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let Some(user) = user else {
        return Ok(Redirect::temporary("/login").into_response());
    };

    let notifs = notifications::Entity::find()
        .filter(notifications::Column::UserId.eq(user.user.id))
        .order_by_desc(notifications::Column::CreatedAt)
        .limit(50)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load notifications"))?;

    let topic_ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.topic_id).collect();
    let actor_ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.actor_id).collect();

    let topic_titles: HashMap<Uuid, String> = if topic_ids.is_empty() {
        HashMap::new()
    } else {
        topics::Entity::find()
            .filter(topics::Column::Id.is_in(topic_ids))
            .all(state.db.as_ref())
            .await
            .map_err(ise("load notif topics"))?
            .into_iter()
            .map(|t| (t.id, t.title))
            .collect()
    };
    let actor_names: HashMap<Uuid, String> = if actor_ids.is_empty() {
        HashMap::new()
    } else {
        users::Entity::find()
            .filter(users::Column::Id.is_in(actor_ids))
            .all(state.db.as_ref())
            .await
            .map_err(ise("load notif actors"))?
            .into_iter()
            .map(|u| (u.id, u.username))
            .collect()
    };

    let rows: Vec<NotifRow> = notifs
        .iter()
        .map(|n| NotifRow {
            id: n.id,
            kind: n.kind.clone(),
            topic_id: n.topic_id,
            post_id: n.post_id,
            topic_title: n
                .topic_id
                .and_then(|id| topic_titles.get(&id).cloned())
                .unwrap_or_else(|| "(removed)".to_string()),
            actor: n
                .actor_id
                .and_then(|id| actor_names.get(&id).cloned())
                .unwrap_or_else(|| "someone".to_string()),
            is_read: n.is_read,
            created: rel(n.created_at),
            created_abs: abs(n.created_at),
        })
        .collect();

    let html = render(&state, "notifications.html", context! {
        title => "Notifications",
        app_name => state.config.app_name,
        user => user.user,
        notifications => rows,
    })?;
    Ok(html.into_response())
}

/// Mark a single notification read; returns the updated item (htmx).
pub async fn mark_read(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    let notif = notifications::Entity::find_by_id(id)
        .filter(notifications::Column::UserId.eq(user.user.id))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load notification"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let notif = if notif.is_read {
        notif
    } else {
        let mut am: notifications::ActiveModel = notif.into();
        am.is_read = Set(true);
        am.update(state.db.as_ref()).await.map_err(ise("mark read"))?
    };

    let row = one_notif_row(state.db.as_ref(), &notif)
        .await
        .map_err(ise("build notif row"))?;
    render(&state, "_notif_item.html", context! { n => row })
}

/// Mark all of the current user's notifications read.
pub async fn mark_all_read(
    State(state): State<AppState>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    notifications::Entity::update_many()
        .col_expr(notifications::Column::IsRead, Expr::value(true))
        .filter(notifications::Column::UserId.eq(user.user.id))
        .filter(notifications::Column::IsRead.eq(false))
        .exec(state.db.as_ref())
        .await
        .map_err(ise("mark all read"))?;
    Ok(Redirect::to("/notifications"))
}