1use 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
11const PLACEHOLDER: AttachmentId = AttachmentId::from_bytes([0; 16]);
13
14#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Picture {
19 File(PathBuf),
21 Bytes {
23 name: String,
25 data: Vec<u8>,
27 },
28 Attachment(AttachmentId),
31}
32
33impl Picture {
34 pub fn file(path: impl Into<PathBuf>) -> Self {
36 Self::File(path.into())
37 }
38
39 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 #[must_use]
49 pub const fn attachment(id: AttachmentId) -> Self {
50 Self::Attachment(id)
51 }
52
53 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub(crate) enum Slot {
89 Image,
90 Thumbnail,
91 AuthorIcon,
92 FooterIcon,
93}
94
95impl Slot {
96 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
129pub struct EmbedBuilder {
130 embed: Embed,
132 pictures: Vec<(Slot, Picture)>,
134}
135
136impl EmbedBuilder {
137 #[must_use]
140 pub fn new() -> Self {
141 Self::default()
142 }
143
144 #[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 #[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 #[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 #[must_use]
167 pub const fn color(mut self, color: u32) -> Self {
168 self.embed.color = Some(color);
169 self
170 }
171
172 #[must_use]
174 pub const fn timestamp(mut self, ms: u64) -> Self {
175 self.embed.timestamp = Some(ms);
176 self
177 }
178
179 #[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 #[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 #[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 #[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 #[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 #[must_use]
240 pub fn to_embed(&self) -> Option<Embed> {
241 self.resolve(|p| p.id())
242 }
243
244 pub fn check(&self) -> Result<()> {
250 crate::embed::check(&[self.shape()], None)
251 }
252
253 pub(crate) fn pictures(&self) -> impl Iterator<Item = (Slot, &Picture)> {
255 self.pictures.iter().map(|(s, p)| (*s, p))
256 }
257
258 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 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 Slot::AuthorIcon | Slot::FooterIcon => {}
296 },
297 }
298 }
299}
300
301impl From<Embed> for EmbedBuilder {
302 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 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}