Skip to main content

djs_model/
emoji.rs

1//! [Emojis](https://docs.discord.com/developers/resources/emoji): custom guild and application
2//! emojis, and the partial emojis used in reactions, components and polls.
3
4use core::fmt;
5
6use compact_str::CompactString;
7use serde::{
8    Deserialize, Deserializer, Serialize, Serializer,
9    de::{Error as DeError, IgnoredAny, MapAccess, Visitor},
10    ser::SerializeStruct,
11};
12
13use crate::{
14    id::{EmojiId, RoleId},
15    user::User,
16};
17
18/// A custom emoji uploaded to a guild or owned by an application.
19///
20/// See the [emoji object](https://docs.discord.com/developers/resources/emoji#emoji-object).
21/// Emojis inside reactions, buttons and polls are [`PartialEmoji`]s (D-056).
22///
23/// discord.js counterpart: `GuildEmoji` / `ApplicationEmoji`.
24///
25/// # Examples
26///
27/// ```
28/// use djs_model::emoji::Emoji;
29///
30/// let emoji: Emoji = serde_json::from_str(
31///     r#"{"id":"41771983429993937","name":"LUL","roles":[],"require_colons":true,
32///         "managed":false,"animated":false}"#,
33/// )?;
34/// assert_eq!(emoji.name, "LUL");
35/// assert!(emoji.available, "absent `available` means usable (D-055)");
36/// # Ok::<(), serde_json::Error>(())
37/// ```
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[non_exhaustive]
40pub struct Emoji {
41    /// The emoji's ID.
42    pub id: EmojiId,
43    /// The emoji's name.
44    pub name: CompactString,
45    /// The roles allowed to use the emoji; empty means everyone. Emojis restricted to
46    /// subscription roles are premium emojis.
47    #[serde(default)]
48    pub roles: Vec<RoleId>,
49    /// Who uploaded the emoji: for guild emojis only visible with the
50    /// [`MANAGE_GUILD_EXPRESSIONS`](crate::permissions::Permissions::MANAGE_GUILD_EXPRESSIONS)
51    /// permission; for application emojis the team member or the bot.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub user: Option<Box<User>>,
54    /// Whether the emoji must be wrapped in colons to be used.
55    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
56    pub require_colons: bool,
57    /// Whether the emoji is managed by an integration (e.g. Twitch).
58    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
59    pub managed: bool,
60    /// Whether the emoji is animated.
61    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
62    pub animated: bool,
63    /// Whether the emoji can be used; `false` when the guild lost the Server Boosts it needs.
64    /// `true` when Discord omits the field (D-055).
65    #[serde(default = "crate::serde_util::default_true")]
66    pub available: bool,
67}
68
69/// An emoji as used in reactions, message components and polls: either a custom emoji or a
70/// Unicode emoji (D-056).
71///
72/// See the [emoji object](https://docs.discord.com/developers/resources/emoji#emoji-object)
73/// examples for standard and custom emojis.
74///
75/// discord.js counterpart: `PartialEmoji` / `ReactionEmoji`.
76///
77/// # Examples
78///
79/// ```
80/// use djs_model::emoji::PartialEmoji;
81///
82/// let fire: PartialEmoji = serde_json::from_str(r#"{"id":null,"name":"🔥"}"#)?;
83/// assert_eq!(fire, PartialEmoji::Unicode { name: "🔥".into() });
84///
85/// let custom: PartialEmoji = serde_json::from_str(r#"{"id":"41771983429993937","name":"LUL","animated":true}"#)?;
86/// assert!(matches!(custom, PartialEmoji::Custom { animated: true, .. }));
87/// assert_eq!(custom.name(), Some("LUL"));
88/// # Ok::<(), serde_json::Error>(())
89/// ```
90#[derive(Clone, Debug, PartialEq, Eq, Hash)]
91pub enum PartialEmoji {
92    /// A custom (guild or application) emoji.
93    Custom {
94        /// The emoji's ID.
95        id: EmojiId,
96        /// The emoji's name; `None` when Discord no longer has the emoji's data (for example a
97        /// deleted emoji in reaction events).
98        name: Option<CompactString>,
99        /// Whether the emoji is animated.
100        animated: bool,
101    },
102    /// A standard Unicode emoji such as `🔥`.
103    Unicode {
104        /// The emoji itself.
105        name: CompactString,
106    },
107}
108
109impl PartialEmoji {
110    /// Returns the custom emoji's ID, or `None` for a Unicode emoji.
111    ///
112    /// discord.js counterpart: `Emoji#id`.
113    #[must_use]
114    pub const fn id(&self) -> Option<EmojiId> {
115        match *self {
116            Self::Custom { id, .. } => Some(id),
117            Self::Unicode { .. } => None,
118        }
119    }
120
121    /// Returns the emoji's name (the emoji itself for Unicode emojis), if known.
122    ///
123    /// discord.js counterpart: `Emoji#name`.
124    #[must_use]
125    pub fn name(&self) -> Option<&str> {
126        match self {
127            Self::Custom { name, .. } => name.as_deref(),
128            Self::Unicode { name } => Some(name),
129        }
130    }
131}
132
133impl From<&Emoji> for PartialEmoji {
134    fn from(emoji: &Emoji) -> Self {
135        Self::Custom {
136            id: emoji.id,
137            name: Some(emoji.name.clone()),
138            animated: emoji.animated,
139        }
140    }
141}
142
143impl Serialize for PartialEmoji {
144    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
145        match self {
146            Self::Custom { id, name, animated } => {
147                let mut state =
148                    serializer.serialize_struct("PartialEmoji", 2 + usize::from(*animated))?;
149                state.serialize_field("id", id)?;
150                state.serialize_field("name", name)?;
151                if *animated {
152                    state.serialize_field("animated", &true)?;
153                }
154                state.end()
155            }
156            Self::Unicode { name } => {
157                let mut state = serializer.serialize_struct("PartialEmoji", 2)?;
158                state.serialize_field("id", &None::<EmojiId>)?;
159                state.serialize_field("name", name)?;
160                state.end()
161            }
162        }
163    }
164}
165
166impl<'de> Deserialize<'de> for PartialEmoji {
167    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
168        #[derive(Deserialize)]
169        #[serde(field_identifier, rename_all = "snake_case")]
170        enum Field {
171            Id,
172            Name,
173            Animated,
174            #[serde(other)]
175            Other,
176        }
177
178        struct EmojiVisitor;
179
180        impl<'de> Visitor<'de> for EmojiVisitor {
181            type Value = PartialEmoji;
182
183            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184                f.write_str("a partial emoji object")
185            }
186
187            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<PartialEmoji, A::Error> {
188                let (mut id, mut name, mut animated) = (None, None, false);
189                while let Some(field) = map.next_key()? {
190                    match field {
191                        Field::Id => id = map.next_value::<Option<EmojiId>>()?,
192                        Field::Name => name = map.next_value::<Option<CompactString>>()?,
193                        Field::Animated => {
194                            animated = map.next_value::<Option<bool>>()?.unwrap_or_default();
195                        }
196                        Field::Other => {
197                            map.next_value::<IgnoredAny>()?;
198                        }
199                    }
200                }
201                match (id, name) {
202                    (Some(id), name) => Ok(PartialEmoji::Custom { id, name, animated }),
203                    (None, Some(name)) => Ok(PartialEmoji::Unicode { name }),
204                    (None, None) => Err(A::Error::custom("emoji has neither an id nor a name")),
205                }
206            }
207        }
208
209        deserializer.deserialize_map(EmojiVisitor)
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn documented_emoji_example() {
219        let json = r#"{"id":"41771983429993937","name":"LUL",
220            "roles":["41771983429993000","41771983429993111"],
221            "user":{"username":"Luigi","discriminator":"0002","id":"96008815106887111",
222                    "avatar":"5500909a3274e1812beb4e8de6631111","public_flags":131328},
223            "require_colons":true,"managed":false,"animated":false}"#;
224        let emoji: Emoji = serde_json::from_str(json).unwrap();
225        assert_eq!(emoji.id.get(), 41_771_983_429_993_937);
226        assert_eq!(emoji.roles.len(), 2);
227        assert_eq!(emoji.user.as_ref().unwrap().discriminator, 2);
228        assert!(emoji.require_colons);
229        assert!(emoji.available);
230        let unavailable: Emoji =
231            serde_json::from_str(r#"{"id":"1","name":"x","available":false}"#).unwrap();
232        assert!(!unavailable.available);
233    }
234
235    #[test]
236    fn partial_emoji_shapes() {
237        let deleted: PartialEmoji =
238            serde_json::from_str(r#"{"id":"41771983429993937","name":null}"#).unwrap();
239        assert_eq!(deleted.name(), None);
240        assert_eq!(
241            deleted.id().map(crate::id::Id::get),
242            Some(41_771_983_429_993_937)
243        );
244
245        // Serialization mirrors the received shapes.
246        for json in [
247            r#"{"id":null,"name":"🔥"}"#,
248            r#"{"id":"41771983429993937","name":"LUL","animated":true}"#,
249            r#"{"id":"41771983429993937","name":null}"#,
250        ] {
251            let emoji: PartialEmoji = serde_json::from_str(json).unwrap();
252            assert_eq!(serde_json::to_string(&emoji).unwrap(), json);
253        }
254
255        // Unknown fields are ignored; an emoji without id and name is rejected.
256        assert!(serde_json::from_str::<PartialEmoji>(r#"{"name":"🔥","x":[1]}"#).is_ok());
257        assert!(serde_json::from_str::<PartialEmoji>(r#"{"id":null,"name":null}"#).is_err());
258    }
259}