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
use std::collections::HashMap;

use serde_json::{json, Value};

use crate::internal::prelude::*;
use crate::model::channel::{PermissionOverwrite, PermissionOverwriteType, VideoQualityMode};
use crate::model::id::ChannelId;

/// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`]
///
/// Defaults are not directly provided by the builder itself.
///
/// # Examples
///
/// Edit a channel, providing a new name and topic:
///
/// ```rust,no_run
/// # use serenity::{http::Http, model::id::ChannelId};
/// #
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// #     let http = Http::default();
/// #     let mut channel = ChannelId(0);
/// // assuming a channel has already been bound
/// if let Err(why) = channel.edit(&http, |c| c.name("new name").topic("a test topic")).await {
///     // properly handle the error
/// }
/// #     Ok(())
/// # }
/// ```
///
/// [`GuildChannel`]: crate::model::channel::GuildChannel
/// [`GuildChannel::edit`]: crate::model::channel::GuildChannel::edit
#[derive(Clone, Debug, Default)]
pub struct EditChannel(pub HashMap<&'static str, Value>);

impl EditChannel {
    /// The bitrate of the channel in bits.
    ///
    /// This is for [voice] channels only.
    ///
    /// [voice]: crate::model::channel::ChannelType::Voice
    pub fn bitrate(&mut self, bitrate: u64) -> &mut Self {
        self.0.insert("bitrate", Value::Number(Number::from(bitrate)));
        self
    }

    /// The camera video quality mode of the channel.
    ///
    /// This is for [voice] channels only.
    ///
    /// [voice]: crate::model::channel::ChannelType::Voice
    pub fn video_quality_mode(&mut self, quality: VideoQualityMode) -> &mut Self {
        self.0.insert("video_quality_mode", Value::Number(Number::from(quality as u8)));
        self
    }

    /// The voice region of the channel.
    /// It is automatic when `None`.
    ///
    /// This is for [voice] channels only.
    ///
    /// [voice]: crate::model::channel::ChannelType::Voice
    pub fn voice_region(&mut self, id: Option<String>) -> &mut Self {
        self.0.insert("rtc_region", match id {
            Some(region) => Value::String(region),
            None => Value::Null,
        });
        self
    }

    /// The name of the channel.
    ///
    /// Must be between 2 and 100 characters long.
    pub fn name<S: ToString>(&mut self, name: S) -> &mut Self {
        self.0.insert("name", Value::String(name.to_string()));
        self
    }

    /// The position of the channel in the channel list.
    pub fn position(&mut self, position: u64) -> &mut Self {
        self.0.insert("position", Value::Number(Number::from(position)));
        self
    }

    /// The topic of the channel. Can be empty.
    ///
    /// Must be between 0 and 1024 characters long.
    ///
    /// This is for [text] channels only.
    ///
    /// [text]: crate::model::channel::ChannelType::Text
    pub fn topic<S: ToString>(&mut self, topic: S) -> &mut Self {
        self.0.insert("topic", Value::String(topic.to_string()));
        self
    }

    /// Is the channel inappropriate for work?
    ///
    /// This is for [text] channels only.
    ///
    /// [text]: crate::model::channel::ChannelType::Text
    pub fn nsfw(&mut self, nsfw: bool) -> &mut Self {
        self.0.insert("nsfw", Value::Bool(nsfw));

        self
    }

    /// The number of users that may be in the channel simultaneously.
    ///
    /// This is for [voice] channels only.
    ///
    /// [voice]: crate::model::channel::ChannelType::Voice
    pub fn user_limit(&mut self, user_limit: u64) -> &mut Self {
        self.0.insert("user_limit", Value::Number(Number::from(user_limit)));
        self
    }

    /// The parent category of the channel.
    ///
    /// This is for [text] and [voice] channels only.
    ///
    /// [text]: crate::model::channel::ChannelType::Text
    /// [voice]: crate::model::channel::ChannelType::Voice
    #[inline]
    pub fn category<C: Into<Option<ChannelId>>>(&mut self, category: C) -> &mut Self {
        self._category(category.into());
        self
    }

    fn _category(&mut self, category: Option<ChannelId>) {
        self.0.insert("parent_id", match category {
            Some(c) => Value::Number(Number::from(c.0)),
            None => Value::Null,
        });
    }

    /// The seconds a user has to wait before sending another message.
    ///
    /// **Note**: Must be between 0 and 21600 seconds (360 minutes or 6 hours).
    #[deprecated(note = "replaced by `rate_limit_per_user`")]
    #[inline]
    pub fn slow_mode_rate(&mut self, seconds: u64) -> &mut Self {
        self.rate_limit_per_user(seconds)
    }

    /// How many seconds must a user wait before sending another message.
    ///
    /// Bots, or users with the [`MANAGE_MESSAGES`] and/or [`MANAGE_CHANNELS`] permissions are exempt
    /// from this restriction.
    ///
    /// **Note**: Must be between 0 and 21600 seconds (360 minutes or 6 hours).
    ///
    /// [`MANAGE_MESSAGES`]: crate::model::permissions::Permissions::MANAGE_MESSAGES
    /// [`MANAGE_CHANNELS`]: crate::model::permissions::Permissions::MANAGE_CHANNELS
    #[doc(alias = "slowmode")]
    pub fn rate_limit_per_user(&mut self, seconds: u64) -> &mut Self {
        self.0.insert("rate_limit_per_user", Value::Number(Number::from(seconds)));

        self
    }

    /// A set of overwrites defining what a user or a user carrying a certain role can
    /// and cannot do.
    ///
    /// # Example
    ///
    /// Inheriting permissions from an exisiting channel:
    ///
    /// ```rust,no_run
    /// # use serenity::{http::Http, model::id::ChannelId};
    /// # use std::sync::Arc;
    /// #
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let http = Arc::new(Http::default());
    /// #     let mut channel = ChannelId(0);
    /// use serenity::model::channel::{PermissionOverwrite, PermissionOverwriteType};
    /// use serenity::model::id::UserId;
    /// use serenity::model::permissions::Permissions;
    ///
    /// // Assuming a channel has already been bound.
    /// let permissions = vec![PermissionOverwrite {
    ///     allow: Permissions::READ_MESSAGES,
    ///     deny: Permissions::SEND_TTS_MESSAGES,
    ///     kind: PermissionOverwriteType::Member(UserId(1234)),
    /// }];
    ///
    /// channel.edit(http, |c| c.name("my_edited_cool_channel").permissions(permissions)).await?;
    /// #    Ok(())
    /// # }
    /// ```
    pub fn permissions<I>(&mut self, perms: I) -> &mut Self
    where
        I: IntoIterator<Item = PermissionOverwrite>,
    {
        let overwrites = perms
            .into_iter()
            .map(|perm| {
                let (id, kind) = match perm.kind {
                    PermissionOverwriteType::Member(id) => (id.0, "member"),
                    PermissionOverwriteType::Role(id) => (id.0, "role"),
                };

                json!({
                    "allow": perm.allow.bits(),
                    "deny": perm.deny.bits(),
                    "id": id,
                    "type": kind,
                })
            })
            .collect();

        self.0.insert("permission_overwrites", Value::Array(overwrites));

        self
    }
}