Skip to main content

babyrite/
expand.rs

1//! Link expansion module.
2//!
3//! This module provides common types for expanding various types of links
4//! (Discord message links, GitHub permalinks, etc.) into rich preview content.
5
6pub mod discord;
7pub mod github;
8
9use crate::config::BabyriteConfig;
10use crate::context::BotContext;
11use regex::Regex;
12use std::collections::HashSet;
13use twilight_model::channel::{Message, message::Embed};
14use twilight_model::id::{Id, marker::GuildMarker};
15
16/// Shared inputs for expanding the links of one message.
17pub struct ExpandContext<'a> {
18    /// The shared bot state.
19    pub ctx: &'a BotContext,
20    /// The message whose links are being expanded.
21    pub message: &'a Message,
22    /// The guild the message was sent in.
23    pub guild_id: Id<GuildMarker>,
24}
25
26/// A link expander: parses its own link type out of a message and expands
27/// each link into [`ExpandedContent`].
28///
29/// Adding a new link type means implementing this trait and registering the
30/// expander in [`EXPANDERS`]; the event handler needs no changes.
31#[async_trait::async_trait]
32pub trait LinkExpander: Send + Sync {
33    /// Whether this expander is enabled under `config`.
34    fn enabled(&self, config: &BabyriteConfig) -> bool;
35
36    /// Parses and expands all links of this expander's type in the message.
37    ///
38    /// Failures are logged per link and never abort the other links or
39    /// expanders, so this returns only the successful expansions. Links skipped
40    /// on purpose — because expanding them would leak content the audience
41    /// cannot see, or because there is nothing to show — are logged at `debug`
42    /// rather than `error`.
43    async fn expand_all(&self, cx: &ExpandContext<'_>) -> Vec<ExpandedContent>;
44}
45
46/// All registered link expanders, in the order their results appear in a reply.
47pub static EXPANDERS: &[&dyn LinkExpander] = &[&discord::DiscordExpander, &github::GitHubExpander];
48
49/// Maximum number of links expanded per message.
50const MAX_LINKS_PER_MESSAGE: usize = 3;
51
52/// Extracts links matching `regex` from `text`, applying the shared link policy:
53/// URLs wrapped in angle brackets (e.g. `<https://...>`) are skipped, duplicate
54/// URLs are ignored, and at most [`MAX_LINKS_PER_MESSAGE`] links are returned.
55///
56/// `parse` converts a regex match into the expander-specific link type;
57/// returning `None` drops that match.
58pub(crate) fn parse_links<T>(
59    text: &str,
60    regex: &Regex,
61    parse: impl Fn(&regex::Captures) -> Option<T>,
62) -> Vec<T> {
63    let mut seen_urls = HashSet::new();
64    regex
65        .captures_iter(text)
66        .filter_map(|captures| {
67            let m = captures.get(0)?;
68            if m.start() > 0 && text.as_bytes()[m.start() - 1] == b'<' {
69                return None;
70            }
71            if !seen_urls.insert(m.as_str()) {
72                return None;
73            }
74            parse(&captures)
75        })
76        .take(MAX_LINKS_PER_MESSAGE)
77        .collect()
78}
79
80/// Expanded content produced by a link expander.
81///
82/// Represents the different kinds of content that can result from
83/// expanding a link.
84pub enum ExpandedContent {
85    /// A Discord message preview displayed as an embed.
86    ///
87    /// Boxed because an embed dwarfs the other variant.
88    Embed(Box<Embed>),
89    /// A code block with syntax highlighting (e.g. GitHub permalink).
90    CodeBlock {
91        /// The programming language for syntax highlighting.
92        language: String,
93        /// The code content.
94        code: String,
95        /// Metadata line displayed above the code block (e.g. file path, line range).
96        metadata: String,
97    },
98}
99
100/// Errors that can occur during link expansion.
101#[derive(thiserror::Error, Debug)]
102pub enum ExpandError {
103    /// An error from the Discord message link expander.
104    #[error(transparent)]
105    Discord(#[from] discord::PreviewError),
106    /// An error from the GitHub permalink expander.
107    #[error(transparent)]
108    GitHub(#[from] github::GitHubExpandError),
109}