zaun_community_protocol/command/object/
embed.rs1use serde::{Deserialize, Serialize};
10
11use crate::command::{BodyError, check};
12use crate::ids::AttachmentId;
13use crate::limits::{
14 COLOR_MAX, EMBED_AUTHOR_NAME, EMBED_DESCRIPTION, EMBED_FIELD_NAME, EMBED_FIELD_VALUE,
15 EMBED_FIELDS, EMBED_FOOTER_TEXT, EMBED_TEXT_TOTAL, EMBED_TITLE, EMBED_URL_MAX,
16 EMBEDS_PER_MESSAGE,
17};
18
19#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
23pub struct Embed {
24 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub title: Option<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub description: Option<String>,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub url: Option<String>,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub color: Option<u32>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub timestamp: Option<u64>,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub author: Option<EmbedAuthor>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub footer: Option<EmbedFooter>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub image: Option<AttachmentId>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub thumbnail: Option<AttachmentId>,
52 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub fields: Vec<EmbedField>,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct EmbedAuthor {
60 pub name: String,
62 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub url: Option<String>,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub icon: Option<AttachmentId>,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct EmbedFooter {
73 pub text: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub icon: Option<AttachmentId>,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct EmbedField {
83 pub name: String,
85 pub value: String,
87 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
90 pub inline: bool,
91}
92
93impl Embed {
94 pub fn attachments(&self) -> impl Iterator<Item = (&'static str, AttachmentId)> + '_ {
97 [
98 ("embeds.image", self.image),
99 ("embeds.thumbnail", self.thumbnail),
100 (
101 "embeds.author.icon",
102 self.author.as_ref().and_then(|a| a.icon),
103 ),
104 (
105 "embeds.footer.icon",
106 self.footer.as_ref().and_then(|f| f.icon),
107 ),
108 ]
109 .into_iter()
110 .filter_map(|(field, id)| id.map(|id| (field, id)))
111 }
112
113 #[must_use]
115 pub fn is_empty(&self) -> bool {
116 self.title.is_none()
117 && self.description.is_none()
118 && self.author.is_none()
119 && self.footer.is_none()
120 && self.image.is_none()
121 && self.thumbnail.is_none()
122 && self.fields.is_empty()
123 }
124
125 fn text_len(&self) -> usize {
127 let opt = |s: Option<&String>| s.map_or(0, |s| s.chars().count());
128 opt(self.title.as_ref())
129 + opt(self.description.as_ref())
130 + opt(self.author.as_ref().map(|a| &a.name))
131 + opt(self.footer.as_ref().map(|f| &f.text))
132 + self
133 .fields
134 .iter()
135 .map(|f| f.name.chars().count() + f.value.chars().count())
136 .sum::<usize>()
137 }
138
139 fn check(&self) -> Result<(), BodyError> {
141 check::opt_text("embeds.title", self.title.as_deref(), EMBED_TITLE)?;
142 check::opt_text(
143 "embeds.description",
144 self.description.as_deref(),
145 EMBED_DESCRIPTION,
146 )?;
147 if let Some(url) = &self.url {
148 link("embeds.url", url)?;
149 if self.title.is_none() {
150 return Err(BodyError::bad("embeds.url", "needs a title"));
151 }
152 }
153 if let Some(color) = self.color {
154 check::range("embeds.color", color, 0, COLOR_MAX)?;
155 }
156 if let Some(timestamp) = self.timestamp {
157 check::json_safe("embeds.timestamp", timestamp)?;
158 }
159 if let Some(author) = &self.author {
160 check::text("embeds.author.name", &author.name, EMBED_AUTHOR_NAME)?;
161 if let Some(url) = &author.url {
162 link("embeds.author.url", url)?;
163 }
164 }
165 if let Some(footer) = &self.footer {
166 check::text("embeds.footer.text", &footer.text, EMBED_FOOTER_TEXT)?;
167 }
168 check::count("embeds.fields", self.fields.len(), EMBED_FIELDS)?;
169 for field in &self.fields {
170 check::text("embeds.fields.name", &field.name, EMBED_FIELD_NAME)?;
171 check::text("embeds.fields.value", &field.value, EMBED_FIELD_VALUE)?;
172 }
173 if self.is_empty() {
174 return Err(BodyError::bad("embeds", "an embed shows nothing"));
175 }
176 Ok(())
177 }
178}
179
180pub(crate) fn link(field: &str, url: &str) -> Result<(), BodyError> {
184 if url.len() > EMBED_URL_MAX {
185 return Err(BodyError::too_large(field, EMBED_URL_MAX));
186 }
187 let rest = url
188 .get(..8)
189 .filter(|scheme| scheme.eq_ignore_ascii_case("https://"))
190 .map(|_| &url[8..]);
191 let Some(rest) = rest else {
192 return Err(BodyError::bad(field, "must be an https:// link"));
193 };
194 if rest.is_empty() || rest.starts_with(['/', '?', '#']) {
195 return Err(BodyError::bad(field, "has no host"));
196 }
197 let authority = rest.split(['/', '?', '#', '\\']).next().unwrap_or_default();
201 if authority.contains('@') {
202 return Err(BodyError::bad(field, "has a user name or password"));
203 }
204 if url
205 .chars()
206 .any(|c| c.is_whitespace() || c.is_control() || is_bidi(c))
207 {
208 return Err(BodyError::bad(
209 field,
210 "contains whitespace or a control character",
211 ));
212 }
213 Ok(())
214}
215
216const fn is_bidi(c: char) -> bool {
218 matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
219}
220
221#[must_use]
228pub fn message_json_len(content: &str, embeds: &[Embed]) -> usize {
229 let len = |r: serde_json::Result<String>| r.map_or(usize::MAX, |s| s.len());
230 len(serde_json::to_string(content)).saturating_add(len(serde_json::to_string(embeds)))
231}
232
233#[must_use]
236pub fn message_json_len_with(
237 content: &str,
238 embeds: &[Embed],
239 components: &[super::Component],
240) -> usize {
241 let extra = if components.is_empty() {
242 0
243 } else {
244 serde_json::to_string(components).map_or(usize::MAX, |s| s.len())
245 };
246 message_json_len(content, embeds).saturating_add(extra)
247}
248
249pub fn check_embeds(
257 embeds: &[Embed],
258 attachments: Option<&[AttachmentId]>,
259) -> Result<(), BodyError> {
260 check::count("embeds", embeds.len(), EMBEDS_PER_MESSAGE)?;
261 let mut total = 0usize;
262 for embed in embeds {
263 embed.check()?;
264 total += embed.text_len();
265 }
266 if total > EMBED_TEXT_TOTAL {
267 return Err(BodyError::too_large("embeds", EMBED_TEXT_TOTAL));
268 }
269 match attachments {
270 Some(listed) => check_pictures(embeds, listed),
271 None => Ok(()),
272 }
273}
274
275pub fn check_pictures(embeds: &[Embed], attachments: &[AttachmentId]) -> Result<(), BodyError> {
282 for embed in embeds {
283 for (field, id) in embed.attachments() {
284 if !attachments.contains(&id) {
285 return Err(BodyError::bad(
286 field,
287 "is not one of the message's attachments",
288 ));
289 }
290 }
291 }
292 Ok(())
293}