twitch_api/helix/endpoints/moderation/
unban_user.rs

1//! Removes the ban or timeout that was placed on the specified user.
2//! [`unban-user`](https://dev.twitch.tv/docs/api/reference#unban-user)
3//!
4//! # Accessing the endpoint
5//!
6//! ## Request: [UnbanUserRequest]
7//!
8//! To use this endpoint, construct a [`UnbanUserRequest`] with the [`UnbanUserRequest::new()`] method.
9//!
10//! ```rust
11//! use twitch_api::helix::moderation::unban_user;
12//! let request = unban_user::UnbanUserRequest::new("1234", "5678", "1337");
13//! ```
14//!
15//! ## Response: [UnbanUserResponse]
16//!
17//!
18//! Send the request to receive the response with [`HelixClient::req_delete()`](helix::HelixClient::req_delete).
19//!
20//!
21//! ```rust, no_run
22//! use twitch_api::helix::{self, moderation::unban_user};
23//! # use twitch_api::client;
24//! # #[tokio::main]
25//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
26//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
27//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
28//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
29//! let request = unban_user::UnbanUserRequest::new("1234", "5678", "1337");
30//! let response: unban_user::UnbanUserResponse = client.req_delete(request, &token).await?.data;
31//! # Ok(())
32//! # }
33//! ```
34//!
35//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestDelete::create_request)
36//! and parse the [`http::Response`] with [`UnbanUserRequest::parse_response(None, &request.get_uri(), response)`](UnbanUserRequest::parse_response)
37
38use super::*;
39use helix::RequestDelete;
40/// Query Parameters for [Unban User](super::unban_user)
41///
42/// [`unban-user`](https://dev.twitch.tv/docs/api/reference#unban-user)
43#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
44#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
45#[must_use]
46#[non_exhaustive]
47pub struct UnbanUserRequest<'a> {
48    /// The ID of the broadcaster whose chat room the user is banned from chatting in.
49    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
50    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
51    pub broadcaster_id: Cow<'a, types::UserIdRef>,
52    /// The ID of a user that has permission to moderate the broadcaster’s chat room. This ID must match the user ID associated with the user OAuth token.
53    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
54    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
55    pub moderator_id: Cow<'a, types::UserIdRef>,
56    /// The ID of the user to remove the ban or timeout from.
57    #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
58    #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
59    pub user_id: Cow<'a, types::UserIdRef>,
60}
61
62impl<'a> UnbanUserRequest<'a> {
63    /// Remove the ban or timeout that was placed on the specified user.
64    pub fn new(
65        broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
66        moderator_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
67        user_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
68    ) -> Self {
69        Self {
70            broadcaster_id: broadcaster_id.into_cow(),
71            moderator_id: moderator_id.into_cow(),
72            user_id: user_id.into_cow(),
73        }
74    }
75}
76
77/// Return Values for [Unban User](super::unban_user)
78///
79/// [`unban-user`](https://dev.twitch.tv/docs/api/reference#unban-user)
80#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
81#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
82#[non_exhaustive]
83pub enum UnbanUserResponse {
84    /// Unban was successful
85    Success,
86}
87
88impl Request for UnbanUserRequest<'_> {
89    type PaginationData = ();
90    type Response = UnbanUserResponse;
91
92    const PATH: &'static str = "moderation/bans";
93    #[cfg(feature = "twitch_oauth2")]
94    const SCOPE: twitch_oauth2::Validator =
95        twitch_oauth2::validator![twitch_oauth2::Scope::ModeratorManageBannedUsers];
96}
97
98impl RequestDelete for UnbanUserRequest<'_> {
99    fn parse_inner_response(
100        request: Option<Self>,
101        uri: &http::Uri,
102        response: &str,
103        status: http::StatusCode,
104    ) -> Result<helix::Response<Self, Self::Response>, helix::HelixRequestDeleteError>
105    where
106        Self: Sized,
107    {
108        match status {
109            http::StatusCode::NO_CONTENT => Ok(helix::Response::with_data(
110                UnbanUserResponse::Success,
111                request,
112            )),
113            _ => Err(helix::HelixRequestDeleteError::InvalidResponse {
114                reason: "unexpected status",
115                response: response.to_string(),
116                status,
117                uri: uri.clone(),
118            }),
119        }
120    }
121}
122
123#[cfg(test)]
124#[test]
125fn test_request() {
126    use helix::*;
127    let req = UnbanUserRequest::new("1234", "5678", "9876");
128
129    dbg!(req.create_request("token", "clientid").unwrap());
130
131    // From twitch docs
132    let data = br#"
133    "#
134    .to_vec();
135
136    let http_response = http::Response::builder().status(204).body(data).unwrap();
137
138    let uri = req.get_uri().unwrap();
139    assert_eq!(
140        uri.to_string(),
141        "https://api.twitch.tv/helix/moderation/bans?broadcaster_id=1234&moderator_id=5678&user_id=9876"
142    );
143
144    dbg!(UnbanUserRequest::parse_response(Some(req), &uri, http_response).unwrap());
145}