1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use crate::{
    gateway::opcode::OpCode,
    id::{GuildId, UserId},
};
use serde::{Deserialize, Serialize};
use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
};

/// Provided IDs is invalid for the request.
///
/// Returned by [`RequestGuildMembersBuilder::user_ids`].
#[derive(Debug)]
pub struct UserIdsError {
    kind: UserIdsErrorType,
}

impl UserIdsError {
    /// Immutable reference to the type of error that occurred.
    #[must_use = "retrieving the type has no effect if left unused"]
    pub const fn kind(&self) -> &UserIdsErrorType {
        &self.kind
    }

    /// Consume the error, returning the source error if there is any.
    #[allow(clippy::unused_self)]
    #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
    pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
        None
    }

    /// Consume the error, returning the owned error type and the source error.
    #[must_use = "consuming the error into its parts has no effect if left unused"]
    pub fn into_parts(self) -> (UserIdsErrorType, Option<Box<dyn Error + Send + Sync>>) {
        (self.kind, None)
    }

    fn too_many(ids: Vec<UserId>) -> Self {
        Self {
            kind: UserIdsErrorType::TooMany { ids },
        }
    }
}

impl Display for UserIdsError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match &self.kind {
            UserIdsErrorType::TooMany { ids } => {
                Display::fmt(&ids.len(), f)?;
                f.write_str(" user IDs were provided when only a maximum of 100 is allowed")
            }
        }
    }
}

impl Error for UserIdsError {}

/// Type of [`UserIdsError`] that occurred.
#[derive(Debug)]
#[non_exhaustive]
pub enum UserIdsErrorType {
    /// More than 100 user IDs were provided.
    TooMany {
        /// Provided list of user IDs.
        ids: Vec<UserId>,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RequestGuildMembers {
    pub d: RequestGuildMembersInfo,
    pub op: OpCode,
}

impl RequestGuildMembers {
    /// Create a new builder to configure a guild members request.
    ///
    /// This is an alias to [`RequestGuildMembersBuilder::new`]. Refer to its
    /// documentation for more information.
    pub const fn builder(guild_id: GuildId) -> RequestGuildMembersBuilder {
        RequestGuildMembersBuilder::new(guild_id)
    }
}

pub struct RequestGuildMembersBuilder {
    guild_id: GuildId,
    nonce: Option<String>,
    presences: Option<bool>,
}

impl RequestGuildMembersBuilder {
    /// Create a new builder to configure and construct a
    /// [`RequestGuildMembers`].
    pub const fn new(guild_id: GuildId) -> Self {
        Self {
            guild_id,
            nonce: None,
            presences: None,
        }
    }

    /// Set the nonce to identify the member chunk response.
    ///
    /// By default, this uses Discord's default.
    pub fn nonce(self, nonce: impl Into<String>) -> Self {
        self._nonce(nonce.into())
    }

    fn _nonce(mut self, nonce: String) -> Self {
        self.nonce.replace(nonce);

        self
    }

    /// Request that guild members' presences are included in member chunks.
    ///
    /// By default, this uses Discord's default.
    pub fn presences(mut self, presences: bool) -> Self {
        self.presences.replace(presences);

        self
    }

    /// Consume the builder, creating a request for users whose usernames start
    /// with the provided string and optionally limiting the number of members
    /// to retrieve.
    ///
    /// If you specify no limit, then Discord's default will be used, which will
    /// be an unbounded number of members. Specifying 0 is also equivalent.
    ///
    /// To request the entire member list, pass in a `None` query. You must also
    /// have the `GUILD_MEMBERS` intent enabled.
    ///
    /// # Examples
    ///
    /// Request all of the guild members that start with the letter "a" and
    /// their presences:
    ///
    /// ```
    /// use twilight_model::{gateway::payload::RequestGuildMembers, id::GuildId};
    ///
    /// let request = RequestGuildMembers::builder(GuildId(1))
    ///     .presences(true)
    ///     .query("a", None);
    ///
    /// assert_eq!(GuildId(1), request.d.guild_id);
    /// assert_eq!(Some(0), request.d.limit);
    /// assert_eq!(Some("a"), request.d.query.as_deref());
    /// assert_eq!(Some(true), request.d.presences);
    /// ```
    pub fn query(self, query: impl Into<String>, limit: Option<u64>) -> RequestGuildMembers {
        self._query(query.into(), limit)
    }

    fn _query(self, query: String, limit: Option<u64>) -> RequestGuildMembers {
        RequestGuildMembers {
            d: RequestGuildMembersInfo {
                guild_id: self.guild_id,
                limit: Some(limit.unwrap_or_default()),
                nonce: self.nonce,
                presences: self.presences,
                query: Some(query),
                user_ids: None,
            },
            op: OpCode::RequestGuildMembers,
        }
    }

    /// Consume the builder, creating a request that requests the provided
    /// member in the specified guild(s).
    ///
    /// # Examples
    ///
    /// Request a member within a guild and specify a nonce of "test":
    ///
    /// ```
    /// use twilight_model::{
    ///     gateway::payload::request_guild_members::{RequestGuildMemberId, RequestGuildMembers},
    ///     id::{GuildId, UserId},
    /// };
    ///
    /// let request = RequestGuildMembers::builder(GuildId(1))
    ///     .nonce("test")
    ///     .user_id(UserId(2));
    ///
    /// assert_eq!(Some(RequestGuildMemberId::One(UserId(2))), request.d.user_ids);
    /// ```
    #[allow(clippy::missing_const_for_fn)]
    pub fn user_id(self, user_id: UserId) -> RequestGuildMembers {
        RequestGuildMembers {
            d: RequestGuildMembersInfo {
                guild_id: self.guild_id,
                limit: None,
                nonce: self.nonce,
                presences: self.presences,
                query: None,
                user_ids: Some(RequestGuildMemberId::One(user_id)),
            },
            op: OpCode::RequestGuildMembers,
        }
    }

    /// Consume the builder, creating a request that requests the provided
    /// user(s) in the specified guild(s).
    ///
    /// Only up to 100 user IDs can be requested at once.
    ///
    /// # Examples
    ///
    /// Request two members within one guild and specify a nonce of "test":
    ///
    /// ```
    /// use twilight_model::{
    ///     gateway::payload::request_guild_members::{RequestGuildMemberId, RequestGuildMembers},
    ///     id::{GuildId, UserId},
    /// };
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let request = RequestGuildMembers::builder(GuildId(1))
    ///     .nonce("test")
    ///     .user_ids(vec![UserId(2), UserId(3)])?;
    ///
    /// assert!(matches!(request.d.user_ids, Some(RequestGuildMemberId::Multiple(ids)) if ids.len() == 2));
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a [`UserIdsErrorType::TooMany`] error type if more than 100 user
    /// IDs were provided.
    pub fn user_ids(
        self,
        user_ids: impl Into<Vec<UserId>>,
    ) -> Result<RequestGuildMembers, UserIdsError> {
        self._user_ids(user_ids.into())
    }

    fn _user_ids(self, user_ids: Vec<UserId>) -> Result<RequestGuildMembers, UserIdsError> {
        if user_ids.len() > 100 {
            return Err(UserIdsError::too_many(user_ids));
        }

        Ok(RequestGuildMembers {
            d: RequestGuildMembersInfo {
                guild_id: self.guild_id,
                limit: None,
                nonce: self.nonce,
                presences: self.presences,
                query: None,
                user_ids: Some(RequestGuildMemberId::Multiple(user_ids)),
            },
            op: OpCode::RequestGuildMembers,
        })
    }
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RequestGuildMembersInfo {
    /// Guild ID.
    pub guild_id: GuildId,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Maximum number of members to request.
    pub limit: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presences: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_ids: Option<RequestGuildMemberId<UserId>>,
}

/// One or a list of IDs in a request.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(untagged)]
pub enum RequestGuildMemberId<T> {
    /// Single ID specified.
    One(T),
    /// List of IDs specified.
    Multiple(Vec<T>),
}

impl<T> From<T> for RequestGuildMemberId<T> {
    fn from(id: T) -> Self {
        Self::One(id)
    }
}

impl<T> From<Vec<T>> for RequestGuildMemberId<T> {
    fn from(ids: Vec<T>) -> Self {
        Self::Multiple(ids)
    }
}