16.9 KiB · text History 263b40b
//! Categories, topics, posts: reading and writing.
//!
//! Reads go through the web's own listing code (`focus::category_topics`,
//! `focus::decorate`, `forum::load_posts`, `forum::build_post_rows`,
//! `forum::record_topic_view`, `forum::resolve_sort`), writes through
//! `crate::actions`. Nothing here decides who may see or do what.
use std::collections::HashSet;

use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::Json;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::views::{utc, Author, Blocked, CategoryRef, Post, Reaction, Tag, TopicSummary};
use super::{ApiError, ApiJson, ApiPath, ApiResult};
use crate::actions::{self, viewer};
use crate::category_tree::CategoryTree;
use crate::entities::{topics, users};
use crate::handlers::focus;
use crate::handlers::forum as web;
use crate::middleware::UserContext;
use crate::AppState;

#[derive(Serialize)]
pub struct CategoryItem {
    #[serde(flatten)]
    pub category: CategoryRef,
    pub description: Option<String>,
    pub parent_id: Option<Uuid>,
    /// 1 for a top-level category.
    pub depth: i32,
    /// Live topics in it and its visible subcategories.
    pub topic_count: u64,
    pub watching: bool,
    /// Who may start topics / reply here (on top of reading it).
    pub posting: Posting,
    /// Whether this user may, as things stand (account, rules; a topic's
    /// lock is on the topic).
    pub can_create_topic: bool,
    pub can_reply: bool,
    /// Which reactions posts here show and take.
    pub reactions: Reactions,
}

#[derive(Serialize)]
pub struct Reactions {
    /// `all`, `none` (off: no reactions shown or taken) or `some`.
    pub mode: &'static str,
    /// The reaction keys offered, for `some`.
    pub keys: Vec<String>,
}

impl From<crate::policy::ReactionRule> for Reactions {
    fn from(r: crate::policy::ReactionRule) -> Self {
        Self { mode: r.mode(), keys: r.keys() }
    }
}

#[derive(Serialize)]
pub struct Rule {
    /// `everyone` (who can read it), `min_trust` or `staff`.
    pub kind: &'static str,
    pub min_trust: Option<i32>,
}

impl From<crate::policy::PostingRule> for Rule {
    fn from(r: crate::policy::PostingRule) -> Self {
        Self { kind: r.kind(), min_trust: r.min_trust() }
    }
}

#[derive(Serialize)]
pub struct Posting {
    pub create_topic: Rule,
    pub reply: Rule,
}

#[derive(Serialize)]
pub struct Categories {
    /// Every category this user can read, in the web's tree order (a parent,
    /// then its children, depth-first).
    pub categories: Vec<CategoryItem>,
}

async fn watched_ids(state: &AppState, user_id: Uuid) -> ApiResult<HashSet<Uuid>> {
    use crate::entities::category_watches;
    use sea_orm::*;
    Ok(category_watches::Entity::find()
        .filter(category_watches::Column::UserId.eq(user_id))
        .all(state.db.as_ref())
        .await?
        .into_iter()
        .map(|w| w.category_id)
        .collect())
}

#[allow(clippy::too_many_arguments)]
fn category_item(
    state: &AppState,
    user: &users::Model,
    tree: &CategoryTree,
    vis: &HashSet<Uuid>,
    counts: &std::collections::HashMap<Uuid, u64>,
    watched: &HashSet<Uuid>,
    id: Uuid,
    depth: i32,
) -> Option<CategoryItem> {
    let c = tree.get(id)?;
    Some(CategoryItem {
        category: CategoryRef::new(tree, id)?,
        description: c.description.clone(),
        parent_id: c.parent_id,
        depth,
        topic_count: focus::subtree_count(tree, vis, counts, id),
        watching: watched.contains(&id),
        posting: Posting {
            create_topic: crate::policy::topic_rule(c).into(),
            reply: crate::policy::reply_rule(c).into(),
        },
        can_create_topic: actions::create_caps(state, Some(user), c).0,
        can_reply: actions::account_block(state, user).is_none() && crate::policy::reply_rule(c).admits(user),
        reactions: crate::policy::ReactionRule::of(c).into(),
    })
}

/// `GET /categories`
pub async fn categories(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<Categories>> {
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    let vis = tree.visible_category_ids(viewer(&uc.user));
    let counts = focus::topic_counts(&state).await?;
    let watched = watched_ids(&state, uc.user.id).await?;
    let categories = tree
        .flatten()
        .into_iter()
        .filter(|(id, _)| vis.contains(id))
        .filter_map(|(id, depth)| category_item(&state, &uc.user, &tree, &vis, &counts, &watched, id, depth))
        .collect();
    Ok(Json(Categories { categories }))
}

#[derive(Debug, Deserialize)]
pub struct SortQuery {
    /// `latest`, `top`, `bottom` or `hot`. Given = remembered as the
    /// account's sort, exactly as `?sort=` on the web.
    pub sort: Option<String>,
}

#[derive(Serialize)]
pub struct CategoryPage {
    pub category: CategoryItem,
    /// Root first, not including this one.
    pub ancestors: Vec<CategoryRef>,
    /// Direct children this user can read.
    pub subcategories: Vec<CategoryItem>,
    pub sort: &'static str,
    /// Topics here and in visible subcategories; pinned first, then `sort`.
    pub topics: Vec<TopicSummary>,
    /// Start a topic here: verified, not silenced, the category's rule.
    /// (`can_post` is the same, kept for older apps.)
    pub can_post: bool,
    pub can_create_topic: bool,
    /// Why not, when not.
    pub create_blocked: Option<Blocked>,
}

/// `GET /categories/{slug}?sort=`
pub async fn category(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(slug): ApiPath<String>,
    Query(q): Query<SortQuery>,
) -> ApiResult<Json<CategoryPage>> {
    let (category, tree) = actions::visible_category(&state, viewer(&uc.user), &slug).await?;
    let vis = tree.visible_category_ids(viewer(&uc.user));
    let sort = web::resolve_sort(&state, q.sort.as_deref(), Some(&uc)).await;
    let counts = focus::topic_counts(&state).await?;
    let watched = watched_ids(&state, uc.user.id).await?;
    let depth = tree.depth(category.id);

    let loaded = focus::category_topics(&state, &tree, &vis, category.id, sort).await?;
    let tiles = focus::decorate(&state, &tree, loaded, Some(uc.user.id)).await?;
    let (can_create_topic, create_blocked) = actions::create_caps(&state, Some(&uc.user), &category);
    Ok(Json(CategoryPage {
        can_create_topic,
        create_blocked: create_blocked.map(Blocked::from),
        category: category_item(&state, &uc.user, &tree, &vis, &counts, &watched, category.id, depth)
            .ok_or_else(|| ApiError::not_found("No such category."))?,
        ancestors: tree.ancestors(category.id).into_iter().filter_map(|id| CategoryRef::new(&tree, id)).collect(),
        subcategories: tree
            .children(category.id)
            .iter()
            .filter(|id| vis.contains(id))
            .filter_map(|&id| category_item(&state, &uc.user, &tree, &vis, &counts, &watched, id, tree.depth(id)))
            .collect(),
        sort: sort.as_str(),
        topics: tiles.into_iter().map(|t| TopicSummary::from_tile(&tree, t)).collect(),
        can_post: can_create_topic,
    }))
}

#[derive(Serialize)]
pub struct TopicDetail {
    pub id: Uuid,
    pub title: String,
    pub category: Option<CategoryRef>,
    /// The category's ancestors, root first.
    pub ancestors: Vec<CategoryRef>,
    pub author: Author,
    pub is_pinned: bool,
    /// Locked by staff: no replies, reactions or edits except from staff.
    /// (`is_closed` is the same flag, kept for older apps.)
    pub is_locked: bool,
    pub is_closed: bool,
    pub lock_reason: Option<String>,
    /// Only staff ever see a removed topic's content.
    pub is_deleted: bool,
    pub views: i32,
    pub posts_count: i32,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub bumped_at: chrono::DateTime<chrono::Utc>,
    pub tags: Vec<Tag>,
}

#[derive(Serialize)]
pub struct TopicPage {
    pub topic: TopicDetail,
    pub posts: Vec<Post>,
    /// Reply here: verified, not silenced, the category's reply rule, not
    /// locked (staff excepted), a live topic.
    pub can_reply: bool,
    /// Why not, when not (a lock, a rule, a silence, verification).
    pub reply_blocked: Option<Blocked>,
    /// React to its posts (the reply rule; also per post).
    pub can_react: bool,
    /// Flag its posts (also per post: not yours, not twice).
    pub can_flag: bool,
    /// Change the tags: author or staff, verified, live topic.
    pub can_edit_tags: bool,
    /// Watching the topic's category.
    pub watching: bool,
}

async fn topic_page(
    state: &AppState,
    uc: &UserContext,
    topic: topics::Model,
    tree: &CategoryTree,
) -> ApiResult<TopicPage> {
    let caps = actions::topic_caps(state, Some(&uc.user), tree.get(topic.category_id), &topic);
    let loaded = web::load_posts(state, topic.id).await?;
    let posts = web::build_post_rows(state, loaded, Some(&uc.user), &topic, &caps).await?;
    let tags = web::tags_for_topic(state, topic.id).await?;
    let author = {
        use sea_orm::EntityTrait;
        users::Entity::find_by_id(topic.user_id)
            .one(state.db.as_ref())
            .await?
            .map(|u| u.username)
            .unwrap_or_else(|| "unknown".into())
    };
    let deleted = topic.deleted_at.is_some();
    Ok(TopicPage {
        can_reply: caps.can_reply,
        reply_blocked: caps.reply_block.clone().map(Blocked::from),
        can_react: caps.can_react,
        can_flag: caps.can_flag,
        can_edit_tags: actions::can_edit_tags(state, &uc.user, &topic),
        watching: actions::is_watching(state, uc.user.id, topic.category_id).await?,
        posts: posts.into_iter().map(|p| api_post(state, p)).collect(),
        topic: TopicDetail {
            id: topic.id,
            title: topic.title.clone(),
            category: CategoryRef::new(tree, topic.category_id),
            ancestors: tree
                .ancestors(topic.category_id)
                .into_iter()
                .filter_map(|id| CategoryRef::new(tree, id))
                .collect(),
            author: Author::new(topic.user_id, author),
            is_pinned: topic.is_pinned,
            is_locked: topic.is_closed,
            is_closed: topic.is_closed,
            lock_reason: topic.closed_reason.clone(),
            is_deleted: deleted,
            views: topic.views,
            posts_count: topic.posts_count,
            created_at: utc(topic.created_at),
            bumped_at: utc(topic.bumped_at),
            tags: tags.into_iter().map(Tag::from).collect(),
        },
    })
}

/// `GET /topics/{id}` — reading it counts a view (at most once per ten
/// minutes per user) and marks it read up to the last post, as on the web.
/// A removed topic is a `410 removed` for everyone but staff.
pub async fn topic(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
    headers: HeaderMap,
) -> ApiResult<Json<TopicPage>> {
    let (topic, tree) = actions::visible_topic(&state, viewer(&uc.user), id).await?;
    if topic.deleted_at.is_some() {
        if !uc.user.is_staff {
            return Err(ApiError::new(StatusCode::GONE, "removed", "This topic was removed."));
        }
    } else {
        web::record_topic_view(&state, &topic, Some(uc.user.id), &headers).await;
    }
    Ok(Json(topic_page(&state, &uc, topic, &tree).await?))
}

#[derive(Debug, Deserialize)]
pub struct NewTopic {
    pub title: String,
    pub body: String,
    #[serde(default)]
    pub tags: Vec<String>,
}

/// `POST /categories/{slug}/topics` → 201 and the new topic's page.
pub async fn create_topic(
    State(state): State<AppState>,
    uc: UserContext,
    ip: crate::client_ip::ClientIp,
    ApiPath(slug): ApiPath<String>,
    ApiJson(body): ApiJson<NewTopic>,
) -> ApiResult<(StatusCode, Json<TopicPage>)> {
    let topic =
        actions::create_topic(&state, &uc.user, &slug, &body.title, &body.body, &body.tags.join(",")).await?;
    crate::ips::record(state.db.as_ref(), uc.user.id, ip.0, crate::ips::Seen::Post).await;
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    Ok((StatusCode::CREATED, Json(topic_page(&state, &uc, topic, &tree).await?)))
}

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

/// `POST /topics/{id}/posts` → 201 and the reply.
pub async fn reply(
    State(state): State<AppState>,
    uc: UserContext,
    ip: crate::client_ip::ClientIp,
    ApiPath(id): ApiPath<Uuid>,
    ApiJson(body): ApiJson<NewPost>,
) -> ApiResult<(StatusCode, Json<Post>)> {
    let post = actions::reply(&state, &uc.user, id, &body.body).await?;
    crate::ips::record(state.db.as_ref(), uc.user.id, ip.0, crate::ips::Seen::Post).await;
    let (topic, tree) = actions::visible_topic(&state, viewer(&uc.user), post.topic_id).await?;
    let caps = actions::topic_caps(&state, Some(&uc.user), tree.get(topic.category_id), &topic);
    let row = web::build_post_rows(&state, vec![(post, Some(uc.user.clone()))], Some(&uc.user), &topic, &caps)
        .await?
        .pop()
        .ok_or_else(|| ApiError::internal("reply row missing"))?;
    Ok((StatusCode::CREATED, Json(api_post(&state, row))))
}

/// A post for the app: `/out` links absolute (crate::links), in the body and
/// on its link cards.
fn api_post(state: &AppState, row: web::PostRow) -> Post {
    let mut post = Post::from(row);
    let links = crate::links::Links::from_config(&state.config);
    post.cooked = links.absolutize(&post.cooked);
    for l in &mut post.links {
        if !l.href.starts_with("http") {
            l.href = format!("{}{}", state.config.public_url.trim_end_matches('/'), l.href);
        }
    }
    post
}

#[derive(Debug, Deserialize)]
pub struct TagsBody {
    pub tags: Vec<String>,
}

#[derive(Serialize)]
pub struct TagsResponse {
    pub tags: Vec<Tag>,
}

/// `PUT /topics/{id}/tags` — replace the topic's tags. Up to five; a name
/// with no tag yet is minted only at the trust level `GET /me` reports, and
/// otherwise dropped, as on the web.
pub async fn set_tags(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
    ApiJson(body): ApiJson<TagsBody>,
) -> ApiResult<Json<TagsResponse>> {
    let tags = actions::set_topic_tags(&state, &uc.user, id, &body.tags.join(",")).await?;
    Ok(Json(TagsResponse { tags: tags.into_iter().map(Tag::from).collect() }))
}

#[derive(Debug, Deserialize)]
pub struct ReactionBody {
    /// A reaction key from a post's `reactions`, or null to clear yours.
    pub key: Option<String>,
}

#[derive(Serialize)]
pub struct ReactionsResponse {
    pub reactions: Vec<Reaction>,
}

/// `PUT /posts/{id}/reaction` — set (or with `null`, clear) your reaction.
pub async fn set_reaction(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
    ApiJson(body): ApiJson<ReactionBody>,
) -> ApiResult<Json<ReactionsResponse>> {
    let views = actions::set_reaction(&state, &uc.user, id, body.key.as_deref()).await?;
    Ok(Json(ReactionsResponse { reactions: views.into_iter().map(Reaction::from).collect() }))
}

#[derive(Debug, Deserialize, Serialize)]
pub struct BookmarkBody {
    pub bookmarked: bool,
}

/// `PUT /posts/{id}/bookmark`
pub async fn set_bookmark(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
    ApiJson(body): ApiJson<BookmarkBody>,
) -> ApiResult<Json<BookmarkBody>> {
    let bookmarked = actions::set_bookmark(&state, &uc.user, id, body.bookmarked).await?;
    Ok(Json(BookmarkBody { bookmarked }))
}

#[derive(Debug, Deserialize, Serialize)]
pub struct WatchBody {
    pub watching: bool,
}

/// `PUT /categories/{slug}/watch` — new topics in it (and below) notify you.
pub async fn set_watch(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(slug): ApiPath<String>,
    ApiJson(body): ApiJson<WatchBody>,
) -> ApiResult<Json<WatchBody>> {
    let (_, watching) = actions::set_watch(&state, &uc.user, &slug, body.watching).await?;
    Ok(Json(WatchBody { watching }))
}

/// For `find`: the tiles for an arbitrary list of topics.
pub(super) async fn summaries(
    state: &AppState,
    tree: &CategoryTree,
    loaded: Vec<(topics::Model, Option<users::Model>)>,
    user_id: Uuid,
) -> ApiResult<Vec<TopicSummary>> {
    let tiles = focus::decorate(state, tree, loaded, Some(user_id)).await?;
    Ok(tiles.into_iter().map(|t| TopicSummary::from_tile(tree, t)).collect())
}

#[derive(Debug, Deserialize)]
pub struct FlagBody {
    /// `spam`, `abusive`, `off_topic` or `other`.
    pub reason: String,
    pub note: Option<String>,
}

#[derive(Serialize)]
pub struct FlagResponse {
    pub flagged: bool,
}

/// `POST /posts/{id}/flags` → 201 `{"flagged": true}`. Once per post
/// (`409 already_flagged`), not your own (`403 own_post`), trust level
/// `MIN_TRUST_TO_FLAG` (`403 trust_level`), not while silenced.
pub async fn flag(
    State(state): State<AppState>,
    uc: UserContext,
    ip: crate::client_ip::ClientIp,
    ApiPath(id): ApiPath<Uuid>,
    ApiJson(body): ApiJson<FlagBody>,
) -> ApiResult<(StatusCode, Json<FlagResponse>)> {
    crate::moderation::flag_post(&state, &uc.user, id, &body.reason, body.note.as_deref(), ip.0).await?;
    Ok((StatusCode::CREATED, Json(FlagResponse { flagged: true })))
}