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
296
use crate::{
    client::Client,
    error::Error,
    request::{self, AuditLogReason, Nullable, Request, TryIntoRequest},
    response::{Response, ResponseFuture},
    routing::Route,
};
use serde::Serialize;
use std::future::IntoFuture;
use twilight_model::{
    guild::Member,
    id::{
        marker::{ChannelMarker, GuildMarker, RoleMarker, UserMarker},
        Id,
    },
    util::Timestamp,
};
use twilight_validate::request::{
    audit_reason as validate_audit_reason,
    communication_disabled_until as validate_communication_disabled_until,
    nickname as validate_nickname, ValidationError,
};

#[derive(Serialize)]
struct UpdateGuildMemberFields<'a> {
    #[allow(clippy::option_option)]
    #[serde(skip_serializing_if = "Option::is_none")]
    channel_id: Option<Nullable<Id<ChannelMarker>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    communication_disabled_until: Option<Nullable<Timestamp>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    deaf: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    mute: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    nick: Option<Nullable<&'a str>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    roles: Option<&'a [Id<RoleMarker>]>,
}

/// Update a guild member.
///
/// All fields are optional. See [Discord Docs/Modify Guild Member].
///
/// [Discord Docs/Modify Guild Member]: https://discord.com/developers/docs/resources/guild#modify-guild-member
#[must_use = "requests must be configured and executed"]
pub struct UpdateGuildMember<'a> {
    fields: UpdateGuildMemberFields<'a>,
    guild_id: Id<GuildMarker>,
    http: &'a Client,
    user_id: Id<UserMarker>,
    reason: Option<&'a str>,
}

impl<'a> UpdateGuildMember<'a> {
    pub(crate) const fn new(
        http: &'a Client,
        guild_id: Id<GuildMarker>,
        user_id: Id<UserMarker>,
    ) -> Self {
        Self {
            fields: UpdateGuildMemberFields {
                channel_id: None,
                communication_disabled_until: None,
                deaf: None,
                mute: None,
                nick: None,
                roles: None,
            },
            guild_id,
            http,
            user_id,
            reason: None,
        }
    }

    /// Move the member to a different voice channel.
    pub const fn channel_id(mut self, channel_id: Option<Id<ChannelMarker>>) -> Self {
        self.fields.channel_id = Some(Nullable(channel_id));

        self
    }

    /// Set the member's [Guild Timeout].
    ///
    /// The timestamp indicates when the user will be able to communicate again.
    /// It can be up to 28 days in the future. Set to [`None`] to remove the
    /// timeout. Requires the [`MODERATE_MEMBERS`] permission. If this is set,
    /// and if the target member is an administrator or the owner of the guild,
    /// the response status code will be 403.
    ///
    /// # Errors
    ///
    /// Returns an error of type [`CommunicationDisabledUntil`] if the expiry
    /// timestamp is more than 28 days from the current time.
    ///
    /// [Guild Timeout]: https://support.discord.com/hc/en-us/articles/4413305239191-Time-Out-FAQ
    /// [`CommunicationDisabledUntil`]: twilight_validate::request::ValidationErrorType::CommunicationDisabledUntil
    /// [`MODERATE_MEMBERS`]: twilight_model::guild::Permissions::MODERATE_MEMBERS
    pub fn communication_disabled_until(
        mut self,
        timestamp: Option<Timestamp>,
    ) -> Result<Self, ValidationError> {
        if let Some(timestamp) = timestamp {
            validate_communication_disabled_until(timestamp)?;
        }

        self.fields.communication_disabled_until = Some(Nullable(timestamp));

        Ok(self)
    }

    /// If true, restrict the member's ability to hear sound from a voice channel.
    pub const fn deaf(mut self, deaf: bool) -> Self {
        self.fields.deaf = Some(deaf);

        self
    }

    /// If true, restrict the member's ability to speak in a voice channel.
    pub const fn mute(mut self, mute: bool) -> Self {
        self.fields.mute = Some(mute);

        self
    }

    /// Set the nickname.
    ///
    /// The minimum length is 1 UTF-16 character and the maximum is 32 UTF-16 characters.
    ///
    /// # Errors
    ///
    /// Returns an error of type [`Nickname`] if the nickname length is too
    /// short or too long.
    ///
    /// [`Nickname`]: twilight_validate::request::ValidationErrorType::Nickname
    pub fn nick(mut self, nick: Option<&'a str>) -> Result<Self, ValidationError> {
        if let Some(nick) = nick {
            validate_nickname(nick)?;
        }

        self.fields.nick = Some(Nullable(nick));

        Ok(self)
    }

    /// Set the new list of roles for a member.
    pub const fn roles(mut self, roles: &'a [Id<RoleMarker>]) -> Self {
        self.fields.roles = Some(roles);

        self
    }

    /// Execute the request, returning a future resolving to a [`Response`].
    #[deprecated(since = "0.14.0", note = "use `.await` or `into_future` instead")]
    pub fn exec(self) -> ResponseFuture<Member> {
        self.into_future()
    }
}

impl<'a> AuditLogReason<'a> for UpdateGuildMember<'a> {
    fn reason(mut self, reason: &'a str) -> Result<Self, ValidationError> {
        validate_audit_reason(reason)?;

        self.reason.replace(reason);

        Ok(self)
    }
}

impl IntoFuture for UpdateGuildMember<'_> {
    type Output = Result<Response<Member>, Error>;

    type IntoFuture = ResponseFuture<Member>;

    fn into_future(self) -> Self::IntoFuture {
        let http = self.http;

        match self.try_into_request() {
            Ok(request) => http.request(request),
            Err(source) => ResponseFuture::error(source),
        }
    }
}

impl TryIntoRequest for UpdateGuildMember<'_> {
    fn try_into_request(self) -> Result<Request, Error> {
        let mut request = Request::builder(&Route::UpdateMember {
            guild_id: self.guild_id.get(),
            user_id: self.user_id.get(),
        })
        .json(&self.fields)?;

        if let Some(reason) = &self.reason {
            request = request.headers(request::audit_header(reason)?);
        }

        Ok(request.build())
    }
}

#[cfg(test)]
mod tests {
    use super::{UpdateGuildMember, UpdateGuildMemberFields};
    use crate::{
        request::{Nullable, Request, TryIntoRequest},
        routing::Route,
        Client,
    };
    use std::error::Error;
    use twilight_model::id::{
        marker::{GuildMarker, UserMarker},
        Id,
    };

    const GUILD_ID: Id<GuildMarker> = Id::new(1);
    const USER_ID: Id<UserMarker> = Id::new(1);

    #[test]
    fn request() -> Result<(), Box<dyn Error>> {
        let client = Client::new("foo".to_owned());
        let builder = UpdateGuildMember::new(&client, GUILD_ID, USER_ID)
            .deaf(true)
            .mute(true);
        let actual = builder.try_into_request()?;

        let body = UpdateGuildMemberFields {
            channel_id: None,
            communication_disabled_until: None,
            deaf: Some(true),
            mute: Some(true),
            nick: None,
            roles: None,
        };
        let route = Route::UpdateMember {
            guild_id: GUILD_ID.get(),
            user_id: USER_ID.get(),
        };
        let expected = Request::builder(&route).json(&body)?.build();

        assert_eq!(actual.body, expected.body);
        assert_eq!(actual.path, expected.path);

        Ok(())
    }

    #[test]
    fn nick_set_null() -> Result<(), Box<dyn Error>> {
        let client = Client::new("foo".to_owned());
        let builder = UpdateGuildMember::new(&client, GUILD_ID, USER_ID).nick(None)?;
        let actual = builder.try_into_request()?;

        let body = UpdateGuildMemberFields {
            channel_id: None,
            communication_disabled_until: None,
            deaf: None,
            mute: None,
            nick: Some(Nullable(None)),
            roles: None,
        };
        let route = Route::UpdateMember {
            guild_id: GUILD_ID.get(),
            user_id: USER_ID.get(),
        };
        let expected = Request::builder(&route).json(&body)?.build();

        assert_eq!(actual.body, expected.body);

        Ok(())
    }

    #[test]
    fn nick_set_value() -> Result<(), Box<dyn Error>> {
        let client = Client::new("foo".to_owned());
        let builder = UpdateGuildMember::new(&client, GUILD_ID, USER_ID).nick(Some("foo"))?;
        let actual = builder.try_into_request()?;

        let body = UpdateGuildMemberFields {
            channel_id: None,
            communication_disabled_until: None,
            deaf: None,
            mute: None,
            nick: Some(Nullable(Some("foo"))),
            roles: None,
        };
        let route = Route::UpdateMember {
            guild_id: GUILD_ID.get(),
            user_id: USER_ID.get(),
        };
        let expected = Request::builder(&route).json(&body)?.build();

        assert_eq!(actual.body, expected.body);

        Ok(())
    }
}