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

use crate::entities::{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 viewer = crate::actions::viewer(&user.user);
    let (category, _) = crate::actions::visible_category(&state, viewer, &slug).await?;
    let held = crate::actions::is_watching(&state, user.user.id, category.id).await?;
    let (category, watching) = crate::actions::set_watch(&state, &user.user, &slug, !held).await?;

    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> {
    // The same notifications the page lists (and the API counts).
    let count = match &user {
        Some(u) => visible_notifications(&state, u, 1000).await?.iter().filter(|n| !n.is_read).count(),
        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 user's latest `limit` notifications, minus those about topics in
/// categories they can no longer read (trust lowered, category restricted):
/// their titles would leak. Reaction notifications from a category whose
/// reactions are now off are left out too (they come back if it's turned
/// on again). The web page and `/api/v1/notifications` both
/// list through this.
pub(crate) async fn visible_notifications(
    state: &AppState,
    user: &UserContext,
    limit: u64,
) -> Result<Vec<notifications::Model>, StatusCode> {
    let notifs = notifications::Entity::find()
        .filter(notifications::Column::UserId.eq(user.user.id))
        .order_by_desc(notifications::Column::CreatedAt)
        .limit(limit)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load notifications"))?;

    let notifs = {
        let ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.topic_id).collect();
        let mut hidden_reactions: HashSet<Uuid> = HashSet::new();
        let hidden: HashSet<Uuid> = if ids.is_empty() {
            HashSet::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(&Some(user.clone())));
            let topics = topics::Entity::find()
                .filter(topics::Column::Id.is_in(ids))
                .all(state.db.as_ref())
                .await
                .map_err(ise("load notif topic categories"))?;
            hidden_reactions = topics
                .iter()
                .filter(|t| tree.get(t.category_id).is_some_and(|c| !c.reactions_enabled))
                .map(|t| t.id)
                .collect();
            topics.into_iter().filter(|t| !vis.contains(&t.category_id)).map(|t| t.id).collect()
        };
        notifs
            .into_iter()
            .filter(|n| n.topic_id.is_none_or(|t| !hidden.contains(&t)))
            .filter(|n| !(n.kind == "reaction" && n.topic_id.is_some_and(|t| hidden_reactions.contains(&t))))
            .collect::<Vec<_>>()
    };

    Ok(notifs)
}

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

/// The notifications page (the 50 newest). In Focus, grouped by topic: one
/// tile per topic the user can still see, newest first, its notifications as
/// the tile's lines; the rest (no topic, or one now hidden) stay a list.
pub async fn show_notifications(
    State(state): State<AppState>,
    Query(q): Query<NotificationsQuery>,
    headers: HeaderMap,
    user: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let Some(user) = user else {
        return Ok(Redirect::temporary("/login").into_response());
    };
    let view = crate::handlers::focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);

    let notifs = visible_notifications(&state, &user, 50).await?;

    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();

    if view.is_focus() {
        use crate::handlers::focus::{self, ListPage};
        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(&Some(user.clone())));
        let ids: Vec<Uuid> = notifs.iter().filter_map(|n| n.topic_id).collect();
        let mut topic_map: HashMap<Uuid, (topics::Model, Option<users::Model>)> = if ids.is_empty() {
            HashMap::new()
        } else {
            topics::Entity::find()
                .filter(topics::Column::Id.is_in(ids))
                .filter(topics::Column::DeletedAt.is_null())
                .find_also_related(users::Entity)
                .all(state.db.as_ref())
                .await
                .map_err(ise("load notif topics"))?
                .into_iter()
                .filter(|(t, _)| vis.contains(&t.category_id))
                .map(|(t, u)| (t.id, (t, u)))
                .collect()
        };
        let mut order: Vec<Uuid> = Vec::new();
        let mut notes: HashMap<Uuid, Vec<String>> = HashMap::new();
        let mut others = Vec::new();
        for r in rows {
            match r.topic_id.filter(|id| topic_map.contains_key(id)) {
                Some(tid) => {
                    if !notes.contains_key(&tid) {
                        order.push(tid);
                    }
                    let what = match r.kind.as_str() {
                        "new_topic" => "posted this topic",
                        "reaction" => "reacted to your post",
                        other => other,
                    };
                    let dot = if r.is_read { "" } else { "● " };
                    notes.entry(tid).or_default().push(format!("{dot}{} {what} · {}", r.actor, r.created));
                }
                None => others.push(minijinja::Value::from_serialize(&r)),
            }
        }
        let list: Vec<_> = order.iter().filter_map(|id| topic_map.remove(id)).collect();
        let (mut tiles, reader) =
            focus::tiles_and_reader(&state, &tree, list, Some(&user), &headers, q.topic).await?;
        for t in &mut tiles {
            t.notes = notes.remove(&t.row.id).unwrap_or_default();
        }
        let mut page = ListPage::new("notifications", "Notifications", "/notifications");
        page.heading_icon = "fa-bell";
        page.empty = if others.is_empty() {
            "No notifications yet. Watch a category to get notified about new topics.".into()
        } else {
            String::new()
        };
        page.mark_all_read = !notes_empty(&tiles, &others);
        page.others = others;
        let html = page.render(&state, tiles, reader, Some(&user), &headers)?;
        return Ok(view.respond(html));
    }

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

/// 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 = crate::actions::mark_notification_read(&state, user.user.id, id).await?;

    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> {
    crate::actions::mark_all_notifications_read(&state, user.user.id).await?;
    Ok(Redirect::to("/notifications"))
}

fn notes_empty(tiles: &[crate::handlers::focus::TopicTile], others: &[minijinja::Value]) -> bool {
    tiles.is_empty() && others.is_empty()
}