Skip to main content

djs_model/rest/
mod.rs

1//! Request bodies and response types of the [REST API](https://docs.discord.com/developers/reference#http-api).
2//!
3//! These are plain data types; sending requests is the job of the `djs-rest` crate.
4//!
5//! discord.js counterpart: the `RESTPost…JSONBody` / `RESTGet…Result` types of
6//! discord-api-types.
7
8use core::fmt::{self, Write as _};
9
10use bytes::Bytes;
11use compact_str::CompactString;
12use serde::{Deserialize, Serialize, Serializer, ser::SerializeSeq};
13
14use crate::{
15    id::UserId,
16    message::{AttachmentRequest, AttachmentRequestId},
17};
18
19mod application;
20mod application_command;
21mod application_identity_profile;
22mod audit_log;
23mod auto_moderation;
24mod channel;
25mod emoji;
26mod entitlement;
27mod error_code;
28mod guild;
29mod guild_scheduled_event;
30mod guild_template;
31mod interaction;
32mod invite;
33mod lobby;
34mod message;
35mod poll;
36mod soundboard;
37mod stage_instance;
38mod sticker;
39mod subscription;
40mod user;
41mod voice;
42mod webhook;
43
44pub(crate) mod setters;
45
46pub use self::{
47    application::EditCurrentApplication,
48    application_command::{
49        CreateApplicationCommand, EditApplicationCommand, EditApplicationCommandPermissions,
50        GetApplicationCommands,
51    },
52    application_identity_profile::{
53        DeleteApplicationIdentity, GetApplicationIdentitiesByExternalId,
54        UpdateApplicationIdentityProfile,
55    },
56    audit_log::GetGuildAuditLog,
57    auto_moderation::{CreateAutoModerationRule, ModifyAutoModerationRule},
58    channel::{
59        ArchivedThreads, CreateChannelInvite, EditChannelPermissions, FollowAnnouncementChannel,
60        ForumTagData, ForumThread, ForumThreadMessage, GetChannelPermissions, GetThreadMember,
61        GroupDmAddRecipient, ListArchivedThreads, ListJoinedPrivateArchivedThreads,
62        ListThreadMembers, ModifyGroupDm, ModifyGuildChannel, ModifyThread, SetVoiceChannelStatus,
63        StartThreadFromMessage, StartThreadInForumOrMediaChannel, StartThreadWithoutMessage,
64    },
65    emoji::{CreateApplicationEmoji, CreateGuildEmoji, ModifyApplicationEmoji, ModifyGuildEmoji},
66    entitlement::{CreateTestEntitlement, ListEntitlements},
67    error_code::ErrorCode,
68    guild::{
69        ActiveThreads, AddGuildMember, BeginGuildPrune, BulkBanResponse, BulkGuildBan,
70        CreateGuildBan, CreateGuildChannel, CreateGuildRole, GetGuild, GetGuildBans,
71        GetGuildPruneCount, ListGuildMembers, ModifyCurrentMember, ModifyGuild,
72        ModifyGuildChannelPosition, ModifyGuildIncidentActions, ModifyGuildMember,
73        ModifyGuildOnboarding, ModifyGuildRole, ModifyGuildRolePosition, ModifyGuildWelcomeScreen,
74        ModifyGuildWidget, OnboardingPromptData, PromptOptionData, SearchGuildMembers, VanityUrl,
75    },
76    guild_scheduled_event::{
77        CreateGuildScheduledEvent, GetGuildScheduledEvent, GetGuildScheduledEventUsers,
78        ListScheduledEventsForGuild, ModifyGuildScheduledEvent, RecurrenceRuleData,
79    },
80    guild_template::{CreateGuildTemplate, ModifyGuildTemplate},
81    interaction::CreateFollowupMessage,
82    invite::{BulkTargetUsers, GetInvite},
83    lobby::{
84        AddLobbyMember, BulkLobbyMember, CreateLobby, CreateOrJoinLobby, GetLobbyMessages,
85        LobbyMemberData, LobbyMetadata, ModifyLobby, SendLobbyMessage,
86    },
87    message::{
88        BulkDeleteMessages, ChannelPins, CreateMessage, EditMessage, GetChannelMessages,
89        GetChannelPins, GetReactions, MessageSearchResults, SearchAuthorType, SearchEmbedType,
90        SearchFilter, SearchGuildMessages, SearchHasType, SearchSortMode, SearchSortOrder,
91    },
92    poll::GetAnswerVoters,
93    soundboard::{CreateGuildSoundboardSound, ModifyGuildSoundboardSound, SendSoundboardSound},
94    stage_instance::{CreateStageInstance, ModifyStageInstance},
95    sticker::{CreateGuildSticker, ModifyGuildSticker},
96    subscription::ListSkuSubscriptions,
97    user::{CreateDm, CreateGroupDm, CurrentUserGuild, GetCurrentUserGuilds, ModifyCurrentUser},
98    voice::{ModifyCurrentUserVoiceState, ModifyUserVoiceState},
99    webhook::{CreateWebhook, EditWebhookMessage, ExecuteWebhook, ModifyWebhook},
100};
101
102/// The response of [Get Gateway](https://docs.discord.com/developers/events/gateway#get-gateway)
103/// (`GET /gateway`, D-136): where to connect to the gateway. Bots use [`GatewayBot`], which also
104/// tells the shard count and session start limit.
105///
106/// discord.js counterpart: none (discord-api-types: `RESTGetAPIGatewayResult`).
107#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
108#[non_exhaustive]
109pub struct Gateway {
110    /// The WSS URL to connect to, e.g. `wss://gateway.discord.gg`.
111    pub url: CompactString,
112}
113
114/// The response of [Get Gateway Bot](https://docs.discord.com/developers/events/gateway#get-gateway-bot)
115/// (`GET /gateway/bot`): where and how to connect to the gateway.
116///
117/// discord.js counterpart: `APIGatewayBotInfo` (discord-api-types).
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[non_exhaustive]
120pub struct GatewayBot {
121    /// The WSS URL to connect to, e.g. `wss://gateway.discord.gg`.
122    pub url: CompactString,
123    /// The recommended number of shards.
124    pub shards: u32,
125    /// Information on the current session start limit.
126    pub session_start_limit: SessionStartLimit,
127}
128
129/// How many gateway sessions the bot may still start
130/// ([session start limit object](https://docs.discord.com/developers/events/gateway#session-start-limit-object)).
131///
132/// discord.js counterpart: `APIGatewaySessionStartLimit` (discord-api-types).
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
134#[non_exhaustive]
135pub struct SessionStartLimit {
136    /// The total number of session starts allowed per reset period (usually 1000 per day).
137    pub total: u32,
138    /// The remaining number of session starts.
139    pub remaining: u32,
140    /// Milliseconds until the limit resets.
141    pub reset_after: u64,
142    /// How many identify requests are allowed per 5 seconds (per rate-limit key).
143    pub max_concurrency: u32,
144}
145
146/// A file uploaded with a request, e.g. a message attachment.
147///
148/// Request bodies that accept files have a `files` field (D-087). `djs-rest` then sends the
149/// request as `multipart/form-data`: the file at index `n` becomes the part `files[n]`, the
150/// JSON body the part `payload_json`, and the body's `attachments` gets an entry for each file
151/// with its name and metadata (D-094). Embeds can show an uploaded image with the URL
152/// `attachment://{name}`.
153///
154/// The data is [`Bytes`] (D-093): cloning a `FileUpload` (to send the same file to many
155/// channels, or for a retry) does not copy the file, and neither do `Bytes::from_static`
156/// (e.g. with `include_bytes!`) and `Bytes::from(Vec<u8>)`.
157///
158/// When [`content_type`](Self::content_type) is not set, it is guessed from the extension of
159/// [`name`](Self::name) (D-095).
160///
161/// See [Uploading Files](https://docs.discord.com/developers/reference#uploading-files).
162///
163/// discord.js counterpart: `AttachmentBuilder` / `RawFile` of `@discordjs/rest`.
164///
165/// # Examples
166///
167/// ```
168/// use djs_model::rest::FileUpload;
169///
170/// let mut image = FileUpload::new("ferris.png", &b"\x89PNG\r\n\x1a\n..."[..]);
171/// image.description = Some("Ferris the crab".into());
172/// image.is_spoiler = true;
173///
174/// // Cloning shares the data.
175/// let copy = image.clone();
176/// assert_eq!(copy.data.as_ptr(), image.data.as_ptr());
177/// ```
178#[derive(Clone, PartialEq)]
179#[non_exhaustive]
180pub struct FileUpload {
181    /// The file name, including its extension (e.g. `ferris.png`).
182    pub name: CompactString,
183    /// The file's contents.
184    pub data: Bytes,
185    /// The [media type](https://en.wikipedia.org/wiki/Media_type) (e.g. `image/png`); guessed
186    /// from the file name when `None`.
187    pub content_type: Option<CompactString>,
188    /// The alt text (max 1024 characters).
189    pub description: Option<CompactString>,
190    /// The file's title.
191    pub title: Option<CompactString>,
192    /// The duration of an audio or video file in seconds (required for voice messages).
193    pub duration_secs: Option<f64>,
194    /// A base64-encoded sampled waveform (required for voice messages).
195    pub waveform: Option<CompactString>,
196    /// Whether the file is blurred until clicked (sets
197    /// [`AttachmentFlags::IS_SPOILER`](crate::message::AttachmentFlags::IS_SPOILER)).
198    pub is_spoiler: bool,
199}
200
201impl FileUpload {
202    /// Creates an upload of `data` named `name`, without metadata.
203    ///
204    /// `data` can be anything that converts into [`Bytes`] without copying: a `Vec<u8>`, a
205    /// `String`, a `&'static [u8]` or a `&'static str`.
206    ///
207    /// discord.js counterpart: `AttachmentBuilder`.
208    #[must_use]
209    pub fn new(name: impl Into<CompactString>, data: impl Into<Bytes>) -> Self {
210        Self {
211            name: name.into(),
212            data: data.into(),
213            content_type: None,
214            description: None,
215            title: None,
216            duration_secs: None,
217            waveform: None,
218            is_spoiler: false,
219        }
220    }
221
222    /// A CSV file named `users.csv` listing `user_ids`, one per line (D-127): the
223    /// `target_users_file` of Update Target Users and Create Channel Invite.
224    ///
225    /// discord.js counterpart: the `targetUsersFile` of `RESTPutAPIInviteTargetUsersFormDataBody` (discord-api-types).
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use djs_model::{id::UserId, rest::FileUpload};
231    ///
232    /// let file = FileUpload::target_users([UserId::new(7), UserId::new(8)]);
233    /// assert_eq!(file.name, "users.csv");
234    /// assert_eq!(&file.data[..], b"7\n8");
235    /// assert_eq!(file.content_type.as_deref(), Some("text/csv"));
236    /// ```
237    #[must_use]
238    pub fn target_users(user_ids: impl IntoIterator<Item = UserId>) -> Self {
239        let mut csv = String::new();
240        for (index, id) in user_ids.into_iter().enumerate() {
241            if index > 0 {
242                csv.push('\n');
243            }
244            // Writing to a `String` cannot fail.
245            let _ = write!(csv, "{id}");
246        }
247        Self {
248            content_type: Some(CompactString::const_new("text/csv")),
249            ..Self::new("users.csv", csv)
250        }
251    }
252}
253
254impl fmt::Debug for FileUpload {
255    /// Shows the size of the data instead of the data.
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        f.debug_struct("FileUpload")
258            .field("name", &self.name)
259            .field("data", &format_args!("<{} bytes>", self.data.len()))
260            .field("content_type", &self.content_type)
261            .field("description", &self.description)
262            .field("title", &self.title)
263            .field("duration_secs", &self.duration_secs)
264            .field("waveform", &self.waveform)
265            .field("is_spoiler", &self.is_spoiler)
266            .finish()
267    }
268}
269
270/// The serialized `attachments` of a body with files (D-094): the explicit entries, then an
271/// entry for every file whose `files[n]` index has no explicit entry.
272#[derive(Clone, Copy)]
273pub(crate) struct Attachments<'a> {
274    explicit: Option<&'a [AttachmentRequest]>,
275    files: &'a [FileUpload],
276}
277
278impl<'a> Attachments<'a> {
279    pub(crate) const fn new(
280        explicit: Option<&'a [AttachmentRequest]>,
281        files: &'a [FileUpload],
282    ) -> Self {
283        Self { explicit, files }
284    }
285
286    /// Whether the field is left out: nothing explicit and no files. `Some(vec![])` is kept,
287    /// because when editing it removes every attachment.
288    pub(crate) const fn is_absent(&self) -> bool {
289        self.explicit.is_none() && self.files.is_empty()
290    }
291
292    /// The attachments of a modify body: [`Patch::Keep`](crate::util::Patch::Keep) sends
293    /// nothing (unless there are files), [`Clear`](crate::util::Patch::Clear) an empty list
294    /// (plus the files), [`Set`](crate::util::Patch::Set) the given ones (plus the files).
295    pub(crate) fn from_patch(
296        attachments: &'a crate::util::Patch<Vec<AttachmentRequest>>,
297        files: &'a [FileUpload],
298    ) -> Self {
299        use crate::util::Patch;
300
301        let explicit = match attachments {
302            Patch::Keep => None,
303            Patch::Clear => Some(&[][..]),
304            Patch::Set(attachments) => Some(attachments.as_slice()),
305        };
306        Self::new(explicit, files)
307    }
308
309    /// The files that get a generated entry, with their `files[n]` index.
310    fn generated(self) -> impl Iterator<Item = (u32, &'a FileUpload)> {
311        let explicit = self.explicit.unwrap_or_default();
312        self.files
313            .iter()
314            .enumerate()
315            .map(|(index, file)| (u32::try_from(index).unwrap_or(u32::MAX), file))
316            .filter(move |(index, _)| {
317                !explicit
318                    .iter()
319                    .any(|entry| entry.id == AttachmentRequestId::Upload(*index))
320            })
321    }
322}
323
324impl Serialize for Attachments<'_> {
325    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
326        /// The entry of a file, borrowing its metadata.
327        #[derive(Serialize)]
328        struct Generated<'a> {
329            id: u32,
330            filename: &'a str,
331            #[serde(skip_serializing_if = "Option::is_none")]
332            title: Option<&'a str>,
333            #[serde(skip_serializing_if = "Option::is_none")]
334            description: Option<&'a str>,
335            #[serde(skip_serializing_if = "Option::is_none")]
336            duration_secs: Option<f64>,
337            #[serde(skip_serializing_if = "Option::is_none")]
338            waveform: Option<&'a str>,
339            #[serde(skip_serializing_if = "core::ops::Not::not")]
340            is_spoiler: bool,
341        }
342
343        let explicit = self.explicit.unwrap_or_default();
344        let mut seq = serializer.serialize_seq(Some(explicit.len() + self.generated().count()))?;
345        for entry in explicit {
346            seq.serialize_element(entry)?;
347        }
348        for (id, file) in self.generated() {
349            seq.serialize_element(&Generated {
350                id,
351                filename: &file.name,
352                title: file.title.as_deref(),
353                description: file.description.as_deref(),
354                duration_secs: file.duration_secs,
355                waveform: file.waveform.as_deref(),
356                is_spoiler: file.is_spoiler,
357            })?;
358        }
359        seq.end()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn gateway_bot_documented_example() {
369        let json = r#"{
370            "url": "wss://gateway.discord.gg/",
371            "shards": 9,
372            "session_start_limit": {
373                "total": 1000,
374                "remaining": 999,
375                "reset_after": 14400000,
376                "max_concurrency": 1
377            }
378        }"#;
379        let info: GatewayBot = serde_json::from_str(json).unwrap();
380        assert_eq!(info.url, "wss://gateway.discord.gg/");
381        assert_eq!(info.shards, 9);
382        assert_eq!(info.session_start_limit.max_concurrency, 1);
383    }
384
385    fn json(body: &CreateMessage) -> String {
386        serde_json::to_string(body).unwrap()
387    }
388
389    #[test]
390    fn files_get_attachment_entries() {
391        let mut body = CreateMessage::default();
392        assert_eq!(json(&body), "{}");
393
394        let mut voice = FileUpload::new("voice.ogg", Vec::from(*b"OggS"));
395        voice.duration_secs = Some(2.5);
396        voice.waveform = Some("AAAA".into());
397        let mut image = FileUpload::new("ferris.png", &b"png"[..]);
398        image.title = Some("Ferris".into());
399        image.description = Some("Ferris the crab".into());
400        image.is_spoiler = true;
401        body.files = vec![voice, image];
402        assert_eq!(
403            json(&body),
404            r#"{"attachments":[{"id":0,"filename":"voice.ogg","duration_secs":2.5,"waveform":"AAAA"},{"id":1,"filename":"ferris.png","title":"Ferris","description":"Ferris the crab","is_spoiler":true}]}"#
405        );
406
407        // An explicit entry for an index replaces the generated one; others are kept first.
408        let mut renamed = AttachmentRequest::upload(1, "crab.png");
409        renamed.description = Some("A crab".into());
410        let keep =
411            AttachmentRequest::existing(crate::id::AttachmentId::new(1_300_000_000_000_000_000));
412        body.attachments = Some(vec![keep, renamed]);
413        assert_eq!(
414            json(&body),
415            r#"{"attachments":[{"id":"1300000000000000000"},{"id":1,"filename":"crab.png","description":"A crab"},{"id":0,"filename":"voice.ogg","duration_secs":2.5,"waveform":"AAAA"}]}"#
416        );
417
418        // Without files, an explicit empty list is sent (it removes attachments on edits).
419        body.files.clear();
420        body.attachments = Some(Vec::new());
421        assert_eq!(json(&body), r#"{"attachments":[]}"#);
422    }
423
424    #[test]
425    fn file_upload_debug_hides_the_data() {
426        let file = FileUpload::new("secret.txt", "not shown");
427        let debug = format!("{file:?}");
428        assert!(
429            debug.contains("<9 bytes>") && !debug.contains("not shown"),
430            "{debug}"
431        );
432    }
433}