Skip to main content

twilight_http/request/channel/webhook/
update_webhook_with_token.rs

1#[cfg(not(target_os = "wasi"))]
2use crate::response::{Response, ResponseFuture};
3use crate::{
4    client::Client,
5    error::Error,
6    request::{Nullable, Request, TryIntoRequest},
7    routing::Route,
8};
9use serde::Serialize;
10use std::future::IntoFuture;
11use twilight_model::{
12    channel::Webhook,
13    id::{Id, marker::WebhookMarker},
14};
15use twilight_validate::request::{ValidationError, webhook_username as validate_webhook_username};
16
17#[derive(Serialize)]
18struct UpdateWebhookWithTokenFields<'a> {
19    #[serde(skip_serializing_if = "Option::is_none")]
20    avatar: Option<Nullable<&'a str>>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    name: Option<&'a str>,
23}
24
25/// Update a webhook, with a token, by ID.
26#[must_use = "requests must be configured and executed"]
27pub struct UpdateWebhookWithToken<'a> {
28    fields: Result<UpdateWebhookWithTokenFields<'a>, ValidationError>,
29    http: &'a Client,
30    token: &'a str,
31    webhook_id: Id<WebhookMarker>,
32}
33
34impl<'a> UpdateWebhookWithToken<'a> {
35    pub(crate) const fn new(
36        http: &'a Client,
37        webhook_id: Id<WebhookMarker>,
38        token: &'a str,
39    ) -> Self {
40        Self {
41            fields: Ok(UpdateWebhookWithTokenFields {
42                avatar: None,
43                name: None,
44            }),
45            http,
46            token,
47            webhook_id,
48        }
49    }
50
51    /// Set the avatar of the webhook.
52    ///
53    /// This must be a Data URI, in the form of
54    /// `data:image/{type};base64,{data}` where `{type}` is the image MIME type
55    /// and `{data}` is the base64-encoded image. See [Discord Docs/Image Data].
56    ///
57    /// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data
58    pub const fn avatar(mut self, avatar: Option<&'a str>) -> Self {
59        if let Ok(fields) = self.fields.as_mut() {
60            fields.avatar = Some(Nullable(avatar));
61        }
62
63        self
64    }
65
66    /// Change the name of the webhook.
67    ///
68    /// # Errors
69    ///
70    /// Returns an error of type [`WebhookUsername`] if the webhook's name is
71    /// invalid.
72    ///
73    /// [`WebhookUsername`]: twilight_validate::request::ValidationErrorType::WebhookUsername
74    pub fn name(mut self, name: &'a str) -> Self {
75        self.fields = self.fields.and_then(|mut fields| {
76            validate_webhook_username(name)?;
77            fields.name = Some(name);
78
79            Ok(fields)
80        });
81
82        self
83    }
84}
85
86#[cfg(not(target_os = "wasi"))]
87impl IntoFuture for UpdateWebhookWithToken<'_> {
88    type Output = Result<Response<Webhook>, Error>;
89
90    type IntoFuture = ResponseFuture<Webhook>;
91
92    fn into_future(self) -> Self::IntoFuture {
93        let http = self.http;
94
95        match self.try_into_request() {
96            Ok(request) => http.request(request),
97            Err(source) => ResponseFuture::error(source),
98        }
99    }
100}
101
102impl TryIntoRequest for UpdateWebhookWithToken<'_> {
103    fn try_into_request(self) -> Result<Request, Error> {
104        let fields = self.fields.map_err(Error::validation)?;
105
106        Request::builder(&Route::UpdateWebhook {
107            token: Some(self.token),
108            webhook_id: self.webhook_id.get(),
109        })
110        .use_authorization_token(false)
111        .json(&fields)
112        .build()
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use std::error::Error;
120
121    #[test]
122    fn test_update_webhook_with_token() -> Result<(), Box<dyn Error>> {
123        const WEBHOOK_ID: Id<WebhookMarker> = Id::new(1);
124
125        let client = Client::new("token".into());
126
127        {
128            let expected = r"{}";
129            let actual =
130                UpdateWebhookWithToken::new(&client, WEBHOOK_ID, "token").try_into_request()?;
131
132            assert_eq!(Some(expected.as_bytes()), actual.body());
133        }
134
135        {
136            let expected = r#"{"avatar":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI"}"#;
137            let actual = UpdateWebhookWithToken::new(&client, WEBHOOK_ID, "token")
138            .avatar(Some("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI"))
139                .try_into_request()?;
140
141            assert_eq!(Some(expected.as_bytes()), actual.body());
142
143            let expected = r#"{"avatar":null}"#;
144            let actual = UpdateWebhookWithToken::new(&client, WEBHOOK_ID, "token")
145                .avatar(None)
146                .try_into_request()?;
147
148            assert_eq!(Some(expected.as_bytes()), actual.body());
149        }
150
151        {
152            let expected = r#"{"name":"Captain Hook"}"#;
153            let actual = UpdateWebhookWithToken::new(&client, WEBHOOK_ID, "token")
154                .name("Captain Hook")
155                .try_into_request()?;
156
157            assert_eq!(Some(expected.as_bytes()), actual.body());
158        }
159
160        {
161            let expected = r#"{"avatar":null,"name":"Captain Hook"}"#;
162            let actual = UpdateWebhookWithToken::new(&client, WEBHOOK_ID, "token")
163                .avatar(None)
164                .name("Captain Hook")
165                .try_into_request()?;
166
167            assert_eq!(Some(expected.as_bytes()), actual.body());
168        }
169        Ok(())
170    }
171}