sparkle_impostor/
username.rs

1use twilight_validate::request::{
2    ValidationErrorType, WEBHOOK_USERNAME_LIMIT_MAX, WEBHOOK_USERNAME_LIMIT_MIN,
3};
4
5use crate::MessageSource;
6
7impl MessageSource<'_> {
8    /// Sanitize the username if it's invalid
9    ///
10    /// This is necessary because usernames or nicks don't have the same
11    /// requirements as webhook usernames
12    ///
13    /// If the username is under [`WEBHOOK_USERNAME_LIMIT_MIN`], appends
14    /// `append` to it, make sure `append` is under 32 characters and is not
15    /// empty
16    ///
17    /// If the username is over [`WEBHOOK_USERNAME_LIMIT_MAX`], trims it and
18    /// ends it with "..."
19    ///
20    /// Replaces invalid substrings with `replace`, make sure it's over
21    /// [`WEBHOOK_USERNAME_LIMIT_MIN`] characters and under 6 characters
22    #[must_use]
23    pub fn sanitize_username(mut self, append: &str, replace: &str) -> Self {
24        if let Err(ValidationErrorType::WebhookUsername { len, substring }) =
25            twilight_validate::request::webhook_username(&self.username)
26                .map_err(|err| err.into_parts().0)
27        {
28            if let Some(len_inner) = len {
29                if len_inner < WEBHOOK_USERNAME_LIMIT_MIN {
30                    self.username.push_str(append);
31                }
32                if len_inner > WEBHOOK_USERNAME_LIMIT_MAX {
33                    self.username = self
34                        .username
35                        .chars()
36                        .take(WEBHOOK_USERNAME_LIMIT_MAX - 3)
37                        .collect();
38                    self.username.push_str("...");
39                }
40            }
41
42            if let Some(substring_inner) = substring {
43                self.username = self.username.replace(substring_inner, replace);
44            }
45        }
46
47        self
48    }
49}