Skip to main content

djs_model/message/
attachment.rs

1//! Files attached to messages.
2
3use compact_str::CompactString;
4use serde::{Deserialize, Serialize};
5
6use super::AttachmentFlags;
7use crate::{application::PartialApplication, id::AttachmentId, user::User, util::Timestamp};
8
9/// A [file attached to a message](https://docs.discord.com/developers/resources/message#attachment-object).
10///
11/// Contains a float ([`duration_secs`](Self::duration_secs)), so it is `PartialEq` but not
12/// `Eq` (D-064).
13///
14/// discord.js counterpart: `Attachment`.
15#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
16#[non_exhaustive]
17pub struct Attachment {
18    /// The attachment's ID.
19    pub id: AttachmentId,
20    /// The file name.
21    pub filename: CompactString,
22    /// The title of the file.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub title: Option<CompactString>,
25    /// The description (alt text, max 1024 characters).
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub description: Option<CompactString>,
28    /// The [media type](https://en.wikipedia.org/wiki/Media_type).
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub content_type: Option<CompactString>,
31    /// The size in bytes.
32    pub size: u64,
33    /// The source URL.
34    pub url: CompactString,
35    /// The URL through Discord's media proxy. It serves images, videos and audio; other files
36    /// get `415 Unsupported Media Type`.
37    pub proxy_url: CompactString,
38    /// The height of an image or video, in pixels.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub height: Option<u32>,
41    /// The width of an image or video, in pixels.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub width: Option<u32>,
44    /// A [thumbhash](https://evanw.github.io/thumbhash/) placeholder of an image or video.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub placeholder: Option<CompactString>,
47    /// The version of the placeholder.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub placeholder_version: Option<u32>,
50    /// Whether the attachment is ephemeral: it is removed after a while (but stays available as
51    /// long as its message exists).
52    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
53    pub ephemeral: bool,
54    /// The duration of an audio or video file, in seconds.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub duration_secs: Option<f64>,
57    /// A base64-encoded sampled waveform (voice messages).
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub waveform: Option<CompactString>,
60    /// The attachment's flags.
61    #[serde(default)]
62    pub flags: AttachmentFlags,
63    /// For clips: the users who were in the stream.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub clip_participants: Vec<User>,
66    /// For clips: when the clip was created.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub clip_created_at: Option<Timestamp>,
69    /// For clips: the application in the stream, if recognized.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub application: Option<Box<PartialApplication>>,
72}
73
74/// An [attachment in a create or edit request](https://docs.discord.com/developers/resources/message#attachment-object-attachment-request-structure):
75/// a new file uploaded with the request (`files[n]`), or an existing attachment to keep.
76///
77/// Sent in message create/edit requests, webhook messages and interaction responses.
78///
79/// discord.js counterpart: the `attachments` option of `MessageCreateOptions` / `AttachmentBuilder`.
80///
81/// # Examples
82///
83/// ```
84/// use djs_model::message::AttachmentRequest;
85///
86/// let mut file = AttachmentRequest::upload(0, "ferris.png");
87/// file.description = Some("Ferris the crab".into());
88/// assert_eq!(
89///     serde_json::to_string(&file).unwrap(),
90///     r#"{"id":0,"filename":"ferris.png","description":"Ferris the crab"}"#
91/// );
92/// ```
93#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
94#[non_exhaustive]
95pub struct AttachmentRequest {
96    /// The upload index or the existing attachment.
97    pub id: AttachmentRequestId,
98    /// The file name.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub filename: Option<CompactString>,
101    /// The file's title.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub title: Option<CompactString>,
104    /// The alt text (max 1024 characters).
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub description: Option<CompactString>,
107    /// The duration of an audio or video file in seconds (required for voice messages).
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub duration_secs: Option<f64>,
110    /// A base64-encoded sampled waveform (required for voice messages).
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub waveform: Option<CompactString>,
113    /// Whether the file is blurred until clicked (sets [`AttachmentFlags::IS_SPOILER`]).
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub is_spoiler: Option<bool>,
116}
117
118impl AttachmentRequest {
119    /// Describes the file uploaded as `files[index]` in the same request.
120    ///
121    /// discord.js counterpart: an `AttachmentPayload` of `files`.
122    #[must_use]
123    pub fn upload(index: u32, filename: impl Into<CompactString>) -> Self {
124        Self::with_id(AttachmentRequestId::Upload(index), Some(filename.into()))
125    }
126
127    /// Keeps an existing attachment (when editing a message).
128    ///
129    /// discord.js counterpart: an existing `Attachment` in `MessageEditOptions#attachments`.
130    #[must_use]
131    pub fn existing(id: AttachmentId) -> Self {
132        Self::with_id(AttachmentRequestId::Existing(id), None)
133    }
134
135    const fn with_id(id: AttachmentRequestId, filename: Option<CompactString>) -> Self {
136        Self {
137            id,
138            filename,
139            title: None,
140            description: None,
141            duration_secs: None,
142            waveform: None,
143            is_spoiler: None,
144        }
145    }
146}
147
148/// The `id` of an [`AttachmentRequest`]: the index `n` of a file uploaded as `files[n]`, or
149/// the ID of an existing attachment.
150///
151/// discord.js counterpart: the `id` of an attachment in `RESTPostAPIChannelMessageJSONBody` (discord-api-types).
152#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
153pub enum AttachmentRequestId {
154    /// A new file, uploaded as `files[n]` in the same multipart request (written as a number).
155    Upload(u32),
156    /// An existing attachment (written as a snowflake string).
157    Existing(AttachmentId),
158}
159
160impl Serialize for AttachmentRequestId {
161    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
162        match self {
163            Self::Upload(index) => serializer.serialize_u32(*index),
164            Self::Existing(id) => id.serialize(serializer),
165        }
166    }
167}
168
169impl<'de> Deserialize<'de> for AttachmentRequestId {
170    /// Numbers that fit in a `u32` are upload indices; strings and larger numbers are IDs.
171    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
172        struct AttachmentRequestIdVisitor;
173
174        impl serde::de::Visitor<'_> for AttachmentRequestIdVisitor {
175            type Value = AttachmentRequestId;
176
177            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
178                f.write_str("an upload index or a snowflake ID")
179            }
180
181            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Self::Value, E> {
182                if let Ok(index) = u32::try_from(value) {
183                    return Ok(AttachmentRequestId::Upload(index));
184                }
185                AttachmentId::new_checked(value)
186                    .map(AttachmentRequestId::Existing)
187                    .ok_or_else(|| E::invalid_value(serde::de::Unexpected::Unsigned(value), &self))
188            }
189
190            fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Self::Value, E> {
191                u64::try_from(value)
192                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(value), &self))
193                    .and_then(|value| self.visit_u64(value))
194            }
195
196            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
197                value
198                    .parse()
199                    .map(AttachmentRequestId::Existing)
200                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
201            }
202        }
203
204        deserializer.deserialize_any(AttachmentRequestIdVisitor)
205    }
206}