Skip to main content

zaun_client/compose/
embed.rs

1//! `EmbedBuilder`: a rich embed in the style of discord.js's, whose pictures are files to
2//! attach (discord.js's `attachment://`) or attachments the message already has.
3
4use std::path::{Path, PathBuf};
5
6use zaun_community_protocol::command::object::{Embed, EmbedAuthor, EmbedField, EmbedFooter};
7use zaun_community_protocol::ids::AttachmentId;
8
9use crate::error::Result;
10
11/// Stands in for a picture not uploaded yet, so its embed can be checked before the upload.
12const PLACEHOLDER: AttachmentId = AttachmentId::from_bytes([0; 16]);
13
14/// Where an embed's picture (or a message's file) comes from. Pictures are never remote
15/// URLs: a file is uploaded as one of the message's attachments, so no reader's client ever
16/// fetches anything from a third party.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Picture {
19    /// A local file, uploaded under its own name.
20    File(PathBuf),
21    /// Bytes, uploaded under `name` (whose extension gives the media type).
22    Bytes {
23        /// The file name.
24        name: String,
25        /// The contents.
26        data: Vec<u8>,
27    },
28    /// An attachment this member uploaded (and has not posted yet) or, for an edit, one the
29    /// message already has.
30    Attachment(AttachmentId),
31}
32
33impl Picture {
34    /// The file at `path`.
35    pub fn file(path: impl Into<PathBuf>) -> Self {
36        Self::File(path.into())
37    }
38
39    /// `data`, uploaded as a file named `name`.
40    pub fn bytes(name: impl Into<String>, data: impl Into<Vec<u8>>) -> Self {
41        Self::Bytes {
42            name: name.into(),
43            data: data.into(),
44        }
45    }
46
47    /// The attachment `id`.
48    #[must_use]
49    pub const fn attachment(id: AttachmentId) -> Self {
50        Self::Attachment(id)
51    }
52
53    /// The attachment's id when this is one already, `None` when it must be uploaded.
54    pub(crate) const fn id(&self) -> Option<AttachmentId> {
55        match self {
56            Self::Attachment(id) => Some(*id),
57            Self::File(_) | Self::Bytes { .. } => None,
58        }
59    }
60}
61
62impl From<PathBuf> for Picture {
63    fn from(path: PathBuf) -> Self {
64        Self::File(path)
65    }
66}
67
68impl From<&Path> for Picture {
69    fn from(path: &Path) -> Self {
70        Self::File(path.to_owned())
71    }
72}
73
74impl From<AttachmentId> for Picture {
75    fn from(id: AttachmentId) -> Self {
76        Self::Attachment(id)
77    }
78}
79
80impl From<&crate::Attachment> for Picture {
81    fn from(a: &crate::Attachment) -> Self {
82        Self::Attachment(a.id())
83    }
84}
85
86/// Which picture of an embed.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub(crate) enum Slot {
89    Image,
90    Thumbnail,
91    AuthorIcon,
92    FooterIcon,
93}
94
95impl Slot {
96    /// The field the protocol names it by.
97    pub(crate) const fn field(self) -> &'static str {
98        match self {
99            Self::Image => "embeds.image",
100            Self::Thumbnail => "embeds.thumbnail",
101            Self::AuthorIcon => "embeds.author.icon",
102            Self::FooterIcon => "embeds.footer.icon",
103        }
104    }
105}
106
107/// A rich embed, built with chained setters and sent with
108/// [`MessageOptions::embed`](crate::MessageOptions::embed):
109///
110/// ```no_run
111/// # fn f(channel: &zaun_client::Channel) -> zaun_client::Result<()> {
112/// use zaun_client::{EmbedBuilder, MessageOptions, Picture};
113///
114/// let embed = EmbedBuilder::new()
115///     .title("Release 1.2")
116///     .url("https://example.com/releases/1.2")
117///     .description("What changed")
118///     .color(0x5865F2)
119///     .author("Release bot", None, Some(Picture::file("bot.png")))
120///     .field("Fixes", "12", true)
121///     .field("Features", "3", true)
122///     .image(Picture::file("screenshot.png"))
123///     .footer("zaun", None);
124/// channel.send(MessageOptions::new().embed(embed))?;
125/// # Ok(())
126/// # }
127/// ```
128#[derive(Debug, Clone, Default, PartialEq, Eq)]
129pub struct EmbedBuilder {
130    /// Everything but the pictures still to upload.
131    embed: Embed,
132    /// Pictures by slot; a slot left empty keeps `embed`'s own id.
133    pictures: Vec<(Slot, Picture)>,
134}
135
136impl EmbedBuilder {
137    /// An empty embed. One needs a title, a description, an author, a footer, a picture or a
138    /// field to be sent.
139    #[must_use]
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// The title (1–256 characters).
145    #[must_use]
146    pub fn title(mut self, title: impl Into<String>) -> Self {
147        self.embed.title = Some(title.into());
148        self
149    }
150
151    /// The text (1–4 096 characters).
152    #[must_use]
153    pub fn description(mut self, description: impl Into<String>) -> Self {
154        self.embed.description = Some(description.into());
155        self
156    }
157
158    /// The title's link: `https://` only. A reader opens it by choice; nothing loads it.
159    #[must_use]
160    pub fn url(mut self, url: impl Into<String>) -> Self {
161        self.embed.url = Some(url.into());
162        self
163    }
164
165    /// The colour of its edge, `0xRRGGBB`.
166    #[must_use]
167    pub const fn color(mut self, color: u32) -> Self {
168        self.embed.color = Some(color);
169        self
170    }
171
172    /// A time it shows, ms since the Unix epoch.
173    #[must_use]
174    pub const fn timestamp(mut self, ms: u64) -> Self {
175        self.embed.timestamp = Some(ms);
176        self
177    }
178
179    /// The author line: a name (1–256 characters), a link (`https://`) and a small picture.
180    #[must_use]
181    pub fn author(
182        mut self,
183        name: impl Into<String>,
184        url: Option<&str>,
185        icon: Option<Picture>,
186    ) -> Self {
187        self.embed.author = Some(EmbedAuthor {
188            name: name.into(),
189            url: url.map(str::to_owned),
190            icon: None,
191        });
192        self.set(Slot::AuthorIcon, icon);
193        self
194    }
195
196    /// The footer line: a text (1–2 048 characters) and a small picture.
197    #[must_use]
198    pub fn footer(mut self, text: impl Into<String>, icon: Option<Picture>) -> Self {
199        self.embed.footer = Some(EmbedFooter {
200            text: text.into(),
201            icon: None,
202        });
203        self.set(Slot::FooterIcon, icon);
204        self
205    }
206
207    /// The large picture.
208    #[must_use]
209    pub fn image(mut self, picture: impl Into<Picture>) -> Self {
210        self.set(Slot::Image, Some(picture.into()));
211        self
212    }
213
214    /// The small picture in the corner.
215    #[must_use]
216    pub fn thumbnail(mut self, picture: impl Into<Picture>) -> Self {
217        self.set(Slot::Thumbnail, Some(picture.into()));
218        self
219    }
220
221    /// Adds a field (name 1–256, value 1–1 024 characters; up to 25), shown beside the
222    /// neighbouring inline fields when `inline`.
223    #[must_use]
224    pub fn field(
225        mut self,
226        name: impl Into<String>,
227        value: impl Into<String>,
228        inline: bool,
229    ) -> Self {
230        self.embed.fields.push(EmbedField {
231            name: name.into(),
232            value: value.into(),
233            inline,
234        });
235        self
236    }
237
238    /// The embed as the protocol has it, when no picture is left to upload.
239    #[must_use]
240    pub fn to_embed(&self) -> Option<Embed> {
241        self.resolve(|p| p.id())
242    }
243
244    /// Checks the embed against the protocol's rules (lengths, links, 25 fields, not empty),
245    /// as sending it would, without uploading anything.
246    ///
247    /// # Errors
248    /// [`Error::Protocol`](crate::Error::Protocol) naming the field and the rule.
249    pub fn check(&self) -> Result<()> {
250        crate::embed::check(&[self.shape()], None)
251    }
252
253    /// The pictures named, with their slots.
254    pub(crate) fn pictures(&self) -> impl Iterator<Item = (Slot, &Picture)> {
255        self.pictures.iter().map(|(s, p)| (*s, p))
256    }
257
258    /// The embed with each picture's id from `id`; `None` when one has none.
259    pub(crate) fn resolve(&self, id: impl Fn(&Picture) -> Option<AttachmentId>) -> Option<Embed> {
260        let mut e = self.embed.clone();
261        for (slot, picture) in &self.pictures {
262            let id = Some(id(picture)?);
263            match slot {
264                Slot::Image => e.image = id,
265                Slot::Thumbnail => e.thumbnail = id,
266                Slot::AuthorIcon => {
267                    if let Some(a) = e.author.as_mut() {
268                        a.icon = id;
269                    }
270                }
271                Slot::FooterIcon => {
272                    if let Some(f) = e.footer.as_mut() {
273                        f.icon = id;
274                    }
275                }
276            }
277        }
278        Some(e)
279    }
280
281    /// The embed with a stand-in for every picture still to upload, to check its shape.
282    pub(crate) fn shape(&self) -> Embed {
283        self.resolve(|p| Some(p.id().unwrap_or(PLACEHOLDER)))
284            .unwrap_or_else(|| self.embed.clone())
285    }
286
287    fn set(&mut self, slot: Slot, picture: Option<Picture>) {
288        self.pictures.retain(|(s, _)| *s != slot);
289        match picture {
290            Some(p) => self.pictures.push((slot, p)),
291            None => match slot {
292                Slot::Image => self.embed.image = None,
293                Slot::Thumbnail => self.embed.thumbnail = None,
294                // `author` and `footer` were just written without an icon.
295                Slot::AuthorIcon | Slot::FooterIcon => {}
296            },
297        }
298    }
299}
300
301impl From<Embed> for EmbedBuilder {
302    /// An embed as received ([`Message::embeds`](crate::Message::embeds)), to send again or
303    /// change: its pictures stay the attachments it names.
304    fn from(embed: Embed) -> Self {
305        Self {
306            embed,
307            pictures: Vec::new(),
308        }
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    const A: AttachmentId = AttachmentId::from_bytes([9; 16]);
317
318    #[test]
319    fn the_setters_fill_the_protocols_embed() {
320        let e = EmbedBuilder::new()
321            .title("T")
322            .description("D")
323            .url("https://example.com")
324            .color(0x00ff00)
325            .timestamp(1_700_000_000_000)
326            .author(
327                "A",
328                Some("https://example.com/a"),
329                Some(Picture::attachment(A)),
330            )
331            .footer("F", None)
332            .thumbnail(A)
333            .field("n1", "v1", true)
334            .field("n2", "v2", false)
335            .to_embed()
336            .unwrap();
337        assert_eq!(e.title.as_deref(), Some("T"));
338        assert_eq!(e.description.as_deref(), Some("D"));
339        assert_eq!(e.url.as_deref(), Some("https://example.com"));
340        assert_eq!(
341            (e.color, e.timestamp),
342            (Some(0x00ff00), Some(1_700_000_000_000))
343        );
344        let author = e.author.unwrap();
345        assert_eq!((author.name.as_str(), author.icon), ("A", Some(A)));
346        assert_eq!(author.url.as_deref(), Some("https://example.com/a"));
347        assert_eq!(e.footer.unwrap().icon, None);
348        assert_eq!((e.image, e.thumbnail), (None, Some(A)));
349        assert_eq!(e.fields.len(), 2);
350        assert!(e.fields[0].inline && !e.fields[1].inline);
351    }
352
353    #[test]
354    fn a_picture_still_to_upload_leaves_no_embed_until_it_has_an_id() {
355        let b = EmbedBuilder::new()
356            .title("t")
357            .image(Picture::file("cat.png"))
358            .footer("f", Some(Picture::bytes("icon.png", vec![1, 2, 3])));
359        assert_eq!(b.to_embed(), None);
360        assert_eq!(b.pictures().count(), 2);
361        // The shape stands a placeholder in for each, so the rules can be checked now.
362        let shape = b.shape();
363        assert_eq!(shape.image, Some(PLACEHOLDER));
364        assert_eq!(shape.footer.unwrap().icon, Some(PLACEHOLDER));
365        assert!(b.check().is_ok());
366        let done = b.resolve(|_| Some(A)).unwrap();
367        assert_eq!((done.image, done.footer.unwrap().icon), (Some(A), Some(A)));
368    }
369
370    #[test]
371    fn setting_a_picture_again_replaces_it() {
372        let b = EmbedBuilder::new()
373            .title("t")
374            .image(Picture::file("a.png"))
375            .image(A);
376        assert_eq!(b.pictures().count(), 1);
377        assert_eq!(b.to_embed().unwrap().image, Some(A));
378    }
379
380    #[test]
381    fn a_broken_embed_is_refused_before_anything_is_sent() {
382        assert!(EmbedBuilder::new().check().is_err(), "it shows nothing");
383        assert!(
384            EmbedBuilder::new().color(1).check().is_err(),
385            "a colour alone is nothing"
386        );
387        assert!(
388            EmbedBuilder::new()
389                .title("t")
390                .url("http://x.org")
391                .check()
392                .is_err()
393        );
394        assert!(
395            EmbedBuilder::new()
396                .description("d")
397                .url("https://x.org")
398                .check()
399                .is_err()
400        );
401        assert!(
402            EmbedBuilder::new()
403                .title("t")
404                .color(0x100_0000)
405                .check()
406                .is_err()
407        );
408        assert!(EmbedBuilder::new().title("x".repeat(257)).check().is_err());
409        let many = (0..26).fold(EmbedBuilder::new(), |b, i| {
410            b.field(i.to_string(), "v", false)
411        });
412        assert!(many.check().is_err());
413        assert!(EmbedBuilder::new().field("n", "", false).check().is_err());
414        assert!(
415            EmbedBuilder::new()
416                .image(Picture::file("a.png"))
417                .check()
418                .is_ok()
419        );
420    }
421
422    #[test]
423    fn a_received_embed_builds_back_unchanged() {
424        let e = EmbedBuilder::new().title("t").image(A).to_embed().unwrap();
425        let again = EmbedBuilder::from(e.clone()).description("more");
426        let out = again.to_embed().unwrap();
427        assert_eq!(out.image, Some(A));
428        assert_eq!(out.description.as_deref(), Some("more"));
429        assert_eq!(EmbedBuilder::from(e.clone()).to_embed(), Some(e));
430    }
431}