31.4 KiB · text History 6e34613
//! Writes shared by the web handlers and `/api/v1` (party-slut's
//! `src/actions.rs`): starting a topic, replying, editing, tagging, reacting,
//! bookmarking, watching, and the profile's preferences and avatar. Staff
//! moderation and flags are in `crate::moderation`.
//!
//! Each one checks what the web always checked — the category is visible to
//! this user (trust level, staff), the account may write (email
//! verification, not silenced), the category's posting rules, the topic isn't
//! locked (`crate::policy`) — 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,
    /// `message` says it to a person).
    Forbidden { code: &'static str, message: String },
    /// Already done and can't be done twice (a second flag).
    Conflict { code: &'static str, message: String },
    /// The input itself is wrong; the message says how, for a person.
    Invalid(String),
    /// Longer than `MAX_POST_CHARS`.
    TooLong(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::Conflict { .. } => StatusCode::CONFLICT,
            Self::Invalid(_) => StatusCode::BAD_REQUEST,
            Self::TooLong(_) => StatusCode::PAYLOAD_TOO_LARGE,
            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.".into() },
            StatusCode::BAD_REQUEST => Self::Invalid("That request couldn't be read.".into()),
            other => Self::Internal(other.to_string()),
        }
    }
}

impl From<crate::policy::Block> for ActionError {
    fn from(b: crate::policy::Block) -> Self {
        Self::Forbidden { code: b.code, message: b.message }
    }
}

impl ActionError {
    /// The sentence for a person (web flash, API message).
    pub fn message(&self) -> String {
        match self {
            Self::NotFound => "We couldn't find that.".into(),
            Self::Unverified => "Verify your email address to post, react or bookmark.".into(),
            Self::Forbidden { message, .. } | Self::Conflict { message, .. } => message.clone(),
            Self::Invalid(m) | Self::TooLong(m) => m.clone(),
            Self::Internal(_) => "Something went wrong on our side.".into(),
        }
    }
}

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

/// For web handlers whose refusals a person should read (the composer's):
/// the status with the sentence as a plain-text body.
pub struct WebError(StatusCode, Option<String>);

impl From<ActionError> for WebError {
    fn from(e: ActionError) -> Self {
        let msg = (!matches!(e, ActionError::Internal(_))).then(|| e.message());
        Self(e.status(), msg)
    }
}

impl From<StatusCode> for WebError {
    fn from(s: StatusCode) -> Self {
        Self(s, None)
    }
}

impl axum::response::IntoResponse for WebError {
    fn into_response(self) -> axum::response::Response {
        match self.1 {
            Some(m) => (self.0, m).into_response(),
            None => self.0.into_response(),
        }
    }
}

/// Refuse a post over `MAX_POST_CHARS`.
fn check_length(state: &AppState, body: &str) -> ActionResult<()> {
    let max = state.config.lameness.max_chars;
    let n = body.chars().count();
    if n > max {
        return Err(ActionError::TooLong(format!(
            "Posts can be at most {max} characters; this one has {n}. Split it up or trim it."
        )));
    }
    Ok(())
}

/// Score a post body ([`crate::lameness`]) against the author's other posts
/// of the last `LAMENESS_DUP_HOURS`. None when the filter is off.
async fn lameness_score(
    state: &AppState,
    user: &users::Model,
    body: &str,
    except: Option<Uuid>,
) -> ActionResult<Option<crate::lameness::Score>> {
    let cfg = &state.config.lameness;
    if !cfg.enabled {
        return Ok(None);
    }
    let since = Utc::now() - chrono::Duration::hours(cfg.dup_hours);
    let mut find = posts::Entity::find()
        .select_only()
        .column(posts::Column::Raw)
        .filter(posts::Column::UserId.eq(user.id))
        .filter(posts::Column::CreatedAt.gt(since))
        .filter(posts::Column::DeletedAt.is_null())
        .order_by_desc(posts::Column::CreatedAt)
        .limit(50);
    if let Some(id) = except {
        find = find.filter(posts::Column::Id.ne(id));
    }
    let recent: Vec<String> = find.into_tuple().all(state.db.as_ref()).await?;
    Ok(Some(crate::lameness::score(
        cfg,
        &crate::lameness::Input { text: body, trust_level: user.trust_level, recent: &recent },
    )))
}

/// Hold the post if the filter tripped (staff are scored but never held).
async fn apply_lameness(
    state: &AppState,
    user: &users::Model,
    post: posts::Model,
    score: Option<crate::lameness::Score>,
) -> ActionResult<posts::Model> {
    match score {
        Some(s) if s.tripped() && !user.is_staff => crate::moderation::hold_post(state, post, &s).await,
        Some(s) if s.tripped() => {
            tracing::info!(post = %post.id, reasons = ?s.reasons(), "lameness: staff post not held");
            Ok(post)
        }
        _ => Ok(post),
    }
}

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

/// A verified address (where the site requires one) — enough for private
/// things like bookmarks.
pub fn require_verified(state: &AppState, user: &users::Model) -> ActionResult<()> {
    if crate::handlers::may_write(state, user) {
        Ok(())
    } else {
        Err(ActionError::Unverified)
    }
}

/// May post, reply, edit, react, tag or flag at all: verified and not
/// silenced. The category's rules and locks come on top.
pub fn require_writer(state: &AppState, user: &users::Model) -> ActionResult<()> {
    require_verified(state, user)?;
    match crate::policy::silenced_block(user) {
        Some(b) => Err(b.into()),
        None => Ok(()),
    }
}

/// Whether [`require_writer`] passes (templates, API booleans).
pub fn can_write(state: &AppState, user: &users::Model) -> bool {
    require_writer(state, user).is_ok()
}

/// Why `user` can't write at all, if they can't: an unverified address or a
/// silence.
pub fn account_block(state: &AppState, user: &users::Model) -> Option<crate::policy::Block> {
    if !crate::handlers::may_write(state, user) {
        return Some(crate::policy::Block::new("unverified", "Verify your email address to post, reply, react and flag."));
    }
    crate::policy::silenced_block(user)
}

/// What a viewer may do in a topic: the pages show exactly these controls,
/// the API sends them, and the writes check the same rules.
#[derive(Clone, Debug, Default, serde::Serialize)]
pub struct TopicCaps {
    pub signed_in: bool,
    pub is_staff: bool,
    pub user_id: Option<Uuid>,
    /// Reply (and, the same rule, react).
    pub can_reply: bool,
    pub can_react: bool,
    /// Why not, for a signed-in viewer (None when they can, or for a
    /// removed topic).
    pub reply_block: Option<crate::policy::Block>,
    /// Flag posts in it (per post: not their own, not twice).
    pub can_flag: bool,
    /// Bookmark posts (private: a lock or silence doesn't stop it).
    pub can_bookmark: bool,
    pub locked: bool,
    pub lock_message: Option<String>,
    /// The category's reactions: which types posts show and take.
    #[serde(skip)]
    pub reactions: crate::policy::ReactionRule,
}

pub fn topic_caps(
    state: &AppState,
    user: Option<&users::Model>,
    category: Option<&categories::Model>,
    topic: &topics::Model,
) -> TopicCaps {
    let locked = topic.is_closed;
    let mut caps = TopicCaps {
        locked,
        lock_message: locked.then(|| crate::policy::lock_message(topic)),
        reactions: category.map(crate::policy::ReactionRule::of).unwrap_or_default(),
        ..Default::default()
    };
    let Some(u) = user else { return caps };
    caps.signed_in = true;
    caps.is_staff = u.is_staff;
    caps.user_id = Some(u.id);
    if topic.deleted_at.is_some() {
        return caps;
    }
    caps.can_bookmark = crate::handlers::may_write(state, u);
    if let Some(b) = account_block(state, u) {
        caps.reply_block = Some(b);
        return caps;
    }
    caps.can_flag = u.is_staff || u.trust_level >= state.config.min_trust_to_flag;
    caps.reply_block = category.and_then(|c| crate::policy::reply_block(u, c, topic));
    caps.can_reply = category.is_some() && caps.reply_block.is_none();
    caps.can_react = caps.can_reply && !caps.reactions.is_off();
    caps
}

/// The reaction types `rule` offers, from the active ones, in order.
pub fn offered_types(
    types: Vec<crate::entities::reaction_types::Model>,
    rule: &crate::policy::ReactionRule,
) -> Vec<crate::entities::reaction_types::Model> {
    types.into_iter().filter(|t| rule.allows(&t.key)).collect()
}

/// Whether a viewer may start a topic in `category`, and why not.
pub fn create_caps(
    state: &AppState,
    user: Option<&users::Model>,
    category: &categories::Model,
) -> (bool, Option<crate::policy::Block>) {
    let Some(u) = user else { return (false, None) };
    let block = account_block(state, u).or_else(|| crate::policy::create_block(u, category));
    (block.is_none(), block)
}

/// The category a topic is in, from a loaded tree.
pub fn topic_category<'a>(tree: &'a CategoryTree, topic: &topics::Model) -> ActionResult<&'a categories::Model> {
    tree.get(topic.category_id).ok_or(ActionError::NotFound)
}

/// 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, with its topic and the
/// category tree.
pub async fn visible_live_post(
    state: &AppState,
    viewer: Viewer,
    post_id: Uuid,
) -> ActionResult<(posts::Model, topics::Model, CategoryTree)> {
    let post = posts::Entity::find_by_id(post_id)
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)?;
    let (topic, tree) = 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, topic, tree))
}

/// 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()));
    }
    check_length(state, body)?;
    let (category, tree) = visible_category(state, viewer(user), slug).await?;
    if let Some(b) = crate::policy::create_block(user, &category) {
        return Err(b.into());
    }
    let score = lameness_score(state, user, body, None).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),
        closed_at: Set(None),
        closed_by_id: Set(None),
        closed_reason: Set(None),
    }
    .insert(state.db.as_ref())
    .await?;
    let post = insert_post(state, user, topic.id, 1, body).await?;
    apply_lameness(state, user, post, score).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()));
    }
    check_length(state, body)?;
    let (topic, tree) = visible_topic(state, viewer(user), topic_id).await?;
    if topic.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    if let Some(b) = crate::policy::reply_block(user, topic_category(&tree, &topic)?, &topic) {
        return Err(b.into());
    }
    let score = lameness_score(state, user, body, None).await?;
    let next_number = topic.posts_count + 1;
    let post = insert_post(state, user, topic.id, next_number, body).await?;
    let post = apply_lameness(state, user, post, score).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),
        moderated_at: Set(None),
        moderated_by_id: Set(None),
        hidden_at: 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(), "edit")
        .await?;
    Ok(post)
}

/// Whether `user` may edit `post` (in `topic`): its author or staff, a live
/// post, not silenced or unverified; not a post staff moderated (only staff
/// can change it then); not in a locked topic (staff excepted).
pub fn edit_block(state: &AppState, user: &users::Model, post: &posts::Model, topic: &topics::Model) -> Option<ActionError> {
    if post.deleted_at.is_some() || topic.deleted_at.is_some() {
        return Some(ActionError::NotFound);
    }
    if !(user.is_staff || user.id == post.user_id) {
        return Some(ActionError::Forbidden { code: "not_author", message: "Only the author or staff can edit this post.".into() });
    }
    if let Err(e) = require_writer(state, user) {
        return Some(e);
    }
    if user.is_staff {
        return None;
    }
    if post.moderated_at.is_some() {
        return Some(ActionError::Forbidden {
            code: "moderated",
            message: "Staff moderated this post; only staff can change it.".into(),
        });
    }
    if topic.is_closed {
        return Some(ActionError::Forbidden { code: "locked", message: crate::policy::lock_message(topic) });
    }
    None
}

/// Edit a post: a new revision, the post updated. A no-op edit changes
/// nothing. Returns the post.
pub async fn edit_post(state: &AppState, user: &users::Model, post_id: Uuid, body: &str) -> ActionResult<posts::Model> {
    let (post, topic, _) = visible_live_post(state, viewer(user), post_id).await?;
    if let Some(e) = edit_block(state, user, &post, &topic) {
        return Err(e);
    }
    let body = body.trim();
    if body.is_empty() {
        return Err(ActionError::Invalid("A post can't be empty.".into()));
    }
    if body == post.raw {
        return Ok(post);
    }
    check_length(state, body)?;
    // Re-scored as the author's: an approved post edited into junk is held
    // again (a staff edit of someone's post isn't held).
    let score = lameness_score(state, user, body, Some(post.id)).await?;
    let now = Utc::now();
    let cooked = markdown::render(body);
    // Revision 1 is the original, so the n-th edit produces revision n+1.
    let next_number = post.edit_count + 2;
    crate::handlers::posts::record_revision(state.db.as_ref(), post.id, next_number, user.id, body, &cooked, now.into(), "edit")
        .await?;
    let mut am: posts::ActiveModel = post.into();
    am.raw = Set(body.to_string());
    am.cooked = Set(cooked);
    am.edit_count = Set(next_number - 1);
    am.edited_at = Set(Some(now.into()));
    am.last_editor_id = Set(Some(user.id));
    am.updated_at = Set(now.into());
    let post = am.update(state.db.as_ref()).await?;
    apply_lameness(state, user, post, score).await
}

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 && !topic.is_closed))
        && can_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.".into(),
        });
    }
    if topic.is_closed && !user.is_staff {
        return Err(ActionError::Forbidden { code: "locked", message: crate::policy::lock_message(&topic) });
    }
    // 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, topic, tree) = visible_live_post(state, viewer(user), post_id).await?;
    let category = topic_category(&tree, &topic)?;
    if let Some(b) = crate::policy::reaction_block(category, key) {
        return Err(b.into());
    }
    if let Some(b) = crate::policy::reply_block(user, category, &topic) {
        return Err(b.into());
    }
    let rule = crate::policy::ReactionRule::of(category);
    if post.hidden_at.is_some() && !user.is_staff {
        return Err(ActionError::Forbidden { code: "hidden", message: "This post is hidden pending staff review.".into() });
    }
    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 = offered_types(active_reaction_types(state.db.as_ref()).await?, &rule);
    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.
/// Bookmarks are private, so a silence or a lock doesn't stop them.
pub async fn set_bookmark(state: &AppState, user: &users::Model, post_id: Uuid, on: bool) -> ActionResult<bool> {
    require_verified(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(())
}