6.4 KiB · text History 7ce364f
//! Rich links on a post (`crate::link_cards`): staff attach, remove and
//! refetch them from the post's moderation controls, inline (htmx swaps the
//! post's link block); the card pictures are served from our own database.
use axum::{
    extract::{Form, Path, Query, State},
    http::{header, StatusCode},
    response::{IntoResponse, Redirect, Response},
};
use axum_htmx::HxRequest;
use minijinja::context;
use sea_orm::*;
use serde::Deserialize;
use uuid::Uuid;

use crate::actions::{visible_topic, ActionError, WebError};
use crate::entities::{post_links, posts, users};
use crate::link_cards::{self, OK};
use crate::middleware::UserContext;
use crate::moderation::Actor;
use crate::AppState;

use super::forum::{build_post_rows, viewer_of};
use super::render;

#[derive(Debug, Deserialize)]
pub struct LinksQuery {
    /// Show the staff panel open.
    pub open: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct AttachForm {
    pub url: String,
}

/// The post's link block (`forum/_post_links.html`): its cards, and for
/// staff the manage panel (open when `open`, with `error` if the last
/// action was refused).
async fn block(
    state: &AppState,
    uc: &Option<UserContext>,
    post_id: Uuid,
    open: bool,
    error: Option<String>,
) -> Result<Response, WebError> {
    let viewer = viewer_of(uc);
    let user = uc.as_ref().map(|c| &c.user);
    let post = posts::Entity::find_by_id(post_id)
        .one(state.db.as_ref())
        .await
        .map_err(ActionError::from)?
        .ok_or(ActionError::NotFound)?;
    let (topic, tree) = visible_topic(state, viewer, post.topic_id).await?;
    let author = users::Entity::find_by_id(post.user_id).one(state.db.as_ref()).await.map_err(ActionError::from)?;
    let caps = crate::actions::topic_caps(state, user, tree.get(topic.category_id), &topic);
    let row = build_post_rows(state, vec![(post, author)], user, &topic, &caps)
        .await?
        .pop()
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
    let open = open && row.can_moderate;
    let poll = open && row.staff_links.iter().any(|l| l.status == link_cards::PENDING);
    let html = render(state, "forum/_post_links.html", context! {
        post => row,
        user => user,
        links_open => open,
        links_poll => poll,
        links_error => error,
        max_links => link_cards::MAX_LINKS,
    })?;
    Ok(html.into_response())
}

/// `GET /p/{id}/links`: the block alone (the staff panel opening, and its
/// poll while a fetch is pending).
pub async fn show_links(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Query(q): Query<LinksQuery>,
    uc: Option<UserContext>,
) -> Result<Response, WebError> {
    block(&state, &uc, id, q.open.is_some(), None).await
}

/// Answer a staff action: the block again for htmx (refusals shown in it,
/// so they swap), else back to the post.
async fn answer(
    state: &AppState,
    uc: UserContext,
    is_htmx: bool,
    post_id: Uuid,
    result: Result<(), ActionError>,
) -> Result<Response, WebError> {
    match result {
        // Not staff, or not there: the plain refusal, whoever asks.
        Err(e @ (ActionError::Forbidden { .. } | ActionError::NotFound | ActionError::Internal(_))) => Err(e.into()),
        Err(e) if is_htmx => block(state, &Some(uc), post_id, true, Some(e.message())).await,
        Err(e) => Err(e.into()),
        Ok(()) if is_htmx => block(state, &Some(uc), post_id, true, None).await,
        Ok(()) => Ok(Redirect::to(&format!("/p/{post_id}")).into_response()),
    }
}

/// `POST /p/{id}/links`: attach a link (staff).
pub async fn attach_link(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    uc: UserContext,
    Form(form): Form<AttachForm>,
) -> Result<Response, WebError> {
    let r = link_cards::attach(&state, Actor::web(&uc.user), id, &form.url).await.map(|_| ());
    answer(&state, uc, is_htmx, id, r).await
}

async fn post_of(state: &AppState, link: Uuid) -> Result<Uuid, ActionError> {
    post_links::Entity::find_by_id(link)
        .select_only()
        .column(post_links::Column::PostId)
        .into_tuple()
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)
}

/// `POST /links/{id}/delete` (staff).
pub async fn remove_link(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    uc: UserContext,
) -> Result<Response, WebError> {
    Actor::web(&uc.user).require_staff()?;
    let post = post_of(&state, id).await?;
    let r = link_cards::remove(&state, Actor::web(&uc.user), id).await.map(|_| ());
    answer(&state, uc, is_htmx, post, r).await
}

/// `POST /links/{id}/refetch` (staff).
pub async fn refetch_link(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    uc: UserContext,
) -> Result<Response, WebError> {
    Actor::web(&uc.user).require_staff()?;
    let post = post_of(&state, id).await?;
    let r = link_cards::refetch(&state, Actor::web(&uc.user), id).await.map(|_| ());
    answer(&state, uc, is_htmx, post, r).await
}

/// `GET /links/{id}/image`: a card's picture, from our database, under the
/// same rule as the card: only where the post may be read and isn't hidden
/// (staff excepted).
pub async fn link_image(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    uc: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let link = post_links::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
        .ok_or(StatusCode::NOT_FOUND)?;
    let viewer = viewer_of(&uc);
    let (post, _, _) = crate::actions::visible_live_post(&state, viewer, link.post_id).await?;
    if post.hidden_at.is_some() && !viewer.staff {
        return Err(StatusCode::NOT_FOUND);
    }
    let (Some(bytes), Some(ct)) = (link.image_data, link.image_content_type) else {
        return Err(StatusCode::NOT_FOUND);
    };
    if link.status != OK {
        return Err(StatusCode::NOT_FOUND);
    }
    Ok((
        [
            (header::CONTENT_TYPE, ct),
            // The URL changes with the picture (`?v=`); private because the
            // post may not be public.
            (header::CACHE_CONTROL, "private, max-age=86400".to_string()),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
            (header::CONTENT_SECURITY_POLICY, "default-src 'none'; sandbox".to_string()),
        ],
        bytes,
    )
        .into_response())
}