19.5 KiB · text History 7e143f3
//! Writes shared by the web handlers and `/api/v1` (party-slut's
//! `src/actions.rs`): starting a topic, replying, tagging, reacting,
//! bookmarking, watching, and the profile's preferences and avatar.
//!
//! Each one checks what the web always checked — the category is visible to
//! this user (trust level, staff), the account may write (email
//! verification), the topic is open — and does the follow-on work (revision,
//! bump, notifications, trust recompute) in one place, so the app can't get a
//! rule the web doesn't, or miss one. The web handlers turn the result into
//! a redirect or an htmx fragment; the API into JSON.
use axum::http::StatusCode;
use chrono::Utc;
use sea_orm::*;
use tracing::error;
use uuid::Uuid;

use crate::category_tree::{CategoryTree, Viewer};
use crate::entities::{
    bookmarks, categories, category_watches, post_reactions, posts, reaction_types, topic_tags, topics, users,
};
use crate::handlers::focus::ViewMode;
use crate::handlers::forum::{apply_tags, tags_for_topic, TagChip, TopicSort};
use crate::handlers::reactions::{active_reaction_types, reaction_views_for_posts, ReactionView};
use crate::markdown;
use crate::AppState;

/// Why an action was refused.
#[derive(Debug)]
pub enum ActionError {
    /// Doesn't exist, or the user can't see it — deliberately one answer.
    NotFound,
    /// The account's email address isn't verified and the site requires it.
    Unverified,
    /// Visible, but not this user's to change (`code` names the rule).
    Forbidden { code: &'static str, message: &'static str },
    /// The input itself is wrong; the message says how, for a person.
    Invalid(String),
    Internal(String),
}

pub type ActionResult<T> = Result<T, ActionError>;

impl ActionError {
    pub fn status(&self) -> StatusCode {
        match self {
            Self::NotFound => StatusCode::NOT_FOUND,
            Self::Unverified | Self::Forbidden { .. } => StatusCode::FORBIDDEN,
            Self::Invalid(_) => StatusCode::BAD_REQUEST,
            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl From<DbErr> for ActionError {
    fn from(e: DbErr) -> Self {
        error!(error = %e, "action failed");
        Self::Internal(e.to_string())
    }
}

/// The shared listing helpers answer bare status codes; carry them across.
impl From<StatusCode> for ActionError {
    fn from(s: StatusCode) -> Self {
        match s {
            StatusCode::NOT_FOUND => Self::NotFound,
            StatusCode::FORBIDDEN => Self::Forbidden { code: "forbidden", message: "You can't do that." },
            StatusCode::BAD_REQUEST => Self::Invalid("That request couldn't be read.".into()),
            other => Self::Internal(other.to_string()),
        }
    }
}

/// What the web handlers return: the status code alone.
impl From<ActionError> for StatusCode {
    fn from(e: ActionError) -> Self {
        e.status()
    }
}

/// The read capability of a signed-in user.
pub fn viewer(user: &users::Model) -> Viewer {
    Viewer { level: Some(user.trust_level), staff: user.is_staff }
}

/// [`crate::handlers::may_write`] as an action error.
pub fn require_writer(state: &AppState, user: &users::Model) -> ActionResult<()> {
    if crate::handlers::may_write(state, user) {
        Ok(())
    } else {
        Err(ActionError::Unverified)
    }
}

/// A category by slug, if `viewer` may read it.
pub async fn visible_category(
    state: &AppState,
    viewer: Viewer,
    slug: &str,
) -> ActionResult<(categories::Model, CategoryTree)> {
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(slug))
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)?;
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    if !tree.can_view(category.id, viewer) {
        return Err(ActionError::NotFound);
    }
    Ok((category, tree))
}

/// A topic, if `viewer` may read its category. Deleted topics are included;
/// callers decide what a tombstone means for them.
pub async fn visible_topic(
    state: &AppState,
    viewer: Viewer,
    topic_id: Uuid,
) -> ActionResult<(topics::Model, CategoryTree)> {
    let topic = topics::Entity::find_by_id(topic_id)
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)?;
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    if !tree.can_view(topic.category_id, viewer) {
        return Err(ActionError::NotFound);
    }
    Ok((topic, tree))
}

/// A live post in a live topic `viewer` may read.
async fn visible_live_post(state: &AppState, viewer: Viewer, post_id: Uuid) -> ActionResult<posts::Model> {
    let post = posts::Entity::find_by_id(post_id)
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)?;
    let (topic, _) = visible_topic(state, viewer, post.topic_id).await?;
    if post.deleted_at.is_some() || topic.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    Ok(post)
}

/// Start a topic in `slug` with its opening post and tags (comma-separated,
/// up to five; minting new ones is trust-gated), and notify the watchers of
/// the category and its ancestors.
pub async fn create_topic(
    state: &AppState,
    user: &users::Model,
    slug: &str,
    title: &str,
    body: &str,
    tags: &str,
) -> ActionResult<topics::Model> {
    require_writer(state, user)?;
    let (title, body) = (title.trim(), body.trim());
    if title.is_empty() {
        return Err(ActionError::Invalid("A topic needs a title.".into()));
    }
    if body.is_empty() {
        return Err(ActionError::Invalid("Write something to start the topic with.".into()));
    }
    let (category, tree) = visible_category(state, viewer(user), slug).await?;

    let now = Utc::now();
    let topic = topics::ActiveModel {
        id: Set(Uuid::now_v7()),
        category_id: Set(category.id),
        user_id: Set(user.id),
        title: Set(title.to_string()),
        is_pinned: Set(false),
        is_closed: Set(false),
        views: Set(0),
        posts_count: Set(1),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        bumped_at: Set(now.into()),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    }
    .insert(state.db.as_ref())
    .await?;
    insert_post(state, user, topic.id, 1, body).await?;

    if !tags.trim().is_empty() {
        apply_tags(state, topic.id, tags, user).await?;
    }

    let mut watch_ids = tree.ancestors(category.id);
    watch_ids.push(category.id);
    if let Err(e) =
        crate::handlers::notifications::notify_new_topic(state.db.as_ref(), topic.id, user.id, &watch_ids).await
    {
        error!(error = %e, "notify watchers failed");
    }
    recompute_trust(state, user).await;
    Ok(topic)
}

/// Reply to a topic: the post, its first revision, the topic bump.
pub async fn reply(state: &AppState, user: &users::Model, topic_id: Uuid, body: &str) -> ActionResult<posts::Model> {
    require_writer(state, user)?;
    let body = body.trim();
    if body.is_empty() {
        return Err(ActionError::Invalid("A reply can't be empty.".into()));
    }
    let (topic, _) = visible_topic(state, viewer(user), topic_id).await?;
    if topic.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    if topic.is_closed {
        return Err(ActionError::Forbidden { code: "closed", message: "This topic is closed to new replies." });
    }
    let next_number = topic.posts_count + 1;
    let post = insert_post(state, user, topic.id, next_number, body).await?;

    let mut t: topics::ActiveModel = topic.into();
    t.posts_count = Set(next_number);
    t.bumped_at = Set(post.created_at);
    t.update(state.db.as_ref()).await?;
    recompute_trust(state, user).await;
    Ok(post)
}

async fn insert_post(
    state: &AppState,
    user: &users::Model,
    topic_id: Uuid,
    post_number: i32,
    body: &str,
) -> ActionResult<posts::Model> {
    let now = Utc::now();
    let cooked = markdown::render(body);
    let post = posts::ActiveModel {
        id: Set(Uuid::now_v7()),
        topic_id: Set(topic_id),
        user_id: Set(user.id),
        post_number: Set(post_number),
        raw: Set(body.to_string()),
        cooked: Set(cooked.clone()),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        edited_at: Set(None),
        edit_count: Set(0),
        last_editor_id: Set(None),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    }
    .insert(state.db.as_ref())
    .await?;
    crate::handlers::posts::record_revision(state.db.as_ref(), post.id, 1, user.id, body, &cooked, now.into())
        .await?;
    Ok(post)
}

async fn recompute_trust(state: &AppState, user: &users::Model) {
    if let Err(e) = crate::trust::recompute(state.db.as_ref(), user).await {
        error!(error = %e, "trust recompute failed");
    }
}

/// Whether `user` may change `topic`'s tags: its author or staff, on a live
/// topic, with a verified address.
pub fn can_edit_tags(state: &AppState, user: &users::Model, topic: &topics::Model) -> bool {
    topic.deleted_at.is_none() && (user.is_staff || user.id == topic.user_id) && crate::handlers::may_write(state, user)
}

/// Replace a topic's tags with `tags` (comma-separated). Same rules as at
/// creation. Returns the tags it ended up with.
pub async fn set_topic_tags(
    state: &AppState,
    user: &users::Model,
    topic_id: Uuid,
    tags: &str,
) -> ActionResult<Vec<TagChip>> {
    require_writer(state, user)?;
    let (topic, _) = visible_topic(state, viewer(user), topic_id).await?;
    if topic.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    if !(user.is_staff || user.id == topic.user_id) {
        return Err(ActionError::Forbidden {
            code: "not_author",
            message: "Only the topic's author or staff can change its tags.",
        });
    }
    // Drop the links, then apply the list. Tag rows stay (other topics may
    // use them; /tags lists zero counts).
    topic_tags::Entity::delete_many()
        .filter(topic_tags::Column::TopicId.eq(topic.id))
        .exec(state.db.as_ref())
        .await?;
    apply_tags(state, topic.id, tags, user).await?;
    let mut t: topics::ActiveModel = topic.clone().into();
    t.updated_at = Set(Utc::now().into());
    t.update(state.db.as_ref()).await?;
    Ok(tags_for_topic(state, topic.id).await?)
}

/// The key of `user`'s current reaction on a post, if any.
pub async fn current_reaction(state: &AppState, user_id: Uuid, post_id: Uuid) -> ActionResult<Option<String>> {
    let Some(r) = post_reactions::Entity::find()
        .filter(post_reactions::Column::PostId.eq(post_id))
        .filter(post_reactions::Column::UserId.eq(user_id))
        .one(state.db.as_ref())
        .await?
    else {
        return Ok(None);
    };
    Ok(reaction_types::Entity::find_by_id(r.reaction_id).one(state.db.as_ref()).await?.map(|t| t.key))
}

/// Set `user`'s reaction on a post to `key` (one per user per post; a new
/// key replaces the old one), or clear it with `None`. A brand-new reaction
/// notifies the post's author. Returns the post's reaction bar.
pub async fn set_reaction(
    state: &AppState,
    user: &users::Model,
    post_id: Uuid,
    key: Option<&str>,
) -> ActionResult<Vec<ReactionView>> {
    require_writer(state, user)?;
    let post = visible_live_post(state, viewer(user), post_id).await?;
    let existing = post_reactions::Entity::find()
        .filter(post_reactions::Column::PostId.eq(post.id))
        .filter(post_reactions::Column::UserId.eq(user.id))
        .one(state.db.as_ref())
        .await?;

    match key {
        None => {
            if let Some(r) = existing {
                post_reactions::Entity::delete_by_id(r.id).exec(state.db.as_ref()).await?;
            }
        }
        Some(key) => {
            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?
                .ok_or_else(|| ActionError::Invalid(format!("There is no “{key}” reaction.")))?;
            match existing {
                Some(r) if r.reaction_id == rtype.id => {}
                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?;
                }
                None => {
                    post_reactions::ActiveModel {
                        id: Set(Uuid::now_v7()),
                        post_id: Set(post.id),
                        user_id: Set(user.id),
                        reaction_id: Set(rtype.id),
                        created_at: Set(Utc::now().into()),
                    }
                    .insert(state.db.as_ref())
                    .await?;
                    if let Err(e) = crate::handlers::notifications::notify_reaction(
                        state.db.as_ref(),
                        post.user_id,
                        user.id,
                        post.id,
                        post.topic_id,
                    )
                    .await
                    {
                        error!(error = %e, "notify reaction failed");
                    }
                }
            }
        }
    }

    let types = active_reaction_types(state.db.as_ref()).await?;
    let mut views = reaction_views_for_posts(state.db.as_ref(), &types, &[post.id], Some(user.id)).await?;
    Ok(views.remove(&post.id).unwrap_or_default())
}

/// Bookmark a post, or remove the bookmark. Returns the new state.
pub async fn set_bookmark(state: &AppState, user: &users::Model, post_id: Uuid, on: bool) -> ActionResult<bool> {
    require_writer(state, user)?;
    let post = visible_live_post(state, viewer(user), post_id).await?;
    let existing = bookmarks::Entity::find()
        .filter(bookmarks::Column::UserId.eq(user.id))
        .filter(bookmarks::Column::PostId.eq(post.id))
        .one(state.db.as_ref())
        .await?;
    match (existing, on) {
        (Some(b), false) => {
            bookmarks::Entity::delete_by_id(b.id).exec(state.db.as_ref()).await?;
        }
        (None, true) => {
            bookmarks::ActiveModel {
                id: Set(Uuid::now_v7()),
                user_id: Set(user.id),
                post_id: Set(post.id),
                created_at: Set(Utc::now().into()),
            }
            .insert(state.db.as_ref())
            .await?;
        }
        _ => {}
    }
    Ok(on)
}

/// Whether `user` has bookmarked `post_id`.
pub async fn is_bookmarked(state: &AppState, user_id: Uuid, post_id: Uuid) -> ActionResult<bool> {
    Ok(bookmarks::Entity::find()
        .filter(bookmarks::Column::UserId.eq(user_id))
        .filter(bookmarks::Column::PostId.eq(post_id))
        .count(state.db.as_ref())
        .await?
        > 0)
}

/// Whether `user_id` watches `category_id`.
pub async fn is_watching(state: &AppState, user_id: Uuid, category_id: Uuid) -> ActionResult<bool> {
    Ok(category_watches::Entity::find()
        .filter(category_watches::Column::UserId.eq(user_id))
        .filter(category_watches::Column::CategoryId.eq(category_id))
        .count(state.db.as_ref())
        .await?
        > 0)
}

/// Watch a category (new topics in it and below notify you), or stop.
/// Returns the category and the new state.
pub async fn set_watch(
    state: &AppState,
    user: &users::Model,
    slug: &str,
    on: bool,
) -> ActionResult<(categories::Model, bool)> {
    let (category, _) = visible_category(state, viewer(user), slug).await?;
    let existing = category_watches::Entity::find()
        .filter(category_watches::Column::UserId.eq(user.id))
        .filter(category_watches::Column::CategoryId.eq(category.id))
        .one(state.db.as_ref())
        .await?;
    match (existing, on) {
        (Some(w), false) => {
            category_watches::Entity::delete_by_id(w.id).exec(state.db.as_ref()).await?;
        }
        (None, true) => {
            category_watches::ActiveModel {
                id: Set(Uuid::now_v7()),
                user_id: Set(user.id),
                category_id: Set(category.id),
                created_at: Set(Utc::now().into()),
            }
            .insert(state.db.as_ref())
            .await?;
        }
        _ => {}
    }
    Ok((category, on))
}

/// The profile's preferences; `None` leaves a field as it is.
#[derive(Debug, Default)]
pub struct Preferences {
    pub reaction_notifications: Option<bool>,
    pub layout: Option<ViewMode>,
    pub sort: Option<TopicSort>,
}

pub async fn update_preferences(
    state: &AppState,
    user: &users::Model,
    prefs: Preferences,
) -> ActionResult<users::Model> {
    let mut am: users::ActiveModel = user.clone().into();
    if let Some(on) = prefs.reaction_notifications {
        am.reaction_notifications = Set(on);
    }
    if let Some(mode) = prefs.layout {
        am.preferred_view = Set(mode.as_str().to_string());
    }
    if let Some(sort) = prefs.sort {
        am.preferred_sort = Set(sort.as_str().to_string());
    }
    am.updated_at = Set(Utc::now().into());
    Ok(am.update(state.db.as_ref()).await?)
}

/// Image types an avatar may be.
pub const AVATAR_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
/// Largest avatar accepted.
pub const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;

/// Replace `user`'s avatar.
pub async fn set_avatar(
    state: &AppState,
    user: &users::Model,
    content_type: Option<&str>,
    data: Vec<u8>,
) -> ActionResult<users::Model> {
    if data.is_empty() {
        return Err(ActionError::Invalid("That file is empty.".into()));
    }
    if data.len() > MAX_AVATAR_BYTES {
        return Err(ActionError::Invalid("An avatar can be at most 5 MB.".into()));
    }
    let content_type = content_type
        .filter(|ct| AVATAR_TYPES.contains(ct))
        .ok_or_else(|| ActionError::Invalid("An avatar must be a PNG, JPEG, GIF or WebP image.".into()))?;
    let mut am: users::ActiveModel = user.clone().into();
    am.avatar_data = Set(Some(data));
    am.avatar_content_type = Set(Some(content_type.to_string()));
    am.updated_at = Set(Utc::now().into());
    Ok(am.update(state.db.as_ref()).await?)
}

/// Back to the generated letter avatar.
pub async fn clear_avatar(state: &AppState, user: &users::Model) -> ActionResult<users::Model> {
    let mut am: users::ActiveModel = user.clone().into();
    am.avatar_data = Set(None);
    am.avatar_content_type = Set(None);
    am.updated_at = Set(Utc::now().into());
    Ok(am.update(state.db.as_ref()).await?)
}

/// Mark one of `user_id`'s notifications read. `NotFound` if it isn't theirs.
pub async fn mark_notification_read(
    state: &AppState,
    user_id: Uuid,
    id: Uuid,
) -> ActionResult<crate::entities::notifications::Model> {
    use crate::entities::notifications;
    let n = notifications::Entity::find_by_id(id)
        .filter(notifications::Column::UserId.eq(user_id))
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)?;
    if n.is_read {
        return Ok(n);
    }
    let mut am: notifications::ActiveModel = n.into();
    am.is_read = Set(true);
    Ok(am.update(state.db.as_ref()).await?)
}

/// Mark all of `user_id`'s notifications read.
pub async fn mark_all_notifications_read(state: &AppState, user_id: Uuid) -> ActionResult<()> {
    use crate::entities::notifications;
    notifications::Entity::update_many()
        .col_expr(notifications::Column::IsRead, sea_orm::sea_query::Expr::value(true))
        .filter(notifications::Column::UserId.eq(user_id))
        .filter(notifications::Column::IsRead.eq(false))
        .exec(state.db.as_ref())
        .await?;
    Ok(())
}