10.3 KiB · text History a4db355
//! A post's own pages and actions: permalink, edit, delete/restore, history,
//! flag, and staff moderation (replace with a note, hide/unhide the earlier
//! versions, restore the body). The rules live in `crate::actions`,
//! `crate::moderation` and `crate::policy`.
use axum::{
    extract::{Form, Path, State},
    http::StatusCode,
    response::{Html, IntoResponse, Redirect, Response},
};
use axum_htmx::HxRequest;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use tracing::error;
use uuid::Uuid;

use crate::actions::{self, viewer};
use crate::entities::{post_revisions, posts, users};
use crate::middleware::UserContext;
use crate::moderation::{self, Actor};
use crate::AppState;

use super::render;

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

/// Insert a version row. Revision 1 is the original; edits append. `kind`
/// is `edit`, `moderation` or `restore`.
#[allow(clippy::too_many_arguments)]
pub async fn record_revision(
    db: &DatabaseConnection,
    post_id: Uuid,
    revision_number: i32,
    editor_id: Uuid,
    raw: &str,
    cooked: &str,
    at: chrono::DateTime<chrono::FixedOffset>,
    kind: &str,
) -> Result<post_revisions::Model, DbErr> {
    let rev = post_revisions::ActiveModel {
        id: Set(Uuid::now_v7()),
        post_id: Set(post_id),
        editor_id: Set(Some(editor_id)),
        revision_number: Set(revision_number),
        raw: Set(raw.to_string()),
        cooked: Set(cooked.to_string()),
        created_at: Set(at),
        kind: Set(kind.to_string()),
        hidden_at: Set(None),
        hidden_by_id: Set(None),
    };
    rev.insert(db).await
}

async fn load_post(state: &AppState, id: Uuid) -> Result<posts::Model, StatusCode> {
    posts::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load post"))?
        .ok_or(StatusCode::NOT_FOUND)
}

fn anchor(post: &posts::Model) -> String {
    format!("/t/{}#post-{}", post.topic_id, post.post_number)
}

/// Short, shareable permalink for a post — redirects to the post's anchor in
/// its topic so links survive even as the topic scrolls/grows.
pub async fn post_permalink(State(state): State<AppState>, Path(id): Path<Uuid>) -> Result<Redirect, StatusCode> {
    let post = load_post(&state, id).await?;
    Ok(Redirect::to(&anchor(&post)))
}

/// Render the edit form (author or staff; see [`actions::edit_block`]).
pub async fn edit_post_form(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    let (post, topic, _) = actions::visible_live_post(&state, viewer(&user.user), id).await?;
    if let Some(e) = actions::edit_block(&state, &user.user, &post, &topic) {
        return Err(e.into());
    }
    render(&state, "posts/edit.html", context! {
        title => "Edit post",
        app_name => state.config.app_name,
        user => user.user,
        post => post,
    })
}

#[derive(Debug, Deserialize)]
pub struct EditPostForm {
    pub body: String,
}

/// Apply an edit ([`actions::edit_post`]).
pub async fn update_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
    Form(form): Form<EditPostForm>,
) -> Result<Redirect, StatusCode> {
    let post = actions::edit_post(&state, &user.user, id, &form.body).await?;
    Ok(Redirect::to(&anchor(&post)))
}

/// Soft-delete a post (author or staff). The row stays as a tombstone.
pub async fn delete_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    let post = moderation::delete_post(&state, Actor::web(&user.user), id).await?;
    Ok(Redirect::to(&anchor(&post)))
}

/// Restore a soft-deleted post (staff only).
pub async fn restore_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    let post = moderation::restore_post(&state, Actor::web(&user.user), id).await?;
    Ok(Redirect::to(&anchor(&post)))
}

#[derive(Serialize)]
struct VersionRow {
    revision_number: i32,
    kind: String,
    /// None when hidden from this viewer.
    cooked: Option<String>,
    editor: String,
    editor_id: Option<Uuid>,
    created_at: String,
    created_at_abs: String,
    current: bool,
    /// Staff hid this version from non-staff (staff see it, marked).
    hidden: bool,
}

/// The edit history (transparency). Versions staff hid after moderating the
/// post read "hidden by staff" for everyone else; staff see them, marked,
/// and the controls to hide, show or restore.
pub async fn post_history(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
    let post = load_post(&state, id).await?;
    crate::handlers::forum::ensure_topic_visible(&state, post.topic_id, &user_context).await?;
    let is_staff = user_context.as_ref().is_some_and(|c| c.user.is_staff);

    let revs = post_revisions::Entity::find()
        .filter(post_revisions::Column::PostId.eq(post.id))
        .order_by_asc(post_revisions::Column::RevisionNumber)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load revisions"))?;

    let latest = revs.iter().map(|(r, _)| r.revision_number).max().unwrap_or(0);
    let any_hidden = revs.iter().any(|(r, _)| r.hidden_at.is_some());
    let versions = revs
        .into_iter()
        .map(|(r, editor)| {
            let hidden = r.hidden_at.is_some();
            VersionRow {
                revision_number: r.revision_number,
                kind: r.kind,
                cooked: (!hidden || is_staff).then_some(r.cooked),
                editor_id: editor.as_ref().map(|u| u.id),
                editor: editor.map(|u| u.username).unwrap_or_else(|| "unknown".to_string()),
                created_at: crate::timeutil::rel(r.created_at),
                created_at_abs: crate::timeutil::abs(r.created_at),
                current: r.revision_number == latest,
                hidden,
            }
        })
        .collect::<Vec<_>>();

    render(&state, "posts/history.html", context! {
        title => "Post history",
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        post_id => post.id,
        topic_id => post.topic_id,
        post_number => post.post_number,
        moderated => post.moderated_at.is_some(),
        any_hidden => any_hidden,
        is_staff => is_staff,
        versions => versions,
    })
}

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

/// Flag a post. htmx gets the post's flag control back (thanks, or the
/// reason it was refused); a plain form goes back to the post.
pub async fn flag_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    ip: crate::client_ip::ClientIp,
    user: UserContext,
    Form(form): Form<FlagForm>,
) -> Result<Response, StatusCode> {
    let result = moderation::flag_post(&state, &user.user, id, &form.reason, form.note.as_deref(), ip.0).await;
    if !is_htmx {
        let flag = result.map_err(StatusCode::from)?;
        let post = load_post(&state, flag.post_id).await?;
        return Ok(Redirect::to(&anchor(&post)).into_response());
    }
    let (flagged, error) = match result {
        Ok(_) => (true, None),
        Err(actions::ActionError::Conflict { message, .. }) => (true, Some(message)),
        Err(e @ actions::ActionError::NotFound) => return Err(e.into()),
        Err(e) => (false, Some(e.message())),
    };
    Ok(render(&state, "forum/_flag.html", context! {
        post => context! { id => id, flagged => flagged, can_flag => !flagged },
        flag_error => error,
        flag_reasons => crate::policy::FLAG_REASONS,
    })?
    .into_response())
}

/// The staff moderation form for a post.
pub async fn moderate_form(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    if !user.user.is_staff {
        return Err(StatusCode::FORBIDDEN);
    }
    let post = load_post(&state, id).await?;
    if post.deleted_at.is_some() {
        return Err(StatusCode::NOT_FOUND);
    }
    let author = users::Entity::find_by_id(post.user_id).one(state.db.as_ref()).await.map_err(ise("load author"))?;
    let flags = super::moderation::pending_flags_for(&state, post.id).await?;
    render(&state, "posts/moderate.html", context! {
        title => "Moderate post",
        app_name => state.config.app_name,
        user => user.user,
        post => post,
        author => author.map(|a| a.username),
        flags => flags,
    })
}

#[derive(Debug, Deserialize)]
pub struct ModerateForm {
    pub note: String,
    /// A checkbox: present = hide the earlier versions from non-staff.
    pub hide_original: Option<String>,
}

/// Replace the post with a staff note ([`moderation::moderate_post`]).
pub async fn moderate_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
    Form(form): Form<ModerateForm>,
) -> Result<Redirect, StatusCode> {
    let post =
        moderation::moderate_post(&state, Actor::web(&user.user), id, &form.note, form.hide_original.is_some()).await?;
    Ok(Redirect::to(&anchor(&post)))
}

/// Hide the earlier versions of a moderated post from non-staff.
pub async fn hide_original(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    moderation::set_original_hidden(&state, Actor::web(&user.user), id, true).await?;
    Ok(Redirect::to(&format!("/p/{id}/history")))
}

/// Show them again.
pub async fn unhide_original(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    moderation::set_original_hidden(&state, Actor::web(&user.user), id, false).await?;
    Ok(Redirect::to(&format!("/p/{id}/history")))
}

/// Put the pre-moderation body back.
pub async fn restore_body(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    let post = moderation::restore_moderated(&state, Actor::web(&user.user), id).await?;
    Ok(Redirect::to(&anchor(&post)))
}