use super::*;
use helix::RequestPost;
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[must_use]
#[non_exhaustive]
pub struct BanUserRequest<'a> {
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub broadcaster_id: Cow<'a, types::UserIdRef>,
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub moderator_id: Cow<'a, types::UserIdRef>,
}
impl<'a> BanUserRequest<'a> {
pub fn new(
broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
moderator_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
) -> Self {
Self {
broadcaster_id: broadcaster_id.into_cow(),
moderator_id: moderator_id.into_cow(),
}
}
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[non_exhaustive]
pub struct BanUserBody<'a> {
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub user_id: Cow<'a, types::UserIdRef>,
#[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<u32>,
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub reason: Cow<'a, str>,
}
impl<'a> BanUserBody<'a> {
pub fn new(
user_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
reason: impl Into<Cow<'a, str>>,
duration: impl Into<Option<u32>>,
) -> Self {
Self {
user_id: user_id.into_cow(),
reason: reason.into(),
duration: duration.into(),
}
}
}
impl helix::HelixRequestBody for BanUserBody<'_> {
fn try_to_body(&self) -> Result<hyper::body::Bytes, helix::BodyError> {
#[derive(Serialize)]
struct InnerBody<'a> {
data: &'a BanUserBody<'a>,
}
serde_json::to_vec(&InnerBody { data: self })
.map_err(Into::into)
.map(Into::into)
}
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct BanUser {
pub broadcaster_id: types::UserId,
pub created_at: types::Timestamp,
pub end_time: Option<types::Timestamp>,
pub moderator_id: types::UserId,
pub user_id: types::UserId,
}
impl Request for BanUserRequest<'_> {
type Response = BanUser;
const PATH: &'static str = "moderation/bans";
#[cfg(feature = "twitch_oauth2")]
const SCOPE: twitch_oauth2::Validator =
twitch_oauth2::validator![twitch_oauth2::Scope::ModeratorManageBannedUsers];
}
impl<'a> RequestPost for BanUserRequest<'a> {
type Body = BanUserBody<'a>;
fn parse_inner_response(
request: Option<Self>,
uri: &http::Uri,
response: &str,
status: http::StatusCode,
) -> Result<helix::Response<Self, Self::Response>, helix::HelixRequestPostError>
where
Self: Sized,
{
#[derive(PartialEq, Deserialize, Debug, Clone)]
struct InnerResponse {
data: Vec<BanUser>,
}
let InnerResponse { data } = helix::parse_json(response, true).map_err(|e| {
helix::HelixRequestPostError::DeserializeError(
response.to_string(),
e,
uri.clone(),
status,
)
})?;
Ok(helix::Response::with_data(
data.into_iter().next().ok_or_else(|| {
helix::HelixRequestPostError::InvalidResponse {
reason: "missing response data",
response: response.to_string(),
status,
uri: uri.clone(),
}
})?,
request,
))
}
}
#[cfg(test)]
#[test]
fn test_request() {
use helix::*;
let req = BanUserRequest::new("1234", "5678");
let body = BanUserBody::new("9876", "no reason", 300);
assert_eq!(
std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
r#"{"data":{"user_id":"9876","duration":300,"reason":"no reason"}}"#
);
dbg!(req.create_request(body, "token", "clientid").unwrap());
let data = br#"
{
"data": [
{
"broadcaster_id": "1234",
"moderator_id": "5678",
"user_id": "9876",
"created_at": "2021-09-28T19:27:31Z",
"end_time": "2021-09-28T19:22:31Z"
}
]
}
"#
.to_vec();
let http_response = http::Response::builder().body(data).unwrap();
let uri = req.get_uri().unwrap();
assert_eq!(
uri.to_string(),
"https://api.twitch.tv/helix/moderation/bans?broadcaster_id=1234&moderator_id=5678"
);
dbg!(BanUserRequest::parse_response(Some(req), &uri, http_response).unwrap());
}
#[cfg(test)]
#[test]
fn test_request_error() {
use helix::*;
let req = BanUserRequest::new("1234", "5678");
let body = BanUserBody::new("9876", "no reason", 300);
dbg!(req.create_request(body, "token", "clientid").unwrap());
let data = br#"
{
"error": "Bad Request",
"status": 400,
"message": "user is already banned"
}
"#
.to_vec();
let http_response = http::Response::builder().status(400).body(data).unwrap();
let uri = req.get_uri().unwrap();
assert_eq!(
uri.to_string(),
"https://api.twitch.tv/helix/moderation/bans?broadcaster_id=1234&moderator_id=5678"
);
dbg!(BanUserRequest::parse_response(Some(req), &uri, http_response).unwrap_err());
}