Skip to main content

djs_model/rest/
user.rs

1//! Bodies, queries and responses of the [user endpoints](https://docs.discord.com/developers/resources/user).
2//!
3//! Update Current User Application Role Connection takes the model's
4//! [`ApplicationRoleConnection`](crate::user::ApplicationRoleConnection) as its body.
5
6use core::fmt;
7use std::collections::BTreeMap;
8
9use compact_str::CompactString;
10use serde::{Deserialize, Serialize};
11
12use crate::{
13    guild::Feature,
14    id::{GuildId, UserId},
15    permissions::Permissions,
16    util::{ImageData, ImageHash, Patch},
17};
18
19/// The body of [Modify Current User](https://docs.discord.com/developers/resources/user#modify-current-user).
20///
21/// discord.js counterpart: `ClientUser#edit`.
22#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
23#[non_exhaustive]
24pub struct ModifyCurrentUser {
25    /// The username.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub username: Option<CompactString>,
28    /// The avatar.
29    #[serde(skip_serializing_if = "Patch::is_keep")]
30    pub avatar: Patch<ImageData>,
31    /// The profile banner.
32    #[serde(skip_serializing_if = "Patch::is_keep")]
33    pub banner: Patch<ImageData>,
34}
35
36/// The query of [Get Current User Guilds](https://docs.discord.com/developers/resources/user#get-current-user-guilds).
37///
38/// discord.js counterpart: `RESTGetAPICurrentUserGuildsQuery` (discord-api-types).
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub struct GetCurrentUserGuilds {
42    /// Guilds with a lower ID.
43    pub before: Option<GuildId>,
44    /// Guilds with a higher ID.
45    pub after: Option<GuildId>,
46    /// The page size (1-200, the default).
47    pub limit: Option<u8>,
48    /// Only the guilds of this bucket (`0` to `max_concurrency - 1`); required for bots
49    /// with [large bot sharding](https://docs.discord.com/developers/events/gateway#sharding-for-large-bots).
50    pub shard: Option<u16>,
51    /// Whether to include the approximate member and presence counts.
52    pub with_counts: Option<bool>,
53}
54
55/// A guild of the current user, as returned by
56/// [Get Current User Guilds](https://docs.discord.com/developers/resources/user#get-current-user-guilds).
57///
58/// discord.js counterpart: `OAuth2Guild`.
59#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[non_exhaustive]
61pub struct CurrentUserGuild {
62    /// The guild's ID.
63    pub id: GuildId,
64    /// The guild's name.
65    pub name: CompactString,
66    /// The [icon hash](https://docs.discord.com/developers/reference#image-formatting).
67    pub icon: Option<ImageHash>,
68    /// The [banner hash](https://docs.discord.com/developers/reference#image-formatting).
69    #[serde(default)]
70    pub banner: Option<ImageHash>,
71    /// Whether the current user owns the guild.
72    pub owner: bool,
73    /// The current user's permissions in the guild.
74    pub permissions: Permissions,
75    /// The guild's features.
76    pub features: Vec<Feature>,
77    /// The approximate number of members (with `with_counts`).
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub approximate_member_count: Option<u32>,
80    /// The approximate number of online members (with `with_counts`).
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub approximate_presence_count: Option<u32>,
83}
84
85/// The body of [Create DM](https://docs.discord.com/developers/resources/user#create-dm).
86///
87/// discord.js counterpart: `RESTPostAPICurrentUserCreateDMChannelJSONBody` (discord-api-types).
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
89#[non_exhaustive]
90pub struct CreateDm {
91    /// The user to open a DM with.
92    pub recipient_id: UserId,
93}
94
95impl CreateDm {
96    /// Opens a DM with `recipient_id`.
97    ///
98    /// discord.js counterpart: `User#createDM`.
99    #[must_use]
100    pub const fn new(recipient_id: UserId) -> Self {
101        Self { recipient_id }
102    }
103}
104
105/// The body of [Create Group DM](https://docs.discord.com/developers/resources/user#create-group-dm).
106///
107/// The access tokens are redacted in the `Debug` output.
108///
109/// discord.js counterpart: none (discord-api-types has no type for Create Group DM's body).
110#[derive(Clone, Default, PartialEq, Eq, Hash, Serialize)]
111#[non_exhaustive]
112pub struct CreateGroupDm {
113    /// `OAuth2` access tokens of the users, who granted the `gdm.join` scope.
114    pub access_tokens: Vec<String>,
115    /// The users' nicknames in the group DM.
116    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
117    pub nicks: BTreeMap<UserId, CompactString>,
118}
119
120impl CreateGroupDm {
121    /// A group DM with the users whose access tokens are `access_tokens`.
122    ///
123    /// discord.js counterpart: none (discord-api-types has no type for Create Group DM's body).
124    #[must_use]
125    pub fn new(access_tokens: Vec<String>) -> Self {
126        Self {
127            access_tokens,
128            nicks: BTreeMap::new(),
129        }
130    }
131}
132
133impl fmt::Debug for CreateGroupDm {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("CreateGroupDm")
136            .field(
137                "access_tokens",
138                &format_args!("<{} redacted>", self.access_tokens.len()),
139            )
140            .field("nicks", &self.nicks)
141            .finish()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn bodies() {
151        let modify = ModifyCurrentUser {
152            username: Some("ferris".into()),
153            avatar: Patch::Clear,
154            ..ModifyCurrentUser::default()
155        };
156        assert_eq!(
157            serde_json::to_string(&modify).unwrap(),
158            r#"{"username":"ferris","avatar":null}"#
159        );
160
161        let mut group = CreateGroupDm::new(vec!["super-secret".into()]);
162        group.nicks.insert(UserId::new(7), "Ferris".into());
163        assert_eq!(
164            serde_json::to_string(&group).unwrap(),
165            r#"{"access_tokens":["super-secret"],"nicks":{"7":"Ferris"}}"#
166        );
167        let debug = format!("{group:?}");
168        assert!(!debug.contains("super-secret"), "{debug}");
169        assert!(debug.contains("<1 redacted>"), "{debug}");
170    }
171
172    #[test]
173    fn current_user_guild() {
174        let guild: CurrentUserGuild = serde_json::from_str(
175            r#"{
176                "id": "80351110224678912", "name": "1337 Krew",
177                "icon": "8342729096ea3675442027381ff50dfe",
178                "banner": "bb42bdc37653b7cf58c4c8cc622e76cb", "owner": true,
179                "permissions": "36953089", "features": ["COMMUNITY", "NEWS"],
180                "approximate_member_count": 3268, "approximate_presence_count": 784
181            }"#,
182        )
183        .unwrap();
184        assert!(guild.owner);
185        assert!(
186            guild
187                .permissions
188                .contains(Permissions::CREATE_INSTANT_INVITE)
189        );
190        assert_eq!(guild.approximate_member_count, Some(3268));
191    }
192}