Skip to main content

djs_model/util/
sound_data.rs

1//! [`SoundData`]: a sound sent inline in a request body as a data URI (D-122).
2
3use core::fmt;
4
5use bytes::Bytes;
6use compact_str::CompactString;
7use serde::{Serialize, Serializer};
8
9use super::image_data::write_base64;
10
11/// A sound sent inside a JSON request body as a data URI (`data:audio/mpeg;base64,…`), like
12/// [`ImageData`](super::ImageData) for images (D-122).
13///
14/// Used by [Create Guild Soundboard Sound](https://docs.discord.com/developers/resources/soundboard#create-guild-soundboard-sound).
15/// The sound is kept as [`Bytes`] and base64-encoded while the body is serialized.
16///
17/// discord.js counterpart: the `file` option of `GuildSoundboardSoundManager#create`.
18///
19/// # Examples
20///
21/// ```
22/// use djs_model::util::SoundData;
23///
24/// // A (truncated) Ogg file: the media type is read from the file signature.
25/// let sound = SoundData::new(&b"OggS\0\x02"[..]).unwrap();
26/// assert_eq!(sound.content_type(), "audio/ogg");
27/// assert_eq!(sound.to_string(), "data:audio/ogg;base64,T2dnUwAC");
28///
29/// assert!(SoundData::new(&b"\x89PNG\r\n\x1a\n"[..]).is_err());
30/// ```
31#[derive(Clone, PartialEq, Eq, Hash)]
32pub struct SoundData {
33    data: Bytes,
34    content_type: CompactString,
35}
36
37impl SoundData {
38    /// A sound whose media type is detected from its file signature: MP3 (with an ID3 tag
39    /// or starting with a frame) or Ogg.
40    ///
41    /// discord.js counterpart: `BufferResolvable` and `Base64Resolvable`, as `GuildSoundboardSoundCreateOptions#file` takes them.
42    ///
43    /// # Errors
44    ///
45    /// [`SoundDataError`] when `data` is neither; use
46    /// [`with_content_type`](Self::with_content_type) to send it anyway.
47    pub fn new(data: impl Into<Bytes>) -> Result<Self, SoundDataError> {
48        let data = data.into();
49        let content_type = detect(&data).ok_or(SoundDataError)?;
50        Ok(Self {
51            data,
52            content_type: CompactString::const_new(content_type),
53        })
54    }
55
56    /// A sound of the given media type (e.g. `audio/mpeg`), which is not checked.
57    ///
58    /// discord.js counterpart: `BufferResolvable` and `Base64Resolvable`, as `GuildSoundboardSoundCreateOptions#file` takes them.
59    #[must_use]
60    pub fn with_content_type(
61        data: impl Into<Bytes>,
62        content_type: impl Into<CompactString>,
63    ) -> Self {
64        Self {
65            data: data.into(),
66            content_type: content_type.into(),
67        }
68    }
69
70    /// The sound file's contents.
71    ///
72    /// discord.js counterpart: none (discord.js turns sounds into data URIs internally).
73    #[must_use]
74    pub const fn data(&self) -> &Bytes {
75        &self.data
76    }
77
78    /// The sound's media type (e.g. `audio/ogg`).
79    ///
80    /// discord.js counterpart: none (discord.js detects the type internally).
81    #[must_use]
82    pub fn content_type(&self) -> &str {
83        &self.content_type
84    }
85}
86
87/// Writes the data URI.
88impl fmt::Display for SoundData {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str("data:")?;
91        f.write_str(&self.content_type)?;
92        f.write_str(";base64,")?;
93        write_base64(&self.data, f)
94    }
95}
96
97/// Shows the media type and the size, not the contents.
98impl fmt::Debug for SoundData {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.debug_struct("SoundData")
101            .field("content_type", &self.content_type)
102            .field("len", &self.data.len())
103            .finish()
104    }
105}
106
107impl Serialize for SoundData {
108    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
109        serializer.collect_str(self)
110    }
111}
112
113/// The error of [`SoundData::new`]: the data is not an MP3 or Ogg file.
114///
115/// discord.js counterpart: none (discord.js accepts any buffer and lets Discord refuse it).
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub struct SoundDataError;
119
120impl fmt::Display for SoundDataError {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.write_str("unknown sound format (expected MP3 or Ogg)")
123    }
124}
125
126impl core::error::Error for SoundDataError {}
127
128/// The media type of `data` from its file signature.
129fn detect(data: &[u8]) -> Option<&'static str> {
130    match data {
131        [b'O', b'g', b'g', b'S', ..] => Some("audio/ogg"),
132        // An ID3v2 tag, or an MPEG audio frame (11 set sync bits).
133        [b'I', b'D', b'3', ..] => Some("audio/mpeg"),
134        [0xff, second, ..] if second & 0xe0 == 0xe0 => Some("audio/mpeg"),
135        _ => None,
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn detects_signatures() {
145        let detected = |data: &[u8]| SoundData::new(data.to_vec()).map(|sound| sound.content_type);
146        assert_eq!(detected(b"ID3\x04\0").unwrap(), "audio/mpeg");
147        assert_eq!(detected(b"\xff\xfb\x90\x64").unwrap(), "audio/mpeg");
148        assert_eq!(detected(b"OggS").unwrap(), "audio/ogg");
149        assert_eq!(detected(b"\xff\xd8\xff"), Err(SoundDataError));
150        assert_eq!(detected(b"RIFF"), Err(SoundDataError));
151        assert_eq!(detected(b""), Err(SoundDataError));
152    }
153
154    #[test]
155    fn serializes_and_hides_the_contents() {
156        let sound = SoundData::with_content_type(&b"abc"[..], "audio/mpeg");
157        assert_eq!(
158            serde_json::to_string(&sound).unwrap(),
159            r#""data:audio/mpeg;base64,YWJj""#
160        );
161        assert_eq!(
162            format!("{sound:?}"),
163            r#"SoundData { content_type: "audio/mpeg", len: 3 }"#
164        );
165    }
166}