7.5 KiB · text History 63417ef
//! The JSON shapes `/api/v1` answers with, built from the same rows the web
//! templates render (`TopicRow`/`TopicTile`, `PostRow`, `ReactionView`), so a
//! field the web shows and the app shows come from one computation.
use chrono::{DateTime, FixedOffset, Utc};
use serde::Serialize;
use uuid::Uuid;

use crate::category_tree::CategoryTree;
use crate::entities::users;
use crate::handlers::focus::TopicTile;
use crate::handlers::forum::{PostRow, TagChip, TopicRow};
use crate::handlers::reactions::ReactionView;
use crate::AppState;

/// ISO-8601 UTC, as every timestamp in the API is sent.
pub fn utc(t: DateTime<FixedOffset>) -> DateTime<Utc> {
    t.with_timezone(&Utc)
}

/// The server-relative avatar URL; uploaded image or generated letter SVG.
pub fn avatar_url(id: Uuid) -> String {
    format!("/u/{id}/avatar")
}

#[derive(Serialize)]
pub struct Author {
    pub id: Uuid,
    pub username: String,
    pub avatar_url: String,
}

impl Author {
    pub fn new(id: Uuid, username: impl Into<String>) -> Self {
        Self { id, username: username.into(), avatar_url: avatar_url(id) }
    }
}

/// The signed-in user, with everything the app gates on.
#[derive(Serialize)]
pub struct Me {
    pub id: Uuid,
    pub username: String,
    pub email: String,
    pub avatar_url: String,
    pub has_avatar: bool,
    pub is_staff: bool,
    pub trust_level: i32,
    pub trust_name: &'static str,
    pub email_verified: bool,
    /// Post, reply, react, bookmark, tag. False only while the site requires
    /// a verified address and this one isn't.
    pub may_write: bool,
    /// New tags (not just existing ones) on a topic.
    pub may_create_tags: bool,
    /// `classic` or `focus`: the profile's Layout.
    pub preferred_view: &'static str,
    /// `latest`, `top`, `bottom` or `hot`.
    pub preferred_sort: String,
    pub reaction_notifications: bool,
    pub created_at: DateTime<Utc>,
}

impl Me {
    pub fn new(state: &AppState, u: &users::Model) -> Self {
        Self {
            id: u.id,
            username: u.username.clone(),
            email: u.email.clone(),
            avatar_url: avatar_url(u.id),
            has_avatar: u.avatar_content_type.is_some(),
            is_staff: u.is_staff,
            trust_level: u.trust_level,
            trust_name: crate::trust::tier_name(u.trust_level),
            email_verified: u.email_verified_at.is_some(),
            may_write: crate::handlers::may_write(state, u),
            may_create_tags: crate::trust::can_create_tags(u, state.config.min_trust_to_create_tag),
            preferred_view: crate::handlers::focus::ViewMode::parse(&u.preferred_view)
                .unwrap_or(crate::handlers::focus::ViewMode::Classic)
                .as_str(),
            preferred_sort: crate::handlers::forum::TopicSort::parse(&u.preferred_sort)
                .unwrap_or(crate::handlers::forum::TopicSort::Latest)
                .as_str()
                .to_string(),
            reaction_notifications: u.reaction_notifications,
            created_at: utc(u.created_at),
        }
    }
}

#[derive(Serialize)]
pub struct MeResponse {
    pub user: Me,
    /// Whether the site requires a verified address to write at all.
    pub verification_required: bool,
    /// The trust level needed to mint a new tag.
    pub min_trust_to_create_tag: i32,
}

impl MeResponse {
    pub fn new(state: &AppState, u: &users::Model) -> Self {
        Self {
            user: Me::new(state, u),
            verification_required: state.config.require_email_verification,
            min_trust_to_create_tag: state.config.min_trust_to_create_tag,
        }
    }
}

/// A category as a chip: enough to draw its lineage colours and link to it.
#[derive(Serialize, Clone)]
pub struct CategoryRef {
    pub id: Uuid,
    pub slug: String,
    pub name: String,
    /// Root first, this one last (the web's lineage circle).
    pub colors: Vec<String>,
}

impl CategoryRef {
    pub fn new(tree: &CategoryTree, id: Uuid) -> Option<Self> {
        let c = tree.get(id)?;
        Some(Self { id, slug: c.slug.clone(), name: c.name.clone(), colors: tree.widget_colors(id) })
    }
}

#[derive(Serialize)]
pub struct Tag {
    pub name: String,
    pub slug: String,
}

impl From<TagChip> for Tag {
    fn from(t: TagChip) -> Self {
        Self { name: t.name, slug: t.slug }
    }
}

#[derive(Serialize)]
pub struct ReactionSummary {
    pub emoji: String,
    pub count: usize,
}

/// A topic in a list, as a Focus tile shows it (the Classic row is a subset).
#[derive(Serialize)]
pub struct TopicSummary {
    pub id: Uuid,
    pub title: String,
    pub category: Option<CategoryRef>,
    pub author: Author,
    pub is_pinned: bool,
    pub is_closed: bool,
    pub posts_count: i32,
    pub replies: i32,
    pub views: i32,
    pub created_at: DateTime<Utc>,
    pub bumped_at: DateTime<Utc>,
    pub tags: Vec<Tag>,
    /// The opening poster, then the top repliers.
    pub posters: Vec<Author>,
    pub reactions: Vec<ReactionSummary>,
    /// Never opened, recently active.
    pub is_new: bool,
    /// Posts since this user last read it.
    pub unread: i32,
    /// What a list adds about it ("Bookmarked #3 · 2h ago").
    pub notes: Vec<String>,
}

impl TopicSummary {
    pub(crate) fn from_tile(tree: &CategoryTree, t: TopicTile) -> Self {
        let row: TopicRow = t.row;
        Self {
            id: row.id,
            title: row.title,
            category: CategoryRef::new(tree, row.category_id),
            author: Author::new(row.author_id, row.author),
            is_pinned: row.is_pinned,
            is_closed: row.is_closed,
            posts_count: row.posts_count,
            replies: t.replies,
            views: row.views,
            created_at: utc(row.created),
            bumped_at: utc(row.bumped),
            tags: row.tags.into_iter().map(Tag::from).collect(),
            posters: t.posters.into_iter().map(|a| Author::new(a.id, a.name)).collect(),
            reactions: t
                .reactions
                .into_iter()
                .map(|r| ReactionSummary { emoji: r.emoji, count: r.count })
                .collect(),
            is_new: t.is_new,
            unread: t.unread,
            notes: t.notes,
        }
    }
}

#[derive(Serialize)]
pub struct Reaction {
    pub key: String,
    pub emoji: String,
    pub count: i64,
    /// This user's (one per post).
    pub reacted: bool,
}

impl From<ReactionView> for Reaction {
    fn from(r: ReactionView) -> Self {
        Self { key: r.key, emoji: r.emoji, count: r.count, reacted: r.reacted }
    }
}

#[derive(Serialize)]
pub struct Post {
    pub id: Uuid,
    pub post_number: i32,
    pub author: Author,
    /// The server's sanitized HTML of the post's markdown — the web's own
    /// rendering. Empty for a removed post.
    pub cooked: String,
    pub created_at: DateTime<Utc>,
    pub edited_at: Option<DateTime<Utc>>,
    pub deleted: bool,
    pub bookmarked: bool,
    pub reactions: Vec<Reaction>,
    /// Edit / delete on the web (the app links out).
    pub can_edit: bool,
}

impl From<PostRow> for Post {
    fn from(p: PostRow) -> Self {
        Self {
            id: p.id,
            post_number: p.post_number,
            author: Author::new(p.author_id, p.author),
            cooked: if p.deleted { String::new() } else { p.cooked },
            created_at: utc(p.created),
            edited_at: p.edited_at.map(utc),
            deleted: p.deleted,
            bookmarked: p.bookmarked,
            reactions: p.reactions.into_iter().map(Reaction::from).collect(),
            can_edit: p.can_edit,
        }
    }
}