36.3 KiB · text History 6e34613
//! Staff pages: the flag queue (`/admin/flags`), users and their sanctions
//! (`/admin/users`), and the moderation log (`/admin/log`). Each is a table
//! in Classic and cards in Focus, like the other admin pages; actions are
//! inline (htmx swaps the item they act on). The rules are
//! `crate::moderation`'s.
use std::collections::HashMap;

use axum::extract::{Form, Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use chrono::{Duration, Utc};
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use tracing::error;
use uuid::Uuid;

use super::focus::{view_for, ViewMode};
use super::render;
use crate::entities::{moderation_log, post_flags, posts, topics, users};
use crate::middleware::UserContext;
use crate::moderation::{self, Actor, FlagCounts, FlaggerRecord, Sanction};
use crate::policy::{self, FlagThreshold};
use crate::timeutil::{abs, rel};
use crate::AppState;

fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
    move |e| {
        error!(error = %e, "{ctx}");
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

fn require_staff(u: &UserContext) -> Result<(), StatusCode> {
    if u.user.is_staff {
        Ok(())
    } else {
        Err(StatusCode::FORBIDDEN)
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct ViewQuery {
    pub view: Option<String>,
    /// `/admin/users?q=` and `/admin/log?q=`: filter.
    pub q: Option<String>,
    /// `/admin/flags?author=` / `?flagger=`, `/admin/log?user=`: one user's.
    pub author: Option<Uuid>,
    pub flagger: Option<Uuid>,
    pub user: Option<Uuid>,
}

/// Times a user has been silenced or suspended (from the log).
async fn sanction_count(state: &AppState, user_id: Uuid) -> Result<u64, StatusCode> {
    moderation_log::Entity::find()
        .filter(moderation_log::Column::TargetId.eq(user_id))
        .filter(moderation_log::Column::Action.is_in(["silence_user", "suspend_user"]))
        .count(state.db.as_ref())
        .await
        .map_err(ise("count sanctions"))
}

// --- the flag queue ---------------------------------------------------------

/// One flag, for staff.
#[derive(Serialize, Clone)]
pub struct FlagRow {
    pub flagger: String,
    pub flagger_id: Uuid,
    pub reason: String,
    pub reason_label: &'static str,
    pub note: Option<String>,
    pub created_rel: String,
    pub created_abs: String,
    /// The flagger is flag-shadowbanned: recorded, not counted.
    pub ignored: bool,
    /// Their record: upheld / dismissed / pending.
    pub record: FlaggerRecord,
}

/// A flagged post in the queue.
#[derive(Serialize)]
pub struct QueueItem {
    pub post_id: Uuid,
    pub post_number: i32,
    pub topic_id: Uuid,
    pub topic_title: String,
    pub topic_locked: bool,
    pub author: String,
    pub author_id: Uuid,
    pub author_staff: bool,
    pub author_silenced: Option<String>,
    pub author_suspended: Option<String>,
    /// At a glance: trust level, account age, past sanctions, and their own
    /// record as a flagger.
    pub author_trust: i32,
    pub author_age: String,
    pub author_sanctions: u64,
    pub author_record: FlaggerRecord,
    pub author_flags_ignored: bool,
    /// Other accounts seen at any of the author's addresses (the addresses
    /// themselves are behind a logged lookup).
    pub author_shared_ip: i64,
    pub cooked: String,
    pub deleted: bool,
    pub moderated: bool,
    pub hidden: bool,
    /// Counted flags, and those from shadowbanned flaggers (collapsed).
    pub flags: Vec<FlagRow>,
    pub ignored_flags: Vec<FlagRow>,
    pub reasons: Vec<(String, usize)>,
    /// The auto-hide's inputs: counted flaggers, readers, their share.
    pub counts: FlagCounts,
    pub share_pct: String,
    pub would_hide: bool,
    /// Resolved since the page loaded (the swapped-in stub).
    pub resolved: Option<String>,
    /// The lameness filter's pending hold: a system flag.
    pub hold: Option<HoldView>,
    /// The author's lameness record (strikes, false positives).
    pub author_holds: moderation::HoldRecord,
}

#[derive(Serialize)]
pub struct HoldView {
    pub reasons: Vec<String>,
    /// Every measurement: (signal, value, tripped).
    pub scores: Vec<(String, String, bool)>,
    pub created_rel: String,
    pub created_abs: String,
}

fn hold_view(h: crate::entities::post_holds::Model) -> HoldView {
    let scores = serde_json::from_str::<Vec<serde_json::Value>>(&h.scores)
        .unwrap_or_default()
        .into_iter()
        .map(|v| {
            (
                v["name"].as_str().unwrap_or_default().replace('_', " "),
                v["value"].as_str().unwrap_or_default().to_string(),
                !v["reason"].is_null(),
            )
        })
        .collect();
    HoldView {
        reasons: h.reason_list(),
        scores,
        created_rel: rel(h.created_at),
        created_abs: abs(h.created_at),
    }
}

/// A post's pending flags, for the moderation form.
pub async fn pending_flags_for(state: &AppState, post_id: Uuid) -> Result<Vec<FlagRow>, StatusCode> {
    let rows = post_flags::Entity::find()
        .filter(post_flags::Column::PostId.eq(post_id))
        .filter(post_flags::Column::ResolvedAt.is_null())
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load flags"))?;
    flag_rows(state, rows).await
}

async fn flag_rows(
    state: &AppState,
    rows: Vec<(post_flags::Model, Option<users::Model>)>,
) -> Result<Vec<FlagRow>, StatusCode> {
    let mut records: HashMap<Uuid, FlaggerRecord> = HashMap::new();
    let mut out = Vec::with_capacity(rows.len());
    for (f, u) in rows {
        let record = match records.get(&f.user_id) {
            Some(r) => *r,
            None => {
                let r = moderation::flagger_record(state.db.as_ref(), f.user_id).await.map_err(ise("flag record"))?;
                records.insert(f.user_id, r);
                r
            }
        };
        out.push(FlagRow {
            flagger: u.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".into()),
            flagger_id: f.user_id,
            reason_label: policy::flag_reason_label(&f.reason),
            reason: f.reason,
            note: f.note,
            created_rel: rel(f.created_at),
            created_abs: abs(f.created_at),
            ignored: u.as_ref().is_some_and(|u| u.flags_ignored_at.is_some()),
            record,
        });
    }
    Ok(out)
}

async fn queue_item(state: &AppState, post: posts::Model) -> Result<QueueItem, StatusCode> {
    let db = state.db.as_ref();
    let topic = topics::Entity::find_by_id(post.topic_id).one(db).await.map_err(ise("load topic"))?;
    let author = users::Entity::find_by_id(post.user_id).one(db).await.map_err(ise("load author"))?;
    let flags = pending_flags_for(state, post.id).await?;
    let (ignored_flags, flags): (Vec<FlagRow>, Vec<FlagRow>) = flags.into_iter().partition(|f| f.ignored);
    let mut reasons: Vec<(String, usize)> = Vec::new();
    for f in &flags {
        match reasons.iter_mut().find(|(l, _)| l == f.reason_label) {
            Some((_, n)) => *n += 1,
            None => reasons.push((f.reason_label.to_string(), 1)),
        }
    }
    let counts = moderation::flag_counts(db, &post).await.map_err(ise("flag counts"))?;
    let t = state.config.flag_threshold;
    let hold = moderation::pending_hold(db, post.id).await.map_err(ise("load hold"))?.map(hold_view);
    let author_holds = moderation::hold_record(db, &state.config.lameness, post.user_id).await.map_err(ise("hold record"))?;
    Ok(QueueItem {
        post_id: post.id,
        post_number: post.post_number,
        topic_id: post.topic_id,
        topic_title: topic.as_ref().map(|t| t.title.clone()).unwrap_or_default(),
        topic_locked: topic.as_ref().is_some_and(|t| t.is_closed),
        author: author.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".into()),
        author_id: post.user_id,
        author_staff: author.as_ref().is_some_and(|u| u.is_staff),
        author_silenced: author.as_ref().and_then(policy::silence).map(|s| format!("read-only{}", s.until_text())),
        author_suspended: author.as_ref().and_then(policy::suspension).map(|s| format!("suspended{}", s.until_text())),
        author_trust: author.as_ref().map(|u| u.trust_level).unwrap_or(0),
        author_age: author.as_ref().map(|u| rel(u.created_at)).unwrap_or_default(),
        author_sanctions: sanction_count(state, post.user_id).await?,
        author_record: moderation::flagger_record(db, post.user_id).await.map_err(ise("author record"))?,
        author_flags_ignored: author.as_ref().is_some_and(|u| u.flags_ignored_at.is_some()),
        author_shared_ip: crate::ips::others_sharing(db, post.user_id).await.map_err(ise("shared addresses"))?,
        cooked: crate::links::Links::from_config(&state.config).display(&post.cooked, false),
        deleted: post.deleted_at.is_some(),
        moderated: post.moderated_at.is_some(),
        hidden: post.hidden_at.is_some(),
        flags,
        ignored_flags,
        reasons,
        share_pct: format!("{:.0}%", FlagThreshold::share(counts.flaggers, counts.readers) * 100.0),
        would_hide: t.should_hide(counts.flaggers, counts.readers),
        counts,
        resolved: None,
        hold,
        author_holds,
    })
}

/// Every post with pending flags: those with counted flags first (hidden
/// ones first, then most flagged), and apart, those flagged only by
/// shadowbanned flaggers.
async fn queue(
    state: &AppState,
    author: Option<Uuid>,
    flagger: Option<Uuid>,
) -> Result<(Vec<QueueItem>, Vec<QueueItem>), StatusCode> {
    let mut find = post_flags::Entity::find()
        .select_only()
        .column(post_flags::Column::PostId)
        .distinct()
        .filter(post_flags::Column::ResolvedAt.is_null());
    if let Some(f) = flagger {
        find = find.filter(post_flags::Column::UserId.eq(f));
    }
    let mut ids: Vec<Uuid> = find
        .into_tuple()
        .all(state.db.as_ref())
        .await
        .map_err(ise("load queue"))?;
    // Lameness holds are the system's flags (not when filtering by a flagger).
    if flagger.is_none() {
        let held: Vec<Uuid> = crate::entities::post_holds::Entity::find()
            .select_only()
            .column(crate::entities::post_holds::Column::PostId)
            .filter(crate::entities::post_holds::Column::ResolvedAt.is_null())
            .into_tuple()
            .all(state.db.as_ref())
            .await
            .map_err(ise("load holds"))?;
        ids.extend(held);
        ids.sort();
        ids.dedup();
    }
    let mut find = posts::Entity::find().filter(posts::Column::Id.is_in(ids));
    if let Some(a) = author {
        find = find.filter(posts::Column::UserId.eq(a));
    }
    let posts = find
        .all(state.db.as_ref())
        .await
        .map_err(ise("load flagged posts"))?;
    let mut items = Vec::with_capacity(posts.len());
    for p in posts {
        items.push(queue_item(state, p).await?);
    }
    items.sort_by(|a, b| b.hidden.cmp(&a.hidden).then(b.flags.len().cmp(&a.flags.len())));
    Ok(items.into_iter().partition(|i| !i.flags.is_empty() || i.hold.is_some()))
}

/// `/admin/flags`
pub async fn flags_page(
    State(state): State<AppState>,
    Query(q): Query<ViewQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let (items, shadow) = queue(&state, q.author, q.flagger).await?;
    let t = state.config.flag_threshold;
    let filter_user = match q.author.or(q.flagger) {
        Some(id) => users::Entity::find_by_id(id).one(state.db.as_ref()).await.map_err(ise("load filter user"))?,
        None => None,
    };
    let filter = filter_user.map(|u| context! {
        username => u.username, id => u.id, role => if q.author.is_some() { "author" } else { "flagger" },
    });
    let page = render(
        &state,
        if view.mode == ViewMode::Focus { "admin/flags_focus.html" } else { "admin/flags.html" },
        context! {
            title => "Flags",
            app_name => state.config.app_name,
            user => user.user,
            items => items,
            shadow => shadow,
            mode => view.mode.as_str(),
            filter => filter,
            nav => "flags",
            threshold => context! { ratio_pct => format!("{:.0}%", t.ratio * 100.0), min_flags => t.min_flags, enough_flags => t.enough_flags },
            durations => DURATIONS, cooldowns => COOLDOWNS,
        },
    )?;
    Ok(view.respond(page))
}

/// What a queue action answers with: the item again (htmx), or the queue.
async fn queue_response(state: &AppState, post_id: Uuid, mode: Option<&str>, resolved: Option<&str>) -> Result<Response, StatusCode> {
    let post = posts::Entity::find_by_id(post_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("reload post"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    let mut item = queue_item(state, post).await?;
    item.resolved = resolved.map(str::to_string);
    let focus = mode == Some("focus");
    Ok(render(
        state,
        if focus { "admin/_flag_card.html" } else { "admin/_flag_row.html" },
        context! { item => item, mode => if focus { "focus" } else { "classic" }, durations => DURATIONS, cooldowns => COOLDOWNS },
    )?
    .into_response())
}

#[derive(Debug, Default, Deserialize)]
pub struct QueueForm {
    pub mode: Option<String>,
    pub reason: Option<String>,
    pub note: Option<String>,
    pub hide_original: Option<String>,
}

/// Dismiss a post's flags (and show it again if they hid it).
pub async fn flags_dismiss(
    State(state): State<AppState>,
    Path(post_id): Path<Uuid>,
    user: UserContext,
    Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
    moderation::dismiss_flags(&state, Actor::web(&user.user), post_id).await?;
    queue_response(&state, post_id, f.mode.as_deref(), Some("Flags dismissed")).await
}

/// Delete the post (upholds its flags).
pub async fn flags_delete(
    State(state): State<AppState>,
    Path(post_id): Path<Uuid>,
    user: UserContext,
    Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    moderation::delete_post(&state, Actor::web(&user.user), post_id).await?;
    queue_response(&state, post_id, f.mode.as_deref(), Some("Post deleted, flags upheld")).await
}

/// Replace the post with a staff note (upholds its flags).
pub async fn flags_moderate(
    State(state): State<AppState>,
    Path(post_id): Path<Uuid>,
    user: UserContext,
    Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
    moderation::moderate_post(
        &state,
        Actor::web(&user.user),
        post_id,
        f.note.as_deref().unwrap_or(""),
        f.hide_original.is_some(),
    )
    .await?;
    queue_response(&state, post_id, f.mode.as_deref(), Some("Post moderated, flags upheld")).await
}

/// Lock the post's topic (the flags stay pending: a lock doesn't decide them).
pub async fn flags_lock(
    State(state): State<AppState>,
    Path(post_id): Path<Uuid>,
    user: UserContext,
    Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let post = posts::Entity::find_by_id(post_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load post"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    moderation::set_locked(&state, Actor::web(&user.user), post.topic_id, true, f.reason.as_deref()).await?;
    queue_response(&state, post_id, f.mode.as_deref(), None).await
}

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

/// The sanction lengths offered (`duration` field): label, hours (0 =
/// until lifted).
/// Suspension lengths.
pub const DURATIONS: [(&str, &str); 6] =
    [("1h", "1 hour"), ("24h", "1 day"), ("72h", "3 days"), ("168h", "1 week"), ("720h", "30 days"), ("", "Until lifted")];

/// Cooldown (read-only) presets: always timed, at most 90 days
/// (`policy::MAX_COOLDOWN_DAYS`, enforced in `moderation::sanction`), plus
/// `custom` (the form's `custom` field, e.g. `5d`, `12h`, `2w`).
pub const COOLDOWNS: [(&str, &str); 7] = [
    ("1h", "1 hour"),
    ("24h", "1 day"),
    ("72h", "3 days"),
    ("168h", "7 days"),
    ("720h", "30 days"),
    ("2160h", "90 days"),
    ("custom", "Custom…"),
];

/// A length: `<n>h`, `<n>d` or `<n>w`.
pub fn parse_length(v: &str) -> Option<Duration> {
    let v = v.trim();
    if v.len() < 2 {
        return None;
    }
    let (n, unit) = v.split_at(v.len() - 1);
    let n: i64 = n.trim().parse().ok().filter(|n| *n > 0)?;
    match unit {
        "h" => Some(Duration::hours(n)),
        "d" => Some(Duration::days(n)),
        "w" => Some(Duration::weeks(n)),
        _ => None,
    }
}

/// "24h" → 24 hours from now; blank → None (until lifted); `custom` takes
/// the custom field.
pub fn parse_duration(s: Option<&str>) -> Result<Option<chrono::DateTime<Utc>>, StatusCode> {
    parse_choice(s, None)
}

fn parse_choice(s: Option<&str>, custom: Option<&str>) -> Result<Option<chrono::DateTime<Utc>>, StatusCode> {
    match s.map(str::trim) {
        None | Some("") => Ok(None),
        Some("custom") => {
            parse_length(custom.unwrap_or_default()).map(|d| Some(Utc::now() + d)).ok_or(StatusCode::BAD_REQUEST)
        }
        Some(v) => parse_length(v).map(|d| Some(Utc::now() + d)).ok_or(StatusCode::BAD_REQUEST),
    }
}

/// A user, for staff.
#[derive(Serialize)]
pub struct UserRow {
    pub id: Uuid,
    pub username: String,
    pub email: String,
    pub is_staff: bool,
    pub is_active: bool,
    pub trust_level: i32,
    pub joined: String,
    pub silenced: Option<String>,
    pub suspended: Option<String>,
    pub flags_ignored: bool,
    pub record: FlaggerRecord,
    /// Flags on their posts staff upheld.
    pub flagged_upheld: u64,
    /// Lameness strikes and the next ladder step.
    pub holds: moderation::HoldRecord,
}

async fn user_row(state: &AppState, u: users::Model) -> Result<UserRow, StatusCode> {
    let record = moderation::flagger_record(state.db.as_ref(), u.id).await.map_err(ise("flag record"))?;
    let flagged_upheld = post_flags::Entity::find()
        .filter(post_flags::Column::Resolution.eq("upheld"))
        .inner_join(posts::Entity)
        .filter(posts::Column::UserId.eq(u.id))
        .count(state.db.as_ref())
        .await
        .map_err(ise("count upheld"))?;
    let reason = |r: &Option<String>| r.as_ref().map(|r| format!(": {r}")).unwrap_or_default();
    Ok(UserRow {
        silenced: policy::silence(&u).map(|s| format!("Read-only{}{}", s.until_text(), reason(&s.reason))),
        suspended: policy::suspension(&u).map(|s| format!("Suspended{}{}", s.until_text(), reason(&s.reason))),
        flags_ignored: u.flags_ignored_at.is_some(),
        id: u.id,
        username: u.username,
        email: u.email,
        is_staff: u.is_staff,
        is_active: u.is_active,
        trust_level: u.trust_level,
        joined: rel(u.created_at),
        record,
        flagged_upheld,
        holds: moderation::hold_record(state.db.as_ref(), &state.config.lameness, u.id).await.map_err(ise("hold record"))?,
    })
}

/// `/admin/users?q=`
pub async fn users_page(
    State(state): State<AppState>,
    Query(q): Query<ViewQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let mut find = users::Entity::find().order_by_asc(users::Column::Username);
    let search = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());
    if let Some(s) = search {
        find = find.filter(
            Condition::any()
                .add(users::Column::Username.contains(s))
                .add(users::Column::Email.contains(s)),
        );
    }
    let all = find.limit(200).all(state.db.as_ref()).await.map_err(ise("load users"))?;
    let mut rows = Vec::with_capacity(all.len());
    for u in all {
        rows.push(user_row(&state, u).await?);
    }
    let page = render(
        &state,
        if view.mode == ViewMode::Focus { "admin/users_focus.html" } else { "admin/users.html" },
        context! {
            title => "Users",
            app_name => state.config.app_name,
            user => user.user,
            users => rows,
            nav => "users",
            q => search,
            mode => view.mode.as_str(),
            durations => DURATIONS, cooldowns => COOLDOWNS,
        },
    )?;
    Ok(view.respond(page))
}

/// `/admin/users/{id}`: one user, with their sanctions controls, their
/// flags (as author and as flagger) and their moderation-log entries.
pub async fn user_page(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Query(q): Query<ViewQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let target = users::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load user"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    let row = user_row(&state, target).await?;
    let raised = post_flags::Entity::find()
        .filter(post_flags::Column::UserId.eq(id))
        .order_by_desc(post_flags::Column::CreatedAt)
        .limit(50)
        .find_also_related(posts::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load raised flags"))?;
    let received = post_flags::Entity::find()
        .inner_join(posts::Entity)
        .filter(posts::Column::UserId.eq(id))
        .order_by_desc(post_flags::Column::CreatedAt)
        .limit(50)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load received flags"))?;
    let flag_ctx = |f: &post_flags::Model, who: String, post: Option<Uuid>| context! {
        reason => policy::flag_reason_label(&f.reason), note => f.note.clone(), when => rel(f.created_at),
        status => f.resolution.clone().unwrap_or_else(|| "pending".into()), who => who, post_id => post.unwrap_or(f.post_id),
    };
    let raised: Vec<minijinja::Value> =
        raised.iter().map(|(f, _)| flag_ctx(f, String::new(), None)).collect();
    let received: Vec<minijinja::Value> = received
        .iter()
        .map(|(f, u)| flag_ctx(f, u.as_ref().map(|u| u.username.clone()).unwrap_or_default(), None))
        .collect();
    let log = log_rows(
        &state,
        moderation_log::Entity::find()
            .filter(Condition::any().add(moderation_log::Column::ActorId.eq(id)).add(moderation_log::Column::TargetId.eq(id)))
            .order_by_desc(moderation_log::Column::CreatedAt)
            .limit(30),
    )
    .await?;
    let page = render(&state, "admin/user.html", context! {
        title => format!("@{}", row.username),
        app_name => state.config.app_name,
        user => user.user,
        u => row,
        shared_ip => crate::ips::others_sharing(state.db.as_ref(), id).await.map_err(ise("shared addresses"))?,
        raised => raised,
        received => received,
        log => log,
        nav => "users",
        // The card's actions answer with a card.
        mode => "focus",
        durations => DURATIONS, cooldowns => COOLDOWNS,
    })?;
    Ok(view.respond(page))
}

#[derive(Debug, Default, Deserialize)]
pub struct SanctionForm {
    pub reason: Option<String>,
    /// See [`DURATIONS`].
    pub duration: Option<String>,
    /// With `duration=custom`: `<n>h`, `<n>d` or `<n>w`.
    pub custom: Option<String>,
    /// `classic` / `focus`: which fragment to answer with.
    pub mode: Option<String>,
    /// Acting from the queue: answer with this post's queue item.
    pub post: Option<Uuid>,
}

async fn user_response(state: &AppState, user_id: Uuid, f: &SanctionForm) -> Result<Response, StatusCode> {
    if let Some(post) = f.post {
        return queue_response(state, post, f.mode.as_deref(), None).await;
    }
    let u = users::Entity::find_by_id(user_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("reload user"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    let row = user_row(state, u).await?;
    let focus = f.mode.as_deref() == Some("focus");
    Ok(render(
        state,
        if focus { "admin/_user_card.html" } else { "admin/_user_row.html" },
        context! { u => row, mode => if focus { "focus" } else { "classic" }, durations => DURATIONS, cooldowns => COOLDOWNS },
    )?
    .into_response())
}

/// `POST /admin/users/{id}/{action}`: silence, suspend, unsilence,
/// unsuspend, flag-shadowban, flag-unshadowban, clear-strikes.
pub async fn user_action(
    State(state): State<AppState>,
    Path((id, action)): Path<(Uuid, String)>,
    user: UserContext,
    Form(f): Form<SanctionForm>,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let db = state.db.as_ref();
    let actor = Actor::web(&user.user);
    let reason = f.reason.as_deref();
    match action.as_str() {
        "silence" | "cooldown" => {
            let until = parse_choice(f.duration.as_deref(), f.custom.as_deref())?;
            moderation::sanction(db, actor, id, Sanction::Silence, reason, until).await?;
        }
        "suspend" => {
            moderation::sanction(db, actor, id, Sanction::Suspend, reason, parse_duration(f.duration.as_deref())?).await?;
        }
        "unsilence" | "end-cooldown" => {
            moderation::lift(db, actor, id, Sanction::Silence).await?;
        }
        "unsuspend" => {
            moderation::lift(db, actor, id, Sanction::Suspend).await?;
        }
        "flag-shadowban" => {
            moderation::set_flags_ignored(db, actor, id, true, reason).await?;
        }
        "flag-unshadowban" => {
            moderation::set_flags_ignored(db, actor, id, false, reason).await?;
        }
        "clear-strikes" => {
            moderation::clear_strikes(db, actor, id).await?;
        }
        _ => return Err(StatusCode::NOT_FOUND),
    }
    user_response(&state, id, &f).await
}

// --- the log ----------------------------------------------------------------

#[derive(Serialize)]
pub struct LogRow {
    pub actor_id: Option<Uuid>,
    pub target_user_id: Option<Uuid>,
    pub when: String,
    pub when_abs: String,
    pub actor: String,
    pub source: String,
    pub action: String,
    pub action_label: &'static str,
    pub target_kind: String,
    pub target_label: String,
    pub target_href: Option<String>,
    pub reason: Option<String>,
}

/// A person's words for a log action.
pub fn action_label(a: &str) -> &'static str {
    match a {
        "lock_topic" => "Locked topic",
        "unlock_topic" => "Unlocked topic",
        "pin_topic" => "Pinned topic",
        "unpin_topic" => "Unpinned topic",
        "delete_topic" => "Deleted topic",
        "restore_topic" => "Restored topic",
        "delete_post" => "Deleted post",
        "restore_post" => "Restored post",
        "moderate_post" => "Moderated post",
        "hide_original" => "Hid original",
        "unhide_original" => "Showed original",
        "restore_post_body" => "Restored post body",
        "auto_hide" => "Auto-hid post",
        "dismiss_flags" => "Dismissed flags",
        "silence_user" => "Cooldown (read-only)",
        "unsilence_user" => "Ended cooldown",
        "suspend_user" => "Suspended",
        "unsuspend_user" => "Lifted suspension",
        "flag_shadowban" => "Ignored flags",
        "flag_unshadowban" => "Counted flags again",
        "category_permissions" => "Changed category permissions",
        "lameness_hold" => "Held post (lameness)",
        "lameness_strike" => "Lameness strike",
        "clear_strikes" => "Cleared strikes",
        "view_ips" => "Viewed addresses of",
        "ip_lookup" => "Looked up address",
        _ => "Other",
    }
}

/// `/admin/log?q=` (q filters action, target or reason).
pub async fn log_page(
    State(state): State<AppState>,
    Query(q): Query<ViewQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let mut find = moderation_log::Entity::find().order_by_desc(moderation_log::Column::CreatedAt);
    if let Some(u) = q.user {
        find = find.filter(
            Condition::any().add(moderation_log::Column::ActorId.eq(u)).add(moderation_log::Column::TargetId.eq(u)),
        );
    }
    let search = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());
    if let Some(s) = search {
        find = find.filter(
            Condition::any()
                .add(moderation_log::Column::Action.contains(s))
                .add(moderation_log::Column::TargetLabel.contains(s))
                .add(moderation_log::Column::Reason.contains(s)),
        );
    }
    let entries = log_rows(&state, find.limit(300)).await?;
    let filter_user = match q.user {
        Some(id) => users::Entity::find_by_id(id).one(state.db.as_ref()).await.map_err(ise("load filter user"))?,
        None => None,
    };
    let page = render(
        &state,
        if view.mode == ViewMode::Focus { "admin/log_focus.html" } else { "admin/log.html" },
        context! {
            title => "Moderation log",
            app_name => state.config.app_name,
            user => user.user,
            entries => entries,
            q => search,
            nav => "log",
            filter => filter_user.map(|u| context! { username => u.username, id => u.id }),
        },
    )?;
    Ok(view.respond(page))
}

async fn log_rows(state: &AppState, find: Select<moderation_log::Entity>) -> Result<Vec<LogRow>, StatusCode> {
    let rows = find.all(state.db.as_ref()).await.map_err(ise("load log"))?;
    let actor_ids: Vec<Uuid> = rows.iter().filter_map(|r| r.actor_id).collect();
    let names: HashMap<Uuid, String> = users::Entity::find()
        .filter(users::Column::Id.is_in(actor_ids))
        .all(state.db.as_ref())
        .await
        .map_err(ise("load actors"))?
        .into_iter()
        .map(|u| (u.id, u.username))
        .collect();
    Ok(rows
        .into_iter()
        .map(|r| LogRow {
            actor_id: r.actor_id,
            target_user_id: (r.target_kind == "user").then_some(r.target_id).flatten(),
            when: rel(r.created_at),
            when_abs: abs(r.created_at),
            actor: match (r.actor_id.and_then(|id| names.get(&id)), r.source.as_str()) {
                (Some(n), _) => n.clone(),
                (None, "system") => "system".into(),
                (None, "cli") => "operator (CLI)".into(),
                (None, _) => "deleted account".into(),
            },
            action_label: action_label(&r.action),
            target_href: match (r.target_kind.as_str(), r.target_id) {
                ("ip", _) => Some(format!("/admin/ips/{}", r.target_label)),
                ("post", Some(id)) => Some(format!("/p/{id}")),
                ("topic", Some(id)) => Some(format!("/t/{id}")),
                ("user", Some(id)) => Some(format!("/admin/users/{id}")),
                (_, Some(id)) => Some(format!("/admin/categories/{id}/edit")),
                _ => None,
            },
            action: r.action,
            source: r.source,
            target_kind: r.target_kind,
            target_label: r.target_label,
            reason: r.reason,
        })
        .collect())
}

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

    #[test]
    fn durations_parse() {
        assert!(parse_duration(None).unwrap().is_none());
        assert!(parse_duration(Some("")).unwrap().is_none());
        let d = parse_duration(Some("24h")).unwrap().unwrap();
        assert!((d - Utc::now() - Duration::hours(24)).num_seconds().abs() < 5);
        assert!(parse_duration(Some("3d")).unwrap().is_some());
        assert!(parse_duration(Some("x")).is_err());
        for (v, _) in DURATIONS {
            assert!(parse_duration(Some(v)).is_ok());
        }
        for (v, _) in COOLDOWNS.iter().filter(|(v, _)| *v != "custom") {
            let end = parse_duration(Some(v)).unwrap().unwrap();
            assert!(end <= Utc::now() + Duration::days(crate::policy::MAX_COOLDOWN_DAYS));
        }
        let two_weeks = parse_choice(Some("custom"), Some("2w")).unwrap().unwrap();
        assert!((two_weeks - Utc::now() - Duration::days(14)).num_seconds().abs() < 5);
        assert!(parse_choice(Some("custom"), Some("")).is_err());
        assert!(parse_choice(Some("custom"), Some("-3d")).is_err());
    }
}

// --- client addresses (staff only; every lookup is logged) -------------------

#[derive(Serialize)]
pub struct SightingRow {
    pub user_id: Uuid,
    pub username: String,
    pub ip: String,
    pub first_seen: String,
    pub last_seen: String,
    pub last_seen_abs: String,
    pub count: i32,
    pub last_action: String,
    pub status: Option<String>,
}

fn sighting_row(s: crate::ips::Sighting) -> SightingRow {
    let now = Utc::now();
    let status = if s.is_staff {
        Some("staff".to_string())
    } else if s.suspended_at.is_some() && s.suspended_until.is_none_or(|u| u > now) {
        Some(format!("suspended{}", s.suspended_until.map(|u| format!(" until {}", u.format("%-d %b %Y"))).unwrap_or_default()))
    } else if s.silenced_at.is_some() && s.silenced_until.is_none_or(|u| u > now) {
        Some(format!("read-only{}", s.silenced_until.map(|u| format!(" until {}", u.format("%-d %b %Y"))).unwrap_or_default()))
    } else {
        None
    };
    SightingRow {
        user_id: s.user_id,
        username: s.username,
        ip: s.ip,
        first_seen: rel(s.first_seen.into()),
        last_seen: rel(s.last_seen.into()),
        last_seen_abs: crate::timeutil::abs(s.last_seen.into()),
        count: s.count,
        last_action: s.last_action,
        status,
    }
}

/// `GET /admin/users/{id}/ips` (htmx, from the user page): the account's
/// addresses, newest first, each with the other accounts seen there.
pub async fn user_ips(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let db = state.db.as_ref();
    let target = users::Entity::find_by_id(id).one(db).await.map_err(ise("load user"))?.ok_or(StatusCode::NOT_FOUND)?;
    let mine = crate::ips::of_user(db, id).await.map_err(ise("load addresses"))?;
    let mut rows = Vec::new();
    for s in mine {
        let others: Vec<SightingRow> = match s.ip.parse::<std::net::IpAddr>() {
            Ok(ip) => crate::ips::in_network(db, crate::client_ip::Cidr::network_of(ip, if ip.is_ipv4() { 32 } else { 128 }))
                .await
                .map_err(ise("load sharers"))?
                .into_iter()
                .filter(|o| o.user_id != id)
                .map(sighting_row)
                .collect(),
            Err(_) => Vec::new(),
        };
        rows.push(context! { at => sighting_row(s), others => others });
    }
    moderation::log(db, Actor::web(&user.user), "view_ips", "user", Some(id), &format!("@{}", target.username), None).await;
    Ok(render(&state, "admin/_user_ips.html", context! {
        rows => rows,
        retention_days => state.config.ip_retention_days,
    })?
    .into_response())
}

/// `GET /admin/ips/{ip}`: every account seen at an address, and in its /24
/// (IPv4) or /64 (IPv6). Logged.
pub async fn ip_page(
    State(state): State<AppState>,
    Path(raw): Path<String>,
    Query(q): Query<ViewQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let ip: std::net::IpAddr = raw.trim().parse().map_err(|_| StatusCode::NOT_FOUND)?;
    let ip = crate::client_ip::canonical(ip);
    let db = state.db.as_ref();
    let exact = crate::ips::in_network(db, crate::client_ip::Cidr::network_of(ip, if ip.is_ipv4() { 32 } else { 128 }))
        .await
        .map_err(ise("lookup address"))?;
    let net = crate::client_ip::Cidr::network_of(ip, if ip.is_ipv4() { 24 } else { 64 });
    let nearby: Vec<SightingRow> = crate::ips::in_network(db, net)
        .await
        .map_err(ise("lookup network"))?
        .into_iter()
        .filter(|s| s.ip != ip.to_string())
        .map(sighting_row)
        .collect();
    moderation::log(db, Actor::web(&user.user), "ip_lookup", "ip", None, &ip.to_string(), None).await;
    let page = render(&state, "admin/ip.html", context! {
        title => format!("Address {ip}"),
        app_name => state.config.app_name,
        user => user.user,
        ip => ip.to_string(),
        network => net.to_string(),
        exact => exact.into_iter().map(sighting_row).collect::<Vec<_>>(),
        nearby => nearby,
        nav => "users",
        retention_days => state.config.ip_retention_days,
    })?;
    Ok(view.respond(page))
}