41.0 KiB · text History 7ce364f
//! Staff moderation, flags and sanctions, shared by the web, `/api/v1` and
//! `manage` (as `crate::actions` is for ordinary writes). Every staff action
//! writes a [`moderation_log`] row: who, what, which, why, when.
//!
//! * Topics: lock / unlock (with a reason), pin / unpin, delete / restore.
//! * Posts: moderate (the body becomes a staff note, through a `moderation`
//!   revision), hide / unhide the pre-moderation versions from non-staff,
//!   restore the pre-moderation body, delete / restore.
//! * Flags: one per user per post; enough flags from enough of a post's
//!   readers hide it pending review ([`crate::policy::FlagThreshold`]);
//!   staff dismiss them or uphold them by moderating or deleting the post.
//!   Flags from a flag-shadowbanned user are recorded but ignored.
//! * Users: silence, suspend (sessions and device tokens revoked), lift
//!   either, flag shadowban.
//! * Lameness holds ([`crate::lameness`]): a caught post is hidden pending
//!   review like the auto-hide. Staff dismiss it (shown again, no strike)
//!   or uphold it by moderating or deleting the post (a strike). Strikes
//!   within `LAMENESS_STRIKE_DAYS` climb `LAMENESS_LADDER`; a flood of holds
//!   gets a short cooldown before anyone reviews them.
use chrono::{DateTime, FixedOffset, Utc};
use sea_orm::sea_query::Expr;
use sea_orm::*;
use tracing::error;
use uuid::Uuid;

use crate::actions::{self, viewer, ActionError, ActionResult};
use crate::entities::{
    api_tokens, moderation_log, post_flags, post_holds, post_revisions, posts, topic_reads, topics, user_sessions, users,
};
use crate::markdown;
use crate::AppState;

/// Where a moderation action came from (`moderation_log.source`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Source {
    Web,
    Api,
    Cli,
    /// The auto-hide.
    System,
}

impl Source {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Web => "web",
            Self::Api => "api",
            Self::Cli => "cli",
            Self::System => "system",
        }
    }
}

/// Who did it: a staff account (None from the CLI without `--by`, or the
/// system) and where.
#[derive(Clone, Copy)]
pub struct Actor<'a> {
    pub user: Option<&'a users::Model>,
    pub source: Source,
}

impl<'a> Actor<'a> {
    pub fn web(u: &'a users::Model) -> Self {
        Self { user: Some(u), source: Source::Web }
    }

    pub fn cli(u: Option<&'a users::Model>) -> Self {
        Self { user: u, source: Source::Cli }
    }

    pub fn system() -> Self {
        Self { user: None, source: Source::System }
    }

    /// Staff, or the CLI (the operator).
    pub(crate) fn require_staff(&self) -> ActionResult<()> {
        match (self.source, self.user) {
            (Source::Cli, _) | (Source::System, _) => Ok(()),
            (_, Some(u)) if u.is_staff => Ok(()),
            _ => Err(ActionError::Forbidden { code: "staff_only", message: "Only staff can do that.".into() }),
        }
    }

    pub(crate) fn id(&self) -> Option<Uuid> {
        self.user.map(|u| u.id)
    }
}

fn clean(s: Option<&str>) -> Option<String> {
    s.map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
}

/// Append to the moderation log. Best effort: a failed log line is logged,
/// not allowed to undo the action.
pub async fn log<C: ConnectionTrait>(
    db: &C,
    actor: Actor<'_>,
    action: &str,
    target_kind: &str,
    target_id: Option<Uuid>,
    target_label: &str,
    reason: Option<&str>,
) {
    let row = moderation_log::ActiveModel {
        id: Set(Uuid::now_v7()),
        actor_id: Set(actor.id()),
        source: Set(actor.source.as_str().into()),
        action: Set(action.into()),
        target_kind: Set(target_kind.into()),
        target_id: Set(target_id),
        target_label: Set(target_label.into()),
        reason: Set(clean(reason)),
        created_at: Set(Utc::now().into()),
    };
    if let Err(e) = row.insert(db).await {
        error!(error = %e, action, "moderation log write failed");
    }
}

fn topic_label(t: &topics::Model) -> String {
    format!("“{}”", t.title)
}

pub(crate) async fn post_label(db: &DatabaseConnection, p: &posts::Model) -> String {
    let title = topics::Entity::find_by_id(p.topic_id).one(db).await.ok().flatten().map(|t| t.title);
    format!("#{} in “{}”", p.post_number, title.unwrap_or_default())
}

fn user_label(u: &users::Model) -> String {
    format!("@{}", u.username)
}

async fn load_topic(state: &AppState, id: Uuid) -> ActionResult<topics::Model> {
    topics::Entity::find_by_id(id).one(state.db.as_ref()).await?.ok_or(ActionError::NotFound)
}

async fn load_post(state: &AppState, id: Uuid) -> ActionResult<posts::Model> {
    posts::Entity::find_by_id(id).one(state.db.as_ref()).await?.ok_or(ActionError::NotFound)
}

// --- topics -----------------------------------------------------------------

/// Lock (`reason` optional) or unlock a topic. Staff can still post in it.
pub async fn set_locked(
    state: &AppState,
    actor: Actor<'_>,
    topic_id: Uuid,
    locked: bool,
    reason: Option<&str>,
) -> ActionResult<topics::Model> {
    actor.require_staff()?;
    let topic = load_topic(state, topic_id).await?;
    if topic.is_closed == locked {
        return Ok(topic);
    }
    let label = topic_label(&topic);
    let now = Utc::now();
    let mut am: topics::ActiveModel = topic.into();
    am.is_closed = Set(locked);
    am.closed_at = Set(locked.then(|| now.into()));
    am.closed_by_id = Set(if locked { actor.id() } else { None });
    am.closed_reason = Set(if locked { clean(reason) } else { None });
    am.updated_at = Set(now.into());
    let topic = am.update(state.db.as_ref()).await?;
    log(state.db.as_ref(), actor, if locked { "lock_topic" } else { "unlock_topic" }, "topic", Some(topic.id), &label, reason)
        .await;
    Ok(topic)
}

/// Pin (first in its lists) or unpin a topic.
pub async fn set_pinned(state: &AppState, actor: Actor<'_>, topic_id: Uuid, pinned: bool) -> ActionResult<topics::Model> {
    actor.require_staff()?;
    let topic = load_topic(state, topic_id).await?;
    if topic.is_pinned == pinned {
        return Ok(topic);
    }
    let label = topic_label(&topic);
    let mut am: topics::ActiveModel = topic.into();
    am.is_pinned = Set(pinned);
    am.updated_at = Set(Utc::now().into());
    let topic = am.update(state.db.as_ref()).await?;
    log(state.db.as_ref(), actor, if pinned { "pin_topic" } else { "unpin_topic" }, "topic", Some(topic.id), &label, None)
        .await;
    Ok(topic)
}

/// Soft-delete a topic: its author, or staff (logged when it isn't theirs).
pub async fn delete_topic(state: &AppState, user: &users::Model, topic_id: Uuid) -> ActionResult<topics::Model> {
    let (topic, _) = actions::visible_topic(state, viewer(user), topic_id).await?;
    if !(user.is_staff || user.id == topic.user_id) {
        return Err(ActionError::Forbidden { code: "not_author", message: "Only the author or staff can delete this topic.".into() });
    }
    if topic.deleted_at.is_some() {
        return Ok(topic);
    }
    let label = topic_label(&topic);
    let now = Utc::now();
    let author = topic.user_id;
    let mut t: topics::ActiveModel = topic.into();
    t.deleted_at = Set(Some(now.into()));
    t.deleted_by_id = Set(Some(user.id));
    t.updated_at = Set(now.into());
    let topic = t.update(state.db.as_ref()).await?;
    // A held topic deleted: staff uphold the hold, the author withdraws it.
    if topic.held_at.is_some() {
        let op = posts::Entity::find()
            .filter(posts::Column::TopicId.eq(topic.id))
            .filter(posts::Column::PostNumber.eq(1))
            .one(state.db.as_ref())
            .await?;
        if let Some(op) = op {
            if user.is_staff && user.id != author {
                uphold_holds(state, &op, user.id).await?;
            } else {
                resolve_holds(state.db.as_ref(), op.id, Some(user.id), "withdrawn").await?;
            }
        }
    }
    if user.id != author {
        log(state.db.as_ref(), Actor::web(user), "delete_topic", "topic", Some(topic.id), &label, None).await;
    }
    Ok(topic)
}

/// Restore a deleted topic (staff).
pub async fn restore_topic(state: &AppState, actor: Actor<'_>, topic_id: Uuid) -> ActionResult<topics::Model> {
    actor.require_staff()?;
    let topic = load_topic(state, topic_id).await?;
    if topic.deleted_at.is_none() {
        return Ok(topic);
    }
    let label = topic_label(&topic);
    let mut t: topics::ActiveModel = topic.into();
    t.deleted_at = Set(None);
    t.deleted_by_id = Set(None);
    t.updated_at = Set(Utc::now().into());
    let topic = t.update(state.db.as_ref()).await?;
    log(state.db.as_ref(), actor, "restore_topic", "topic", Some(topic.id), &label, None).await;
    state.live.publish(topic.id);
    Ok(topic)
}

// --- posts ------------------------------------------------------------------

/// Soft-delete a post: its author, or staff. Staff deleting someone else's
/// post upholds its pending flags and is logged.
pub async fn delete_post(state: &AppState, actor: Actor<'_>, post_id: Uuid) -> ActionResult<posts::Model> {
    let user = actor.user.ok_or(ActionError::NotFound)?;
    let post = load_post(state, post_id).await?;
    let (topic, _) = actions::visible_topic(state, viewer(user), post.topic_id).await?;
    let _ = topic;
    if !(user.is_staff || user.id == post.user_id) {
        return Err(ActionError::Forbidden { code: "not_author", message: "Only the author or staff can delete this post.".into() });
    }
    if post.deleted_at.is_some() {
        return Ok(post);
    }
    let now = Utc::now();
    let by_staff = user.id != post.user_id;
    let label = post_label(state.db.as_ref(), &post).await;
    let mut am: posts::ActiveModel = post.into();
    am.deleted_at = Set(Some(now.into()));
    am.deleted_by_id = Set(Some(user.id));
    am.hidden_at = Set(None);
    am.updated_at = Set(now.into());
    let post = am.update(state.db.as_ref()).await?;
    if by_staff {
        resolve_flags(state.db.as_ref(), post.id, user.id, "upheld").await?;
        log(state.db.as_ref(), actor, "delete_post", "post", Some(post.id), &label, None).await;
        // Upholding a held opening post by deleting it takes the topic (its
        // title is the same junk) with it.
        if uphold_holds(state, &post, user.id).await? && post.post_number == 1 {
            delete_topic(state, user, post.topic_id).await?;
        }
    } else {
        // Withdrawn before review: no strike.
        resolve_holds(state.db.as_ref(), post.id, Some(user.id), "withdrawn").await?;
    }
    Ok(post)
}

/// Restore a deleted post (staff).
pub async fn restore_post(state: &AppState, actor: Actor<'_>, post_id: Uuid) -> ActionResult<posts::Model> {
    actor.require_staff()?;
    let post = load_post(state, post_id).await?;
    if post.deleted_at.is_none() {
        return Ok(post);
    }
    let label = post_label(state.db.as_ref(), &post).await;
    let mut am: posts::ActiveModel = post.into();
    am.deleted_at = Set(None);
    am.deleted_by_id = Set(None);
    am.updated_at = Set(Utc::now().into());
    let post = am.update(state.db.as_ref()).await?;
    log(state.db.as_ref(), actor, "restore_post", "post", Some(post.id), &label, None).await;
    state.live.publish(post.topic_id);
    Ok(post)
}

/// The post's revisions, oldest first.
pub async fn revisions(db: &DatabaseConnection, post_id: Uuid) -> Result<Vec<post_revisions::Model>, DbErr> {
    post_revisions::Entity::find()
        .filter(post_revisions::Column::PostId.eq(post_id))
        .order_by_asc(post_revisions::Column::RevisionNumber)
        .all(db)
        .await
}

/// Replace a post's body with a staff note, shown as "staff: <note>". It's a
/// `moderation` revision in the post's history; the author can't edit it
/// back. With `hide_original`, the versions before it are hidden from
/// non-staff in the history. Upholds the post's pending flags and lifts a
/// pending-review hide (staff have decided).
pub async fn moderate_post(
    state: &AppState,
    actor: Actor<'_>,
    post_id: Uuid,
    note: &str,
    hide_original: bool,
) -> ActionResult<posts::Model> {
    actor.require_staff()?;
    let note = note.trim();
    if note.is_empty() {
        return Err(ActionError::Invalid("Write the note that replaces the post.".into()));
    }
    let post = load_post(state, post_id).await?;
    if post.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    let editor = actor.id().ok_or_else(|| ActionError::Invalid("Moderation needs a staff account (--by).".into()))?;
    let now = Utc::now();
    let cooked = markdown::render(note);
    let next = post.edit_count + 2;
    crate::handlers::posts::record_revision(state.db.as_ref(), post.id, next, editor, note, &cooked, now.into(), "moderation")
        .await?;
    let label = post_label(state.db.as_ref(), &post).await;
    let was_hidden = post.hidden_at.is_some();
    let mut am: posts::ActiveModel = post.into();
    am.raw = Set(note.to_string());
    am.cooked = Set(cooked);
    am.edit_count = Set(next - 1);
    am.edited_at = Set(Some(now.into()));
    am.last_editor_id = Set(Some(editor));
    am.moderated_at = Set(Some(now.into()));
    am.moderated_by_id = Set(Some(editor));
    am.hidden_at = Set(None);
    am.updated_at = Set(now.into());
    let post = am.update(state.db.as_ref()).await?;
    resolve_flags(state.db.as_ref(), post.id, editor, "upheld").await?;
    log(state.db.as_ref(), actor, "moderate_post", "post", Some(post.id), &label, Some(note)).await;
    uphold_holds(state, &post, editor).await?;
    if hide_original {
        set_original_hidden(state, actor, post.id, true).await?;
    }
    // A hidden or held post shows again, as the note (a held opening post
    // brings its topic back).
    if was_hidden {
        state.live.publish(post.topic_id);
    }
    Ok(post)
}

/// The revisions a moderation replaced: everything before the latest
/// `moderation` revision that isn't itself a moderation note.
fn pre_moderation(revs: &[post_revisions::Model]) -> Vec<&post_revisions::Model> {
    let Some(cut) = revs.iter().filter(|r| r.kind == "moderation").map(|r| r.revision_number).max() else {
        return vec![];
    };
    revs.iter().filter(|r| r.revision_number < cut && r.kind != "moderation").collect()
}

/// Hide (or show again) a moderated post's earlier versions from non-staff
/// in its history. Staff still see them, marked.
pub async fn set_original_hidden(state: &AppState, actor: Actor<'_>, post_id: Uuid, hidden: bool) -> ActionResult<()> {
    actor.require_staff()?;
    let post = load_post(state, post_id).await?;
    if post.moderated_at.is_none() {
        return Err(ActionError::Invalid("Only a moderated post's earlier versions can be hidden.".into()));
    }
    let revs = revisions(state.db.as_ref(), post.id).await?;
    let ids: Vec<Uuid> = pre_moderation(&revs).into_iter().map(|r| r.id).collect();
    if ids.is_empty() {
        return Ok(());
    }
    post_revisions::Entity::update_many()
        .col_expr(
            post_revisions::Column::HiddenAt,
            Expr::value(if hidden { Some(DateTime::<FixedOffset>::from(Utc::now())) } else { None }),
        )
        .col_expr(post_revisions::Column::HiddenById, Expr::value(if hidden { actor.id() } else { None }))
        .filter(post_revisions::Column::Id.is_in(ids))
        .exec(state.db.as_ref())
        .await?;
    let label = post_label(state.db.as_ref(), &post).await;
    log(state.db.as_ref(), actor, if hidden { "hide_original" } else { "unhide_original" }, "post", Some(post.id), &label, None)
        .await;
    Ok(())
}

/// Put a moderated post's last pre-moderation body back (a `restore`
/// revision) and show its history to everyone again.
pub async fn restore_moderated(state: &AppState, actor: Actor<'_>, post_id: Uuid) -> ActionResult<posts::Model> {
    actor.require_staff()?;
    let post = load_post(state, post_id).await?;
    if post.moderated_at.is_none() {
        return Ok(post);
    }
    let revs = revisions(state.db.as_ref(), post.id).await?;
    let original = pre_moderation(&revs)
        .into_iter()
        .last()
        .cloned()
        .ok_or_else(|| ActionError::Invalid("There's no earlier version to restore.".into()))?;
    let editor = actor.id().ok_or_else(|| ActionError::Invalid("Restoring needs a staff account (--by).".into()))?;
    let hidden: Vec<Uuid> = revs.iter().filter(|r| r.hidden_at.is_some()).map(|r| r.id).collect();
    if !hidden.is_empty() {
        post_revisions::Entity::update_many()
            .col_expr(post_revisions::Column::HiddenAt, Expr::value(Option::<DateTime<FixedOffset>>::None))
            .col_expr(post_revisions::Column::HiddenById, Expr::value(Option::<Uuid>::None))
            .filter(post_revisions::Column::Id.is_in(hidden))
            .exec(state.db.as_ref())
            .await?;
    }
    let now = Utc::now();
    let next = post.edit_count + 2;
    crate::handlers::posts::record_revision(
        state.db.as_ref(),
        post.id,
        next,
        editor,
        &original.raw,
        &original.cooked,
        now.into(),
        "restore",
    )
    .await?;
    let label = post_label(state.db.as_ref(), &post).await;
    let mut am: posts::ActiveModel = post.into();
    am.raw = Set(original.raw.clone());
    am.cooked = Set(original.cooked.clone());
    am.edit_count = Set(next - 1);
    am.edited_at = Set(Some(now.into()));
    am.last_editor_id = Set(Some(editor));
    am.moderated_at = Set(None);
    am.moderated_by_id = Set(None);
    am.updated_at = Set(now.into());
    let post = am.update(state.db.as_ref()).await?;
    log(state.db.as_ref(), actor, "restore_post_body", "post", Some(post.id), &label, None).await;
    Ok(post)
}

// --- flags ------------------------------------------------------------------

/// Whether `user` has flagged `post_id`.
pub async fn has_flagged(db: &DatabaseConnection, user_id: Uuid, post_id: Uuid) -> Result<bool, DbErr> {
    Ok(post_flags::Entity::find()
        .filter(post_flags::Column::UserId.eq(user_id))
        .filter(post_flags::Column::PostId.eq(post_id))
        .count(db)
        .await?
        > 0)
}

/// Flag a post (`reason` one of [`crate::policy::FLAG_REASONS`], `note`
/// optional). Once per post; not your own. May hide the post pending review.
/// A flag-shadowbanned user's flag is recorded the same way (they can't
/// tell) but counts for nothing.
pub async fn flag_post(
    state: &AppState,
    user: &users::Model,
    post_id: Uuid,
    reason: &str,
    note: Option<&str>,
    ip: Option<std::net::IpAddr>,
) -> ActionResult<post_flags::Model> {
    actions::require_writer(state, user)?;
    let (post, _, _) = actions::visible_live_post(state, viewer(user), post_id).await?;
    if let Some(b) = crate::policy::flag_block(user, post.user_id, state.config.min_trust_to_flag) {
        return Err(b.into());
    }
    if !crate::policy::FLAG_REASONS.iter().any(|(k, _)| *k == reason) {
        return Err(ActionError::Invalid("Pick a reason: spam, abusive, off_topic or other.".into()));
    }
    let note = clean(note).map(|n| n.chars().take(1000).collect::<String>());
    if has_flagged(state.db.as_ref(), user.id, post.id).await? {
        return Err(ActionError::Conflict { code: "already_flagged", message: "You've already flagged this post.".into() });
    }
    let flag = post_flags::ActiveModel {
        id: Set(Uuid::now_v7()),
        post_id: Set(post.id),
        user_id: Set(user.id),
        reason: Set(reason.into()),
        note: Set(note),
        created_at: Set(Utc::now().into()),
        resolved_at: Set(None),
        resolved_by_id: Set(None),
        resolution: Set(None),
        ip: Set(ip.map(|i| crate::client_ip::canonical(i).to_string())),
    }
    .insert(state.db.as_ref())
    .await?;
    crate::ips::record(state.db.as_ref(), user.id, ip, crate::ips::Seen::Flag).await;
    evaluate_auto_hide(state, post.id).await?;
    Ok(flag)
}

/// The inputs to the auto-hide for one post.
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
pub struct FlagCounts {
    /// Pending flags from users whose flags count.
    pub flaggers: u64,
    /// Distinct readers at or past the post, not its author.
    pub readers: u64,
}

/// Count a post's effective pending flaggers and its readers.
pub async fn flag_counts(db: &DatabaseConnection, post: &posts::Model) -> Result<FlagCounts, DbErr> {
    let flaggers = post_flags::Entity::find()
        .filter(post_flags::Column::PostId.eq(post.id))
        .filter(post_flags::Column::ResolvedAt.is_null())
        .inner_join(users::Entity)
        .filter(users::Column::FlagsIgnoredAt.is_null())
        .count(db)
        .await?;
    let readers = topic_reads::Entity::find()
        .filter(topic_reads::Column::TopicId.eq(post.topic_id))
        .filter(topic_reads::Column::LastReadPostNumber.gte(post.post_number))
        .filter(topic_reads::Column::UserId.ne(post.user_id))
        .count(db)
        .await?;
    Ok(FlagCounts { flaggers, readers })
}

/// Hide a post pending review if its flags now reach the threshold. Returns
/// whether it hid it.
pub async fn evaluate_auto_hide(state: &AppState, post_id: Uuid) -> ActionResult<bool> {
    let post = load_post(state, post_id).await?;
    if post.hidden_at.is_some() || post.deleted_at.is_some() || post.moderated_at.is_some() {
        return Ok(false);
    }
    let c = flag_counts(state.db.as_ref(), &post).await?;
    if !state.config.flag_threshold.should_hide(c.flaggers, c.readers) {
        return Ok(false);
    }
    let label = post_label(state.db.as_ref(), &post).await;
    let mut am: posts::ActiveModel = post.into();
    am.hidden_at = Set(Some(Utc::now().into()));
    let post = am.update(state.db.as_ref()).await?;
    let why = format!("{} of {} readers flagged it", c.flaggers, c.readers.max(c.flaggers));
    log(state.db.as_ref(), Actor::system(), "auto_hide", "post", Some(post.id), &label, Some(&why)).await;
    Ok(true)
}

async fn resolve_flags(db: &DatabaseConnection, post_id: Uuid, by: Uuid, resolution: &str) -> Result<u64, DbErr> {
    let r = post_flags::Entity::update_many()
        .col_expr(post_flags::Column::ResolvedAt, Expr::value(DateTime::<FixedOffset>::from(Utc::now())))
        .col_expr(post_flags::Column::ResolvedById, Expr::value(by))
        .col_expr(post_flags::Column::Resolution, Expr::value(resolution))
        .filter(post_flags::Column::PostId.eq(post_id))
        .filter(post_flags::Column::ResolvedAt.is_null())
        .exec(db)
        .await?;
    Ok(r.rows_affected)
}

/// Dismiss a post's pending flags and show it again if they had hidden it.
pub async fn dismiss_flags(state: &AppState, actor: Actor<'_>, post_id: Uuid) -> ActionResult<u64> {
    actor.require_staff()?;
    let by = actor.id().ok_or_else(|| ActionError::Invalid("Needs a staff account.".into()))?;
    let post = load_post(state, post_id).await?;
    let n = resolve_flags(state.db.as_ref(), post.id, by, "dismissed").await?;
    let holds = resolve_holds(state.db.as_ref(), post.id, Some(by), "dismissed").await?;
    let label = post_label(state.db.as_ref(), &post).await;
    if post.hidden_at.is_some() {
        let mut am: posts::ActiveModel = post.clone().into();
        am.hidden_at = Set(None);
        am.update(state.db.as_ref()).await?;
        // Shown again (and its topic, if it was a held opening post).
        state.live.publish(post.topic_id);
    }
    let what = if holds > 0 {
        format!("{n} flag(s) and the lameness hold (a false positive)")
    } else {
        format!("{n} flag(s)")
    };
    log(state.db.as_ref(), actor, "dismiss_flags", "post", Some(post.id), &label, Some(&what)).await;
    Ok(n + holds)
}

// --- lameness holds ------------------------------------------------------

/// The post's pending hold, if any.
pub async fn pending_hold(db: &DatabaseConnection, post_id: Uuid) -> Result<Option<post_holds::Model>, DbErr> {
    post_holds::Entity::find()
        .filter(post_holds::Column::PostId.eq(post_id))
        .filter(post_holds::Column::ResolvedAt.is_null())
        .one(db)
        .await
}

/// Pending holds' reasons for these posts.
pub async fn pending_hold_reasons(db: &DatabaseConnection, post_ids: &[Uuid]) -> Result<std::collections::HashMap<Uuid, Vec<String>>, DbErr> {
    if post_ids.is_empty() {
        return Ok(Default::default());
    }
    Ok(post_holds::Entity::find()
        .filter(post_holds::Column::PostId.is_in(post_ids.to_vec()))
        .filter(post_holds::Column::ResolvedAt.is_null())
        .all(db)
        .await?
        .into_iter()
        .map(|h| (h.post_id, h.reason_list()))
        .collect())
}

/// Hold a post the filter caught: hidden pending review (a pending hold is
/// updated with the new scores), logged as `system`, then the flood guard.
pub async fn hold_post(state: &AppState, post: posts::Model, score: &crate::lameness::Score) -> ActionResult<posts::Model> {
    let db = state.db.as_ref();
    let reasons = score.reasons().join("\n");
    let scores = serde_json::to_string(&score.signals).unwrap_or_default();
    match pending_hold(db, post.id).await? {
        Some(h) => {
            let mut am: post_holds::ActiveModel = h.into();
            am.reasons = Set(reasons.clone());
            am.scores = Set(scores);
            am.update(db).await?;
        }
        None => {
            post_holds::ActiveModel {
                id: Set(Uuid::now_v7()),
                post_id: Set(post.id),
                user_id: Set(post.user_id),
                reasons: Set(reasons.clone()),
                scores: Set(scores),
                created_at: Set(Utc::now().into()),
                resolved_at: Set(None),
                resolved_by_id: Set(None),
                resolution: Set(None),
                strike_cleared_at: Set(None),
            }
            .insert(db)
            .await?;
        }
    }
    let label = post_label(db, &post).await;
    let author = post.user_id;
    let post = if post.hidden_at.is_none() {
        let mut am: posts::ActiveModel = post.into();
        am.hidden_at = Set(Some(Utc::now().into()));
        am.update(db).await?
    } else {
        post
    };
    sync_topic_held(db, post.id).await?;
    log(db, Actor::system(), "lameness_hold", "post", Some(post.id), &label, Some(&reasons.replace('\n', "; "))).await;
    flood_guard(state, author).await?;
    Ok(post)
}

async fn resolve_holds(db: &DatabaseConnection, post_id: Uuid, by: Option<Uuid>, resolution: &str) -> Result<u64, DbErr> {
    let r = post_holds::Entity::update_many()
        .col_expr(post_holds::Column::ResolvedAt, Expr::value(DateTime::<FixedOffset>::from(Utc::now())))
        .col_expr(post_holds::Column::ResolvedById, Expr::value(by))
        .col_expr(post_holds::Column::Resolution, Expr::value(resolution))
        .filter(post_holds::Column::PostId.eq(post_id))
        .filter(post_holds::Column::ResolvedAt.is_null())
        .exec(db)
        .await?;
    if r.rows_affected > 0 {
        sync_topic_held(db, post_id).await?;
    }
    Ok(r.rows_affected)
}

/// Staff moderated or deleted a held post: the hold is upheld, a strike,
/// and the ladder.
/// Returns whether there was a hold.
async fn uphold_holds(state: &AppState, post: &posts::Model, by: Uuid) -> ActionResult<bool> {
    if resolve_holds(state.db.as_ref(), post.id, Some(by), "upheld").await? > 0 {
        escalate(state, post.user_id).await?;
        return Ok(true);
    }
    Ok(false)
}

/// Keep `topics.held_at` in step with the opening post's pending hold: the
/// one place it's written. A held opening post hides its whole topic from
/// everyone but the author and staff (`Viewer::sees_topic`); a held reply
/// hides only itself.
async fn sync_topic_held(db: &DatabaseConnection, post_id: Uuid) -> Result<(), DbErr> {
    let Some(post) = posts::Entity::find_by_id(post_id).one(db).await? else { return Ok(()) };
    if post.post_number != 1 {
        return Ok(());
    }
    let held = pending_hold(db, post.id).await?.map(|h| h.created_at);
    topics::Entity::update_many()
        .col_expr(topics::Column::HeldAt, Expr::value(held))
        .filter(topics::Column::Id.eq(post.topic_id))
        .exec(db)
        .await?;
    Ok(())
}

/// Strikes that count: upheld holds within `LAMENESS_STRIKE_DAYS`, not
/// cleared by staff.
pub async fn strikes(db: &DatabaseConnection, cfg: &crate::lameness::Config, user_id: Uuid) -> Result<u64, DbErr> {
    let since = Utc::now() - chrono::Duration::days(cfg.strike_days);
    post_holds::Entity::find()
        .filter(post_holds::Column::UserId.eq(user_id))
        .filter(post_holds::Column::Resolution.eq("upheld"))
        .filter(post_holds::Column::ResolvedAt.gt(since))
        .filter(post_holds::Column::StrikeClearedAt.is_null())
        .count(db)
        .await
}

/// A user's holds: strikes, and how many staff dismissed or are pending.
#[derive(Clone, Debug, Default, serde::Serialize)]
pub struct HoldRecord {
    pub strikes: u64,
    pub strike_days: i64,
    pub dismissed: u64,
    pub pending: u64,
    pub upheld_total: u64,
    /// What the next strike brings.
    pub next_step: String,
}

pub async fn hold_record(db: &DatabaseConnection, cfg: &crate::lameness::Config, user_id: Uuid) -> Result<HoldRecord, DbErr> {
    let rows: Vec<Option<String>> = post_holds::Entity::find()
        .select_only()
        .column(post_holds::Column::Resolution)
        .filter(post_holds::Column::UserId.eq(user_id))
        .into_tuple()
        .all(db)
        .await?;
    let mut r = HoldRecord { strike_days: cfg.strike_days, ..Default::default() };
    for res in rows {
        match res.as_deref() {
            None => r.pending += 1,
            Some("dismissed") => r.dismissed += 1,
            Some("upheld") => r.upheld_total += 1,
            _ => {}
        }
    }
    r.strikes = strikes(db, cfg, user_id).await?;
    r.next_step = cfg.step(r.strikes as usize + 1).describe();
    Ok(r)
}

/// Apply the ladder step for the user's current strikes. A cooldown never
/// shortens a longer silence already in place.
async fn escalate(state: &AppState, user_id: Uuid) -> ActionResult<()> {
    let db = state.db.as_ref();
    let cfg = &state.config.lameness;
    let n = strikes(db, cfg, user_id).await? as usize;
    let Some(user) = users::Entity::find_by_id(user_id).one(db).await? else { return Ok(()) };
    if user.is_staff {
        return Ok(());
    }
    let step = cfg.step(n);
    let why = format!(
        "Automatic: {n} post(s) held as junk and upheld by staff in {} days ({})",
        cfg.strike_days,
        step.describe()
    );
    log(db, Actor::system(), "lameness_strike", "user", Some(user.id), &user_label(&user), Some(&why)).await;
    match step {
        crate::lameness::Step::Nothing => {}
        crate::lameness::Step::Cooldown(d) => cooldown(db, &user, d, &why).await?,
        crate::lameness::Step::Suspend => {
            if crate::policy::suspension(&user).is_none() {
                sanction(db, Actor::system(), user.id, Sanction::Suspend, Some(&format!("{why}; pending staff review")), None)
                    .await?;
            }
        }
    }
    Ok(())
}

/// A system cooldown of `d` (capped at the 90-day maximum), unless a longer
/// one is already running.
async fn cooldown(db: &DatabaseConnection, user: &users::Model, d: chrono::Duration, why: &str) -> ActionResult<()> {
    let d = d.min(chrono::Duration::days(crate::policy::MAX_COOLDOWN_DAYS));
    let until = Utc::now() + d;
    if crate::policy::silence(user).is_some_and(|s| s.until.is_none_or(|u| u >= until)) {
        return Ok(());
    }
    sanction(db, Actor::system(), user.id, Sanction::Silence, Some(why), Some(until)).await?;
    Ok(())
}

/// `LAMENESS_FLOOD_HOLDS` holds within `LAMENESS_FLOOD_WINDOW` (dismissed
/// ones don't count) → `LAMENESS_FLOOD_COOLDOWN` read-only now, before
/// review, to stop a flood. No strike.
async fn flood_guard(state: &AppState, user_id: Uuid) -> ActionResult<()> {
    let cfg = &state.config.lameness;
    let db = state.db.as_ref();
    let since = Utc::now() - cfg.flood_window;
    let n = post_holds::Entity::find()
        .filter(post_holds::Column::UserId.eq(user_id))
        .filter(post_holds::Column::CreatedAt.gt(since))
        .filter(
            Condition::any()
                .add(post_holds::Column::Resolution.is_null())
                .add(post_holds::Column::Resolution.ne("dismissed")),
        )
        .count(db)
        .await?;
    if (n as usize) < cfg.flood_holds {
        return Ok(());
    }
    let Some(user) = users::Entity::find_by_id(user_id).one(db).await? else { return Ok(()) };
    if user.is_staff {
        return Ok(());
    }
    let why = format!(
        "Automatic: {n} posts held for review within {}; read-only for {} while staff look",
        crate::lameness::human_duration(cfg.flood_window),
        crate::lameness::human_duration(cfg.flood_cooldown)
    );
    cooldown(db, &user, cfg.flood_cooldown, &why).await
}

/// Staff clear a user's strikes (the holds stay, as history).
pub async fn clear_strikes(db: &DatabaseConnection, actor: Actor<'_>, user_id: Uuid) -> ActionResult<u64> {
    actor.require_staff()?;
    let user = users::Entity::find_by_id(user_id).one(db).await?.ok_or(ActionError::NotFound)?;
    let r = post_holds::Entity::update_many()
        .col_expr(post_holds::Column::StrikeClearedAt, Expr::value(DateTime::<FixedOffset>::from(Utc::now())))
        .filter(post_holds::Column::UserId.eq(user_id))
        .filter(post_holds::Column::Resolution.eq("upheld"))
        .filter(post_holds::Column::StrikeClearedAt.is_null())
        .exec(db)
        .await?;
    log(db, actor, "clear_strikes", "user", Some(user.id), &user_label(&user), Some(&format!("{} strike(s)", r.rows_affected))).await;
    Ok(r.rows_affected)
}

/// A flagger's record: flags staff upheld, dismissed, and still pending.
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
pub struct FlaggerRecord {
    pub upheld: u64,
    pub dismissed: u64,
    pub pending: u64,
}

pub async fn flagger_record(db: &DatabaseConnection, user_id: Uuid) -> Result<FlaggerRecord, DbErr> {
    let rows: Vec<Option<String>> = post_flags::Entity::find()
        .select_only()
        .column(post_flags::Column::Resolution)
        .filter(post_flags::Column::UserId.eq(user_id))
        .into_tuple()
        .all(db)
        .await?;
    let mut r = FlaggerRecord::default();
    for res in rows {
        match res.as_deref() {
            Some("upheld") => r.upheld += 1,
            Some("dismissed") => r.dismissed += 1,
            _ => r.pending += 1,
        }
    }
    Ok(r)
}

// --- users ------------------------------------------------------------------

/// What can be done to an account.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sanction {
    Silence,
    Suspend,
}

fn target_ok(actor: &Actor<'_>, target: &users::Model) -> ActionResult<()> {
    if target.is_staff {
        return Err(ActionError::Forbidden {
            code: "staff",
            message: "Staff accounts can't be sanctioned; remove their staff rights first.".into(),
        });
    }
    if actor.id() == Some(target.id) {
        return Err(ActionError::Forbidden { code: "self", message: "You can't sanction yourself.".into() });
    }
    Ok(())
}

/// Silence or suspend `target` until `until` (None = until lifted). A
/// suspension also signs them out everywhere: sessions and device tokens.
pub async fn sanction(
    db: &DatabaseConnection,
    actor: Actor<'_>,
    target_id: Uuid,
    kind: Sanction,
    reason: Option<&str>,
    until: Option<DateTime<Utc>>,
) -> ActionResult<users::Model> {
    actor.require_staff()?;
    let target = users::Entity::find_by_id(target_id).one(db).await?.ok_or(ActionError::NotFound)?;
    target_ok(&actor, &target)?;
    if until.is_some_and(|u| u <= Utc::now()) {
        return Err(ActionError::Invalid("The end time has to be in the future.".into()));
    }
    if kind == Sanction::Silence {
        // A cooldown: always timed, at most MAX_COOLDOWN_DAYS, and the person
        // is told why.
        let max = Utc::now() + chrono::Duration::days(crate::policy::MAX_COOLDOWN_DAYS) + chrono::Duration::minutes(1);
        match until {
            None => return Err(ActionError::Invalid("A cooldown needs an end (at most 90 days).".into())),
            Some(u) if u > max => {
                return Err(ActionError::Invalid(format!(
                    "A cooldown is at most {} days; suspend for longer.",
                    crate::policy::MAX_COOLDOWN_DAYS
                )))
            }
            _ => {}
        }
        if clean(reason).is_none() {
            return Err(ActionError::Invalid("A cooldown needs a reason; they see it.".into()));
        }
    }
    let now: DateTime<FixedOffset> = Utc::now().into();
    let until = until.map(DateTime::<FixedOffset>::from);
    let label = user_label(&target);
    let mut am: users::ActiveModel = target.into();
    match kind {
        Sanction::Silence => {
            am.silenced_at = Set(Some(now));
            am.silenced_until = Set(until);
            am.silence_reason = Set(clean(reason));
        }
        Sanction::Suspend => {
            am.suspended_at = Set(Some(now));
            am.suspended_until = Set(until);
            am.suspend_reason = Set(clean(reason));
        }
    }
    am.updated_at = Set(now);
    let user = am.update(db).await?;
    if kind == Sanction::Suspend {
        user_sessions::Entity::delete_many().filter(user_sessions::Column::UserId.eq(user.id)).exec(db).await?;
        api_tokens::Entity::delete_many().filter(api_tokens::Column::UserId.eq(user.id)).exec(db).await?;
    }
    let action = match kind {
        Sanction::Silence => "silence_user",
        Sanction::Suspend => "suspend_user",
    };
    let reason = match until {
        Some(u) => format!("{} (until {})", clean(reason).unwrap_or_else(|| "no reason given".into()), u.format("%Y-%m-%d %H:%M UTC")),
        None => clean(reason).unwrap_or_else(|| "no reason given".into()),
    };
    log(db, actor, action, "user", Some(user.id), &label, Some(&reason)).await;
    Ok(user)
}

/// Lift a silence or suspension.
pub async fn lift(db: &DatabaseConnection, actor: Actor<'_>, target_id: Uuid, kind: Sanction) -> ActionResult<users::Model> {
    actor.require_staff()?;
    let target = users::Entity::find_by_id(target_id).one(db).await?.ok_or(ActionError::NotFound)?;
    let label = user_label(&target);
    let mut am: users::ActiveModel = target.into();
    match kind {
        Sanction::Silence => {
            am.silenced_at = Set(None);
            am.silenced_until = Set(None);
            am.silence_reason = Set(None);
        }
        Sanction::Suspend => {
            am.suspended_at = Set(None);
            am.suspended_until = Set(None);
            am.suspend_reason = Set(None);
        }
    }
    am.updated_at = Set(Utc::now().into());
    let user = am.update(db).await?;
    let action = match kind {
        Sanction::Silence => "unsilence_user",
        Sanction::Suspend => "unsuspend_user",
    };
    log(db, actor, action, "user", Some(user.id), &label, None).await;
    Ok(user)
}

/// Flag shadowban on or off: the user's flags stop (or start again)
/// counting toward the auto-hide and surfacing in the queue. They aren't
/// told.
pub async fn set_flags_ignored(
    db: &DatabaseConnection,
    actor: Actor<'_>,
    target_id: Uuid,
    ignored: bool,
    reason: Option<&str>,
) -> ActionResult<users::Model> {
    actor.require_staff()?;
    let target = users::Entity::find_by_id(target_id).one(db).await?.ok_or(ActionError::NotFound)?;
    if ignored {
        target_ok(&actor, &target)?;
    }
    if target.flags_ignored_at.is_some() == ignored {
        return Ok(target);
    }
    let label = user_label(&target);
    let mut am: users::ActiveModel = target.into();
    am.flags_ignored_at = Set(ignored.then(|| Utc::now().into()));
    let user = am.update(db).await?;
    log(db, actor, if ignored { "flag_shadowban" } else { "flag_unshadowban" }, "user", Some(user.id), &label, reason).await;
    Ok(user)
}

/// Look a user up by username (the CLI and the admin forms).
pub async fn find_user(db: &DatabaseConnection, username: &str) -> ActionResult<users::Model> {
    users::Entity::find()
        .filter(users::Column::Username.eq(username))
        .one(db)
        .await?
        .ok_or(ActionError::NotFound)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rev(n: i32, kind: &str) -> post_revisions::Model {
        post_revisions::Model {
            id: Uuid::now_v7(),
            post_id: Uuid::nil(),
            editor_id: None,
            revision_number: n,
            raw: String::new(),
            cooked: String::new(),
            created_at: Utc::now().into(),
            kind: kind.into(),
            hidden_at: None,
            hidden_by_id: None,
        }
    }

    #[test]
    fn what_a_moderation_replaced() {
        let revs = [rev(1, "edit"), rev(2, "edit"), rev(3, "moderation")];
        let n: Vec<i32> = pre_moderation(&revs).iter().map(|r| r.revision_number).collect();
        assert_eq!(n, [1, 2]);
        // Moderated twice: both notes stay visible; the body before is hidden.
        let revs = [rev(1, "edit"), rev(2, "moderation"), rev(3, "moderation")];
        let n: Vec<i32> = pre_moderation(&revs).iter().map(|r| r.revision_number).collect();
        assert_eq!(n, [1]);
        // Restored, then moderated again: the restore counts as a body.
        let revs = [rev(1, "edit"), rev(2, "moderation"), rev(3, "restore"), rev(4, "moderation")];
        let n: Vec<i32> = pre_moderation(&revs).iter().map(|r| r.revision_number).collect();
        assert_eq!(n, [1, 3]);
        assert!(pre_moderation(&[rev(1, "edit")]).is_empty());
    }
}