Skip to main content

zaun_client/
mention.rs

1//! Mentions (specification ยง8.5): the text that shows one and the list that notifies.
2
3use zaun_community_protocol::ids::{MemberId, RoleId};
4use zaun_community_protocol::limits::{MENTION_MEMBERS, MENTION_ROLES};
5
6/// Who a message mentions, as the protocol has it ([`Message::mentions`](crate::Message)).
7pub use zaun_community_protocol::command::object::Mentions;
8
9/// The text that shows `@everyone`.
10pub const EVERYONE: &str = "@everyone";
11
12/// The text that shows a member mention, `<@id>` (discord.js `userMention`). It only shows
13/// where the mention is: the message's mentions list is what notifies.
14#[must_use]
15pub fn member(id: MemberId) -> String {
16    format!("<@{}>", id.to_b64())
17}
18
19/// The text that shows a role mention, `<@&id>` (discord.js `roleMention`).
20#[must_use]
21pub fn role(id: RoleId) -> String {
22    format!("<@&{}>", id.to_b64())
23}
24
25/// The mentions `content` shows: `<@id>` (and Discord's `<@!id>`) for members, `<@&id>` for
26/// roles, `@everyone`. Each id once, in order, at most 50 members and 20 roles; malformed
27/// ids are skipped. Use it on text this member wrote, not on text from someone else.
28#[must_use]
29pub fn parse(content: &str) -> Mentions {
30    let mut out = Mentions {
31        everyone: content.contains(EVERYONE),
32        ..Mentions::default()
33    };
34    let mut rest = content;
35    while let Some(start) = rest.find("<@") {
36        rest = &rest[start + 2..];
37        // A tag ends at the first `>`; a `<` or a space first means this was not one.
38        let end = rest
39            .find(|c: char| c == '>' || c == '<' || c.is_whitespace())
40            .unwrap_or(rest.len());
41        if !rest[end..].starts_with('>') {
42            continue;
43        }
44        let inner = &rest[..end];
45        rest = &rest[end + 1..];
46        if let Some(id) = inner.strip_prefix('&') {
47            if let Ok(id) = RoleId::from_b64(id)
48                && out.roles.len() < MENTION_ROLES
49                && !out.roles.contains(&id)
50            {
51                out.roles.push(id);
52            }
53        } else if let Ok(id) = MemberId::from_b64(inner.strip_prefix('!').unwrap_or(inner))
54            && out.members.len() < MENTION_MEMBERS
55            && !out.members.contains(&id)
56        {
57            out.members.push(id);
58        }
59    }
60    out
61}
62
63/// `extra` added to `into`: `everyone` if either has it, each member and role once.
64#[cfg(not(target_arch = "wasm32"))]
65pub(crate) fn merge(into: &mut Mentions, extra: Mentions) {
66    into.everyone |= extra.everyone;
67    for m in extra.members {
68        if !into.members.contains(&m) {
69            into.members.push(m);
70        }
71    }
72    for r in extra.roles {
73        if !into.roles.contains(&r) {
74            into.roles.push(r);
75        }
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    const A: MemberId = MemberId::from_bytes([1; 16]);
84    const R: RoleId = RoleId::from_bytes([2; 16]);
85
86    #[test]
87    fn parse_reads_each_well_formed_mention_once() {
88        // `<@ x` and `<@&` are not tags; the well-formed tags right after them still count.
89        let b = MemberId::from_bytes([3; 16]);
90        let text = format!(
91            "<@ x {} {} <@!{}> <@&{} @everyone <@nope> <@&{}x>",
92            member(b),
93            member(A),
94            A.to_b64(),
95            role(R),
96            R.to_b64()
97        );
98        let m = parse(&text);
99        assert!(m.everyone);
100        assert_eq!((m.members, m.roles), (vec![b, A], vec![R]));
101        assert_eq!(parse("plain"), Mentions::default());
102    }
103
104    #[test]
105    fn parse_stops_at_the_protocol_limits() {
106        let many: String = (0..60u8)
107            .map(|n| member(MemberId::from_bytes([n; 16])))
108            .collect();
109        assert_eq!(parse(&many).members.len(), MENTION_MEMBERS);
110    }
111}