//! 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, flag, tag at all: a verified address (where the
/// site requires one) and no silence. Categories and locks add their own
/// rules (`can_create_topic`, `can_reply`).
pub may_write: bool,
/// A cooldown (read-only) in force: the app shows it as a banner.
pub silenced: Option<SanctionView>,
/// The same cooldown's end, flat: read-only until then.
pub read_only_until: Option<DateTime<Utc>>,
/// 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::actions::can_write(state, u),
read_only_until: crate::policy::silence(u).and_then(|s| s.until),
silenced: crate::policy::silence(u).map(|s| SanctionView {
message: crate::policy::silence_message(&s),
until: s.until,
reason: s.reason,
}),
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),
}
}
}
/// A silence, for the person it applies to.
#[derive(Serialize)]
pub struct SanctionView {
pub until: Option<DateTime<Utc>>,
pub reason: Option<String>,
/// The sentence the web shows ("You're silenced until …: reason").
pub message: String,
}
/// Why something can't be done: `code` for the program, `message` for the
/// person (the web's wording).
#[derive(Serialize, Clone)]
pub struct Blocked {
pub code: &'static str,
pub message: String,
}
impl From<crate::policy::Block> for Blocked {
fn from(b: crate::policy::Block) -> Self {
Self { code: b.code, message: b.message }
}
}
#[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,
/// Locked by staff (the same flag as `is_closed`, kept for older apps).
pub is_locked: 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_locked: row.is_closed,
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,
/// Staff replaced the body with a note: `cooked` is the note, shown as
/// "staff: …". The original is never sent.
pub moderated: Option<Moderated>,
/// Hidden pending staff review: `cooked` is empty (unless you wrote it).
pub hidden: bool,
/// Your post, held by the lameness filter: why. Only ever sent to the
/// author (others see just `hidden`).
#[serde(skip_serializing_if = "Option::is_none")]
pub held: Option<Held>,
pub can_react: bool,
pub can_flag: bool,
/// You flagged it.
pub flagged: bool,
}
#[derive(Serialize)]
pub struct Held {
pub reasons: Vec<String>,
}
#[derive(Serialize)]
pub struct Moderated {
pub by: Option<String>,
pub at: Option<DateTime<Utc>>,
}
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,
moderated: p.moderated.then(|| Moderated { by: p.moderated_by.clone(), at: p.moderated_at.map(utc) }),
hidden: p.hidden,
held: (p.own && !p.held.is_empty()).then(|| Held { reasons: p.held.clone() }),
can_react: p.can_react,
can_flag: p.can_flag,
flagged: p.flagged,
}
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
9.8 KiB · text
History
6e34613