Skip to main content

zaun_bot/
mention.rs

1//! Mentions: the text that shows them (`<@id>`, `<@&id>`, `@everyone`) and what a message
2//! names in its `mentions`. Zaun names mentions explicitly: the host never reads them from the
3//! text, so a message notifies only who its [`Mentions`] list.
4
5use crate::types::{Id, Mentions};
6
7/// The text that shows `@everyone`.
8pub const EVERYONE: &str = "@everyone";
9/// Most members one message may mention (spec §12).
10pub const MAX_MEMBERS: usize = 50;
11/// Most roles one message may mention (spec §12).
12pub const MAX_ROLES: usize = 20;
13
14/// The text that shows a member mention: `<@id>` (discord.js `userMention`).
15#[must_use]
16pub fn member(id: &str) -> String {
17    format!("<@{id}>")
18}
19
20/// The text that shows a role mention: `<@&id>` (discord.js `roleMention`).
21#[must_use]
22pub fn role(id: &str) -> String {
23    format!("<@&{id}>")
24}
25
26/// No mentions.
27#[must_use]
28pub fn none() -> Mentions {
29    Mentions {
30        everyone: false,
31        members: Vec::new(),
32        roles: Vec::new(),
33    }
34}
35
36/// Whether `id` is a well-formed Zaun id: 16 bytes in unpadded base64url (22 characters, the
37/// last one of `A`, `Q`, `g`, `w`).
38#[must_use]
39pub fn is_id(id: &str) -> bool {
40    let b = id.as_bytes();
41    b.len() == 22
42        && b.iter()
43            .all(|c| c.is_ascii_alphanumeric() || *c == b'-' || *c == b'_')
44        && matches!(b[21], b'A' | b'Q' | b'g' | b'w')
45}
46
47/// The mentions `content` shows: `<@id>` (and Discord's `<@!id>`) for members, `<@&id>` for
48/// roles, `@everyone`. Each id once, in order, at most [`MAX_MEMBERS`] members and
49/// [`MAX_ROLES`] roles; malformed ids are skipped. Use it only on text the bot wrote: on
50/// text from members it would mention whoever they named.
51#[must_use]
52pub fn parse(content: &str) -> Mentions {
53    let mut out = none();
54    out.everyone = content.contains(EVERYONE);
55    let mut rest = content;
56    while let Some(start) = rest.find("<@") {
57        rest = &rest[start + 2..];
58        // A tag ends at the first `>`; a `<` or a space first means this was not one.
59        let end = rest
60            .find(|c: char| c == '>' || c == '<' || c.is_whitespace())
61            .unwrap_or(rest.len());
62        if !rest[end..].starts_with('>') {
63            continue;
64        }
65        let inner = &rest[..end];
66        let (is_role, id) = match inner.as_bytes().first() {
67            Some(b'&') => (true, &inner[1..]),
68            Some(b'!') => (false, &inner[1..]),
69            _ => (false, inner),
70        };
71        if is_id(id) {
72            let (list, max) = if is_role {
73                (&mut out.roles, MAX_ROLES)
74            } else {
75                (&mut out.members, MAX_MEMBERS)
76            };
77            push_unique(list, id, max);
78        }
79        rest = &rest[end + 1..];
80    }
81    out
82}
83
84/// Adds `id` to `list` unless it is there or the list holds `max`.
85pub(crate) fn push_unique(list: &mut Vec<Id>, id: &str, max: usize) {
86    if list.len() < max && !list.iter().any(|x| x == id) {
87        list.push(id.to_owned());
88    }
89}
90
91/// Merges `more` into `into`: `everyone` if either has it, each member and role once.
92pub(crate) fn merge(into: &mut Mentions, more: Mentions) {
93    into.everyone |= more.everyone;
94    for m in more.members {
95        push_unique(&mut into.members, &m, usize::MAX);
96    }
97    for r in more.roles {
98        push_unique(&mut into.roles, &r, usize::MAX);
99    }
100}
101
102impl Mentions {
103    /// Whether member `id` is named.
104    #[must_use]
105    pub fn has_member(&self, id: &str) -> bool {
106        self.members.iter().any(|m| m == id)
107    }
108
109    /// Whether role `id` is named.
110    #[must_use]
111    pub fn has_role(&self, id: &str) -> bool {
112        self.roles.iter().any(|r| r == id)
113    }
114
115    /// Whether a member with `member_id` and `role_ids` is mentioned: by id, by one of its
116    /// roles, or by `@everyone`.
117    #[must_use]
118    pub fn includes(&self, member_id: &str, role_ids: &[Id]) -> bool {
119        self.everyone || self.has_member(member_id) || role_ids.iter().any(|r| self.has_role(r))
120    }
121
122    /// Whether nobody is mentioned.
123    #[must_use]
124    pub fn is_empty(&self) -> bool {
125        !self.everyone && self.members.is_empty() && self.roles.is_empty()
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    const A: &str = "AAAAAAAAAAAAAAAAAAAAAA";
134    const B: &str = "BBBBBBBBBBBBBBBBBBBBBQ";
135
136    #[test]
137    fn parse_finds_members_roles_and_everyone_once_each() {
138        // `<@ x` and `<@&` are not tags; the well-formed tags right after them still count.
139        const C: &str = "CCCCCCCCCCCCCCCCCCCCCg";
140        let text = format!("hi <@ x <@{C}> <@{A}> <@!{A}> <@&<@&{B}> @everyone <@{B}x> <@&short>");
141        let m = parse(&text);
142        assert!(m.everyone);
143        assert_eq!(m.members, vec![C.to_owned(), A.to_owned()]);
144        assert_eq!(m.roles, vec![B.to_owned()]);
145        assert_eq!(member(A), format!("<@{A}>"));
146        assert_eq!(role(B), format!("<@&{B}>"));
147    }
148
149    #[test]
150    fn parse_skips_malformed_ids_and_stops_at_the_limits() {
151        assert!(
152            !is_id("AAAAAAAAAAAAAAAAAAAAAB"),
153            "a 16-byte id ends in A, Q, g or w"
154        );
155        let many: String = (0..60).map(|n| format!("<@{n:0>21}A>")).collect();
156        assert_eq!(parse(&many).members.len(), MAX_MEMBERS);
157        assert!(parse("plain text").is_empty());
158    }
159
160    #[test]
161    fn includes_counts_members_roles_and_everyone() {
162        let m = parse(&format!("<@&{B}>"));
163        assert!(m.includes(A, &[B.to_owned()]));
164        assert!(!m.includes(A, &[]));
165        assert!(parse("@everyone").includes(A, &[]));
166    }
167}
168
169impl crate::types::Member {
170    /// The text that shows a mention of this member: `<@member_id>`.
171    #[must_use]
172    pub fn mention(&self) -> String {
173        member(&self.member_id)
174    }
175}
176
177impl crate::types::Role {
178    /// The text that shows a mention of this role: `<@&role_id>`.
179    #[must_use]
180    pub fn mention(&self) -> String {
181        role(&self.role_id)
182    }
183}