19.1 KiB · text History 263b40b
//! Link-preview metadata (movie_monster's `handlers::meta`, adapted): what a
//! scraper sees when someone pastes one of our URLs into Slack, Discord,
//! iMessage or <https://www.linkpreview.app>.
//!
//! Unfurlers don't run JavaScript and don't follow hx-boost. They fetch the
//! URL once and read `<head>`, so every public page hands a [`PageMeta`] to
//! its template and `root.html` turns it into OpenGraph and Twitter-card
//! tags. A page that builds none (admin, auth, profile, devices,
//! moderation, bookmarks, notifications, reactions, search) gets the site
//! name, the generic description and `noindex`.
//!
//! **Always as anonymous.** The unfurler has no session, so a card is built
//! from what an anonymous visitor may see, even when the request carries
//! one, using the same rules as the pages (`Viewer::anonymous`, `Visible`).
//! A topic in a members-only, trust-gated or staff-only category, a held or
//! deleted topic, or a hidden opening post gives a generic card: no title,
//! no excerpt. So a signed-in member who copies a link never leaks it
//! through the card. A moderated opening post's body *is* the staff note,
//! so that's what the excerpt shows; the original is never read here.
//!
//! **Absolute URLs** come from `PUBLIC_URL` (`Config::public_url`), never
//! from `Host` / `X-Forwarded-Host`: those are client-controlled, and this
//! service no longer trusts headers it doesn't have to.
use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
use sea_orm::EntityTrait;
use serde::Serialize;

use crate::category_tree::{CategoryTree, Viewer};
use crate::entities::{categories, posts, topics};
use crate::AppState;

/// How much description a scraper gets. Most unfurlers cut near 200
/// characters; sending more just means they choose the cut, mid-word.
pub const MAX_DESCRIPTION: usize = 200;

/// The square site mark (512×512, from the app's launcher icon), used
/// whenever a page has no image of its own. A card with no image reads as a
/// broken link.
pub const DEFAULT_IMAGE: &str = "/assets/img/site-mark.png";
const DEFAULT_IMAGE_SIZE: u32 = 512;

/// The description of a page that says nothing of its own.
pub fn site_description(app_name: &str) -> String {
    format!("{app_name}: a discussion forum.")
}

/// Everything `root.html` needs for one page's preview card.
#[derive(Clone, Debug, Serialize)]
pub struct PageMeta {
    /// `og:title`: the page's own name; the brand rides in `og:site_name`.
    pub title: String,
    pub description: String,
    /// Absolute canonical URL: `og:url` and `<link rel=canonical>`.
    pub url: String,
    pub image: String,
    pub image_alt: String,
    /// Known only for the site mark.
    pub image_width: Option<u32>,
    pub image_height: Option<u32>,
    /// `summary_large_image` needs a known, wide image; everything we have is
    /// the square mark or an image of unknown size, so this is `summary`.
    pub twitter_card: &'static str,
    /// `og:type`.
    pub kind: &'static str,
    pub noindex: bool,
    /// For `article`s.
    pub published: Option<String>,
    pub modified: Option<String>,
    pub section: Option<String>,
    pub tags: Vec<String>,
    pub author: Option<String>,
    #[serde(skip)]
    base: String,
}

impl PageMeta {
    /// A card for `path` with the site defaults, narrowed by the builders.
    pub fn new(state: &AppState, path: &str) -> Self {
        let base = state.config.public_url.trim_end_matches('/').to_string();
        PageMeta {
            title: state.config.app_name.clone(),
            description: site_description(&state.config.app_name),
            url: join(&base, path),
            image: join(&base, DEFAULT_IMAGE),
            image_alt: state.config.app_name.clone(),
            image_width: Some(DEFAULT_IMAGE_SIZE),
            image_height: Some(DEFAULT_IMAGE_SIZE),
            twitter_card: "summary",
            kind: "website",
            noindex: false,
            published: None,
            modified: None,
            section: None,
            tags: Vec::new(),
            author: None,
            base,
        }
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// The description, flattened and cut to [`MAX_DESCRIPTION`] at a word.
    pub fn description(mut self, text: impl AsRef<str>) -> Self {
        let text = summarize(text.as_ref(), MAX_DESCRIPTION);
        if !text.is_empty() {
            self.description = text;
        }
        self
    }

    /// An image of ours (a path, or an absolute URL on `PUBLIC_URL`'s host);
    /// anything else keeps the site mark.
    pub fn image(mut self, url: Option<&str>, alt: &str) -> Self {
        if let Some(abs) = url.map(str::trim).filter(|u| !u.is_empty()).and_then(|u| own_url(&self.base, u)) {
            self.image = abs;
            self.image_alt = alt.to_string();
            self.image_width = None;
            self.image_height = None;
        }
        self
    }

    pub fn noindex(mut self, noindex: bool) -> Self {
        self.noindex = noindex;
        self
    }
}

fn join(base: &str, path: &str) -> String {
    format!("{base}/{}", path.trim_start_matches('/'))
}

/// `u` as an absolute URL if it's ours: a site path, or our own origin.
/// Third-party images aren't put in cards: the unfurler would fetch (and
/// show) whatever that host serves, which we never vetted and which can
/// change, and it tells that host who's looking.
fn own_url(base: &str, u: &str) -> Option<String> {
    if u.starts_with('/') && !u.starts_with("//") {
        return Some(join(base, u));
    }
    let ours = url::Url::parse(base).ok()?;
    let theirs = url::Url::parse(u).ok()?;
    (theirs.origin() == ours.origin()).then(|| theirs.to_string())
}

/// Flatten whitespace and cut to `max` characters on a word boundary, with
/// an ellipsis.
pub fn summarize(text: &str, max: usize) -> String {
    let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.chars().count() <= max {
        return flat;
    }
    let mut out = String::new();
    for word in flat.split(' ') {
        // -1 leaves room for the ellipsis.
        if out.chars().count() + word.chars().count() + 1 > max - 1 {
            break;
        }
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(word);
    }
    // One word longer than the budget: cut it rather than return nothing.
    if out.is_empty() {
        out = flat.chars().take(max - 1).collect();
    }
    format!("{}…", out.trim_end_matches(|c: char| c.is_ascii_punctuation()))
}

/// Join names into "A, B and C", trailing into "and N more" past `max`.
/// Names say more than a count about whether to click.
pub fn name_list(items: &[String], max: usize) -> String {
    let shown: Vec<&str> = items.iter().take(max).map(String::as_str).collect();
    let more = items.len().saturating_sub(shown.len());
    let head = match shown.len() {
        0 => return String::new(),
        1 => shown[0].to_string(),
        _ if more > 0 => shown.join(", "),
        n => format!("{} and {}", shown[..n - 1].join(", "), shown[n - 1]),
    };
    match more {
        0 => head,
        1 => format!("{head} and 1 more"),
        n => format!("{head} and {n} more"),
    }
}

/// A post's markdown as plain text (no markup, no raw HTML, no code
/// blocks), and its first image's URL.
pub fn plain_text(raw: &str) -> (String, Option<String>) {
    let mut out = String::new();
    let mut image = None;
    let mut in_code_block = 0usize;
    let mut in_image = 0usize;
    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    opts.insert(Options::ENABLE_TABLES);
    for ev in Parser::new_ext(raw, opts) {
        match ev {
            Event::Start(Tag::CodeBlock(_)) => in_code_block += 1,
            Event::End(TagEnd::CodeBlock) => {
                in_code_block = in_code_block.saturating_sub(1);
                out.push(' ');
            }
            Event::Start(Tag::Image { dest_url, .. }) => {
                in_image += 1;
                if image.is_none() {
                    image = Some(dest_url.to_string());
                }
            }
            Event::End(TagEnd::Image) => in_image = in_image.saturating_sub(1),
            Event::Text(t) | Event::Code(t) if in_code_block == 0 && in_image == 0 => out.push_str(&t),
            Event::SoftBreak | Event::HardBreak => out.push(' '),
            Event::End(TagEnd::Paragraph | TagEnd::Heading(_) | TagEnd::Item | TagEnd::TableCell) => out.push(' '),
            _ => {}
        }
    }
    (out, image)
}

/// The card for a topic, as an anonymous visitor would see it: the title,
/// the opening post as plain text, the category and tags. Anything an
/// anonymous visitor can't read gives a generic card.
pub async fn topic(
    state: &AppState,
    tree: &CategoryTree,
    topic: &topics::Model,
    tag_names: Vec<String>,
) -> PageMeta {
    let path = format!("/t/{}", topic.id);
    let anon = Viewer::anonymous();
    let app = &state.config.app_name;
    let category = tree.get(topic.category_id);
    if topic.deleted_at.is_some() || !tree.can_view(topic.category_id, anon) || !anon.sees_topic(topic) {
        return PageMeta::new(state, &path)
            .title(format!("A members-only discussion on {app}"))
            .description(format!("Sign in to {app} to read it."))
            .noindex(true);
    }
    let op = posts_first(state, topic.id).await;
    let mut m = PageMeta::new(state, &path).title(topic.title.clone());
    m.kind = "article";
    m.published = Some(topic.created_at.to_rfc3339());
    m.modified = Some(topic.bumped_at.to_rfc3339());
    m.section = category.map(|c| c.name.clone());
    m.tags = tag_names;
    match op {
        // Readable: its text (for a moderated post, the staff note that
        // replaced it), and its first image if it's ours.
        Some(p) if p.deleted_at.is_none() && p.hidden_at.is_none() => {
            let (text, img) = plain_text(&p.raw);
            m = m.description(text).image(img.as_deref(), &topic.title);
            m.author = crate::entities::users::Entity::find_by_id(p.user_id)
                .one(state.db.as_ref())
                .await
                .ok()
                .flatten()
                .map(|u| u.username);
        }
        _ => {
            m = m.description(format!(
                "A discussion in {} on {app}.",
                category.map(|c| c.name.as_str()).unwrap_or("a category")
            ));
        }
    }
    m
}

async fn posts_first(state: &AppState, topic_id: uuid::Uuid) -> Option<posts::Model> {
    use sea_orm::{ColumnTrait, QueryFilter};
    posts::Entity::find()
        .filter(posts::Column::TopicId.eq(topic_id))
        .filter(posts::Column::PostNumber.eq(1))
        .one(state.db.as_ref())
        .await
        .ok()
        .flatten()
}

/// The card for a category: its description, else what's in it (names over
/// counts), as anonymous; generic when anonymous can't read it.
pub fn category(
    state: &AppState,
    tree: &CategoryTree,
    c: &categories::Model,
    path: &str,
    topic_count: u64,
    recent_titles: &[String],
) -> PageMeta {
    let app = &state.config.app_name;
    if !tree.can_view(c.id, Viewer::anonymous()) {
        return PageMeta::new(state, path)
            .title(format!("A members-only category on {app}"))
            .description(format!("Sign in to {app} to read it."))
            .noindex(true);
    }
    let m = PageMeta::new(state, path).title(c.name.clone());
    match c.description.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
        Some(d) => m.description(d),
        None => m.description(topics_sentence(topic_count, recent_titles)),
    }
}

/// "12 topics: A, B, C and 9 more." Names first; the count is the whole
/// category, not just the titles given.
pub fn topics_sentence(total: u64, titles: &[String]) -> String {
    let noun = if total == 1 { "topic" } else { "topics" };
    let shown: Vec<String> = titles.iter().take(3).cloned().collect();
    if shown.is_empty() {
        return format!("{total} {noun}.");
    }
    let more = (total as usize).saturating_sub(shown.len());
    if more == 0 {
        return format!("{total} {noun}: {}.", name_list(&shown, 3));
    }
    format!("{total} {noun}: {} and {more} more.", shown.join(", "))
}

// --- list pages ---------------------------------------------------------------
// Their names come from anonymous-only queries, whoever is asking.

fn anon_vis(tree: &CategoryTree) -> crate::category_tree::Visible {
    tree.visible_category_ids(Viewer::anonymous())
}

/// A Focus list opened at `?topic=`: that topic's card (the URL people
/// copy). Without one, the list's own card.
pub async fn with_reader(state: &AppState, tree: &CategoryTree, topic: Option<uuid::Uuid>, list: PageMeta) -> PageMeta {
    let Some(id) = topic else { return list };
    match topics::Entity::find_by_id(id).one(state.db.as_ref()).await.ok().flatten() {
        Some(t) => {
            let tags = crate::handlers::forum::tags_for_topic(state, t.id)
                .await
                .map(|v| v.into_iter().map(|c| c.name).collect())
                .unwrap_or_default();
            self::topic(state, tree, &t, tags).await
        }
        None => list,
    }
}

async fn anon_latest_titles(state: &AppState, tree: &CategoryTree, n: u64) -> Vec<String> {
    crate::handlers::landing::latest_topics(state, &anon_vis(tree), n)
        .await
        .unwrap_or_default()
        .into_iter()
        .map(|(t, _)| t.title)
        .collect()
}

/// `/`: the site, and what's newest.
pub async fn home(state: &AppState, tree: &CategoryTree) -> PageMeta {
    let app = &state.config.app_name;
    let names = anon_latest_titles(state, tree, 4).await;
    let m = PageMeta::new(state, "/").title(app.clone());
    if names.is_empty() {
        return m;
    }
    m.description(format!("{} Latest: {}.", site_description(app), name_list(&names, 3)))
}

/// `/p/latest` and `/p/popular`.
pub async fn feed(state: &AppState, tree: &CategoryTree, popular: bool) -> PageMeta {
    let app = &state.config.app_name;
    let vis = anon_vis(tree);
    let limit = crate::handlers::landing::FEED_LIMIT;
    let loaded = if popular {
        crate::handlers::landing::popular_topics(state, &vis, limit as usize).await
    } else {
        crate::handlers::landing::latest_topics(state, &vis, limit).await
    }
    .unwrap_or_default();
    let names: Vec<String> = loaded.into_iter().map(|(t, _)| t.title).collect();
    let (path, title, lead) = if popular {
        ("/p/popular", format!("Popular on {app}"), "The most active topics of the last 30 days")
    } else {
        ("/p/latest", format!("Latest on {app}"), "The newest activity")
    };
    let m = PageMeta::new(state, path).title(title);
    if names.is_empty() {
        return m.description(format!("{lead}. Nothing yet."));
    }
    m.description(format!("{lead}: {}.", name_list(&names, 3)))
}

/// `/c/`: the top-level categories anonymous visitors can read.
pub fn categories_index(state: &AppState, tree: &CategoryTree) -> PageMeta {
    let vis = anon_vis(tree);
    let names: Vec<String> = tree
        .roots()
        .iter()
        .filter(|id| vis.contains(id))
        .filter_map(|id| tree.get(*id).map(|c| c.name.clone()))
        .collect();
    let noun = if names.len() == 1 { "category" } else { "categories" };
    PageMeta::new(state, "/c/")
        .title(format!("Categories on {}", state.config.app_name))
        .description(format!("{} {noun}: {}.", names.len(), name_list(&names, 4)))
}

/// `/c/{slug}`: [`category`] with the anonymous topic count and the newest
/// titles under it.
pub async fn category_page(state: &AppState, tree: &CategoryTree, c: &categories::Model) -> PageMeta {
    let path = format!("/c/{}", c.slug);
    let vis = anon_vis(tree);
    let mut loaded = crate::handlers::focus::category_topics(state, tree, &vis, c.id, crate::handlers::forum::TopicSort::Latest)
        .await
        .unwrap_or_default();
    let total = loaded.len() as u64;
    loaded.truncate(3);
    let titles: Vec<String> = loaded.into_iter().map(|(t, _)| t.title).collect();
    category(state, tree, c, &path, total, &titles)
}

/// `/tags`: the tags anonymous visitors can see, most used first.
pub async fn tags_index(state: &AppState, tree: &CategoryTree) -> PageMeta {
    let aggs = crate::handlers::tags::visible_tags(state, &anon_vis(tree)).await.unwrap_or_default();
    let names: Vec<String> = aggs.iter().filter(|a| a.cnt > 0).map(|a| format!("#{}", a.name)).collect();
    PageMeta::new(state, "/tags")
        .title(format!("Tags on {}", state.config.app_name))
        .description(format!("{} tags: {}.", names.len(), name_list(&names, 5)))
}

/// `/tag/{slug}`: the topics anonymous visitors can see under it.
pub async fn tag_page(state: &AppState, tree: &CategoryTree, slug: &str) -> PageMeta {
    let path = format!("/tag/{slug}");
    let aggs = crate::handlers::tags::visible_tags(state, &anon_vis(tree)).await.unwrap_or_default();
    let Some(agg) = aggs.into_iter().find(|a| a.slug == slug && a.cnt > 0) else {
        return PageMeta::new(state, &path).noindex(true);
    };
    let titles = crate::handlers::tags::topic_titles(state, &agg).await;
    let total = agg.cnt as u64;
    let noun = if total == 1 { "topic" } else { "topics" };
    let mut sentence = topics_sentence(total, &titles);
    sentence = sentence.replacen(&format!("{total} {noun}"), &format!("{total} {noun} tagged #{}", agg.name), 1);
    PageMeta::new(state, &path).title(format!("#{}", agg.name)).description(sentence)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_long_description_cuts_on_a_word_boundary() {
        let out = summarize(&"word ".repeat(100), 40);
        assert!(out.chars().count() <= 40, "{out:?} is over budget");
        assert!(out.ends_with('…'));
        assert!(!out.contains("wor…"), "cut mid-word: {out:?}");
        assert_eq!(summarize("  two\n  lines  ", 200), "two lines");
        assert_eq!(summarize(&"x".repeat(50), 10), "xxxxxxxxx…");
    }

    #[test]
    fn markdown_becomes_plain_text() {
        let (t, img) = plain_text(
            "# Hello\n\nSome **bold** and `code`, a [link](https://x.test).\n\n```\nfn main() {}\n```\n\n![a cat](/assets/cat.png) <b>raw</b>\n\n- one\n- two",
        );
        assert_eq!(summarize(&t, 200), "Hello Some bold and code, a link. raw one two");
        assert_eq!(img.as_deref(), Some("/assets/cat.png"));
    }

    #[test]
    fn only_our_own_images() {
        let base = "https://forum.example";
        assert_eq!(own_url(base, "/a.png").as_deref(), Some("https://forum.example/a.png"));
        assert_eq!(own_url(base, "https://forum.example/a.png").as_deref(), Some("https://forum.example/a.png"));
        assert_eq!(own_url(base, "https://evil.example/a.png"), None);
        assert_eq!(own_url(base, "//evil.example/a.png"), None);
    }

    #[test]
    fn names_read_as_a_sentence() {
        let t: Vec<String> = ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect();
        assert_eq!(name_list(&t[..2], 3), "A and B");
        assert_eq!(name_list(&t, 3), "A, B, C and 1 more");
        assert_eq!(topics_sentence(3, &t[..3]), "3 topics: A, B and C.");
        assert_eq!(topics_sentence(12, &t[..3]), "12 topics: A, B, C and 9 more.");
        assert_eq!(topics_sentence(0, &[]), "0 topics.");
    }
}