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
use super::CreateMessage;
use twilight_model::id::{RoleId, UserId};

/// Whether or not the section will be parsed.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Parsed;

/// A vec of explicit users to be parsed.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ExplicitUser(Vec<UserId>);

/// A vec of explicit roles to be parsed.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ExplicitRole(Vec<RoleId>);

/// Not currently specified.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Unspecified;

/// Parse types.
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ParseTypes {
    Users,
    Roles,
    Everyone,
}

/// Stores the allowed mentions.
#[derive(serde::Deserialize, serde::Serialize, Clone, Default, Debug, Eq, Hash, PartialEq)]
#[must_use = "It will not be added unless `build()` is called."]
pub struct AllowedMentions {
    parse: Vec<ParseTypes>,
    users: Option<Vec<UserId>>,
    roles: Option<Vec<RoleId>>,
}

pub trait VisitAllowedMentionsEveryone: Sized {
    fn visit(self, _: &mut AllowedMentions) {}
}

pub trait VisitAllowedMentionsUsers: Sized {
    fn visit(self, _: &mut AllowedMentions) {}
}

pub trait VisitAllowedMentionsRoles: Sized {
    fn visit(self, _: &mut AllowedMentions) {}
}

impl VisitAllowedMentionsEveryone for Unspecified {}
impl VisitAllowedMentionsUsers for Unspecified {}
impl VisitAllowedMentionsRoles for Unspecified {}

impl VisitAllowedMentionsEveryone for Parsed {
    fn visit(self, d: &mut AllowedMentions) {
        d.parse.push(ParseTypes::Everyone);
    }
}

impl VisitAllowedMentionsUsers for Parsed {
    fn visit(self, d: &mut AllowedMentions) {
        d.parse.push(ParseTypes::Users);
    }
}

impl VisitAllowedMentionsRoles for Parsed {
    fn visit(self, d: &mut AllowedMentions) {
        d.parse.push(ParseTypes::Roles);
    }
}

impl VisitAllowedMentionsUsers for ExplicitUser {
    fn visit(self, d: &mut AllowedMentions) {
        d.users = Some(self.0)
    }
}

impl VisitAllowedMentionsRoles for ExplicitRole {
    fn visit(self, d: &mut AllowedMentions) {
        d.roles = Some(self.0)
    }
}

/// A builder for allowed mentions.
///
/// # Example
///
/// ```rust,no_run
/// use twilight_http::request::channel::message::allowed_mentions::AllowedMentionsBuilder;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// let mut allowed_mentions = AllowedMentionsBuilder::new()
///     .parse_everyone()
///     .parse_users()
///     .build_solo();
/// # Ok(()) }
/// ```
pub struct AllowedMentionsBuilder<'a, E, U, R> {
    create_message: Option<CreateMessage<'a>>,
    e: E,
    u: U,
    r: R,
}

impl<'a> AllowedMentionsBuilder<'a, Unspecified, Unspecified, Unspecified> {
    pub(crate) fn for_builder(create_message: CreateMessage<'a>) -> Self {
        Self {
            create_message: Some(create_message),
            e: Unspecified,
            u: Unspecified,
            r: Unspecified,
        }
    }

    /// Create the builder.
    pub fn new() -> Self {
        Self {
            create_message: None,
            e: Unspecified,
            u: Unspecified,
            r: Unspecified,
        }
    }
}

impl<'a> Default for AllowedMentionsBuilder<'a, Unspecified, Unspecified, Unspecified> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, U, R> AllowedMentionsBuilder<'a, Unspecified, U, R> {
    /// Enable parsing for the `@everyone` and `@here` tags.
    pub fn parse_everyone(self) -> AllowedMentionsBuilder<'a, Parsed, U, R> {
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: Parsed,
            u: self.u,
            r: self.r,
        }
    }
}

impl<'a, E, R> AllowedMentionsBuilder<'a, E, Unspecified, R> {
    /// Enable parsing for all user tags.
    pub fn parse_users(self) -> AllowedMentionsBuilder<'a, E, Parsed, R> {
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: Parsed,
            r: self.r,
        }
    }

    /// Enable parsing for specific user tags.
    pub fn parse_specific_users(
        self,
        u: impl IntoIterator<Item = UserId>,
    ) -> AllowedMentionsBuilder<'a, E, ExplicitUser, R> {
        let vec = u.into_iter().collect::<Vec<_>>();
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: ExplicitUser(vec),
            r: self.r,
        }
    }
}

impl<'a, E, U> AllowedMentionsBuilder<'a, E, U, Unspecified> {
    /// Enable parsing for all role tags.
    pub fn parse_roles(self) -> AllowedMentionsBuilder<'a, E, U, Parsed> {
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: self.u,
            r: Parsed,
        }
    }

    /// Enable parsing for specific role tags.
    pub fn parse_specific_roles(
        self,
        r: impl IntoIterator<Item = RoleId>,
    ) -> AllowedMentionsBuilder<'a, E, U, ExplicitRole> {
        let vec = r.into_iter().collect::<Vec<_>>();
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: self.u,
            r: ExplicitRole(vec),
        }
    }
}

impl<'a, E, U> AllowedMentionsBuilder<'a, E, U, ExplicitRole> {
    /// Enable parsing for more specific role tags.
    ///
    /// If there are already some specific `RoleId`s in this builder, extend them with the content
    /// of `r`.
    pub fn parse_specific_roles(mut self, r: impl IntoIterator<Item = RoleId>) -> Self {
        self.r.0.extend(r);
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: self.u,
            r: self.r,
        }
    }
}

impl<'a, E, R> AllowedMentionsBuilder<'a, E, ExplicitUser, R> {
    /// Enable parsing for more specific user tags.
    ///
    /// If there are already some specific `UserId`s in this builder, extend them with the content
    /// of `u`.
    pub fn parse_specific_users(mut self, u: impl IntoIterator<Item = UserId>) -> Self {
        self.u.0.extend(u);
        AllowedMentionsBuilder {
            create_message: self.create_message,
            e: self.e,
            u: self.u,
            r: self.r,
        }
    }
}

impl<
        'a,
        E: VisitAllowedMentionsEveryone,
        U: VisitAllowedMentionsUsers,
        R: VisitAllowedMentionsRoles,
    > AllowedMentionsBuilder<'a, E, U, R>
{
    /// Return a [`CreateMessage`] struct with the specified `allowed_mentions`.
    ///
    /// [`CreateMessage`]: ../create_message/struct.CreateMessage.html
    pub fn build(self) -> CreateMessage<'a> {
        match self.create_message {
            Some(mut builder) => {
                let mut m = AllowedMentions::default();
                self.e.visit(&mut m);
                self.u.visit(&mut m);
                self.r.visit(&mut m);
                builder.fields.allowed_mentions.replace(m);
                builder
            }
            None => panic!(
                "Tried to build to a messagebuilder but none was provided during construction"
            ),
        }
    }

    /// Build a raw [`AllowedMentions`] for use in [`ClientBuilder#default_allowed_mentions`].
    ///
    /// [`AllowedMentions`]: ./struct.AllowedMentions.html
    /// [`ClientBuilder#default_allowed_mentions`]: ../../../../client/struct.ClientBuilder.html#method.default_allowed_mentions
    pub fn build_solo(self) -> AllowedMentions {
        let mut m = AllowedMentions::default();

        self.e.visit(&mut m);
        self.u.visit(&mut m);
        self.r.visit(&mut m);
        m
    }
}