use std::marker::PhantomData;
use super::*;
use helix::RequestPost;
use serde::Serialize;
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug, Default)]
#[must_use]
#[non_exhaustive]
pub struct SendChatMessageRequest<'a> {
#[serde(skip)]
_marker: PhantomData<&'a ()>,
}
impl SendChatMessageRequest<'_> {
pub fn new() -> Self { SendChatMessageRequest::default() }
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
#[must_use]
#[non_exhaustive]
pub struct SendChatMessageBody<'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 sender_id: Cow<'a, types::UserIdRef>,
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
pub message: Cow<'a, str>,
#[cfg_attr(feature = "typed-builder", builder(setter(into)))]
#[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub reply_parent_message_id: Option<Cow<'a, types::MsgIdRef>>,
}
impl<'a> SendChatMessageBody<'a> {
pub fn new(
broadcaster_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
sender_id: impl types::IntoCow<'a, types::UserIdRef> + 'a,
message: impl types::IntoCow<'a, str> + 'a,
) -> Self {
Self {
broadcaster_id: broadcaster_id.into_cow(),
sender_id: sender_id.into_cow(),
message: message.into_cow(),
reply_parent_message_id: None,
}
}
pub fn reply_parent_message_id(
mut self,
reply_parent_message_id: impl types::IntoCow<'a, types::MsgIdRef> + 'a,
) -> Self {
self.reply_parent_message_id = Some(reply_parent_message_id.into_cow());
self
}
}
impl helix::private::SealedSerialize for SendChatMessageBody<'_> {}
impl helix::HelixRequestBody for [SendChatMessageBody<'_>] {
fn try_to_body(&self) -> Result<hyper::body::Bytes, helix::BodyError> {
#[derive(Serialize)]
struct InnerBody<'a> {
data: &'a [SendChatMessageBody<'a>],
}
serde_json::to_vec(&InnerBody { data: self })
.map_err(Into::into)
.map(Into::into)
}
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ChatMessageDropCode {
MsgBanned,
MsgBadCharacters,
MsgChannelBlocked,
MsgChannelSuspended,
MsgDuplicate,
MsgEmoteonly,
MsgFollowersonly,
MsgFollowersonlyFollowed,
MsgFollowersonlyZero,
MsgR9k,
MsgRatelimit,
MsgRejected,
MsgRejectedMandatory,
MsgRequiresVerifiedPhoneNumber,
MsgSlowmode,
MsgSubsonly,
MsgSuspended,
MsgTimedout,
MsgVerifiedEmail,
#[serde(untagged)]
Unknown(String),
}
impl std::fmt::Display for ChatMessageDropCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.serialize(f) }
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct ChatMessageDropReason {
pub code: ChatMessageDropCode,
pub message: String,
}
#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct SendChatMessageResponse {
#[serde(deserialize_with = "crate::deserialize_none_from_empty_string")]
pub message_id: Option<types::MsgId>,
pub is_sent: bool,
pub drop_reason: Option<ChatMessageDropReason>,
}
impl Request for SendChatMessageRequest<'_> {
type Response = SendChatMessageResponse;
const PATH: &'static str = "chat/messages";
#[cfg(feature = "twitch_oauth2")]
const SCOPE: twitch_oauth2::Validator =
twitch_oauth2::validator![twitch_oauth2::Scope::UserWriteChat];
}
impl<'a> RequestPost for SendChatMessageRequest<'a> {
type Body = SendChatMessageBody<'a>;
fn parse_inner_response<'d>(
request: Option<Self>,
uri: &http::Uri,
response: &str,
status: http::StatusCode,
) -> Result<helix::Response<Self, Self::Response>, helix::HelixRequestPostError>
where
Self: Sized,
{
let resp = match status {
http::StatusCode::OK => {
let resp: helix::InnerResponse<[SendChatMessageResponse; 1]> =
helix::parse_json(response, true).map_err(|e| {
helix::HelixRequestPostError::DeserializeError(
response.to_string(),
e,
uri.clone(),
status,
)
})?;
let [s] = resp.data;
s
}
_ => {
return Err(helix::HelixRequestPostError::InvalidResponse {
reason: "unexpected status",
response: response.to_string(),
status,
uri: uri.clone(),
})
}
};
Ok(helix::Response::with_data(resp, request))
}
}
#[cfg(test)]
#[test]
fn test_success() {
use helix::*;
let req = SendChatMessageRequest::new();
let body = SendChatMessageBody::new("12826", "141981764", "Hello, world! twitchdevHype");
assert_eq!(
std::str::from_utf8(&body.try_to_body().unwrap()).unwrap(),
r#"{"broadcaster_id":"12826","sender_id":"141981764","message":"Hello, world! twitchdevHype"}"#
);
dbg!(req.create_request(body, "token", "clientid").unwrap());
let data = br#"
{
"data": [
{
"message_id": "abc-123-def",
"is_sent": true
}
]
}
"#
.to_vec();
let http_response = http::Response::builder().status(200).body(data).unwrap();
let uri = req.get_uri().unwrap();
assert_eq!(
uri.to_string(),
"https://api.twitch.tv/helix/chat/messages?"
);
dbg!(SendChatMessageRequest::parse_response(Some(req), &uri, http_response).unwrap());
}
#[cfg(test)]
#[test]
fn test_reject() {
use helix::*;
let req = SendChatMessageRequest::new();
let data = br#"
{
"data": [
{
"message_id": "",
"is_sent": false,
"drop_reason": {
"code": "msg_rejected",
"message": "Your message is being checked by mods and has not been sent."
}
}
]
}
"#
.to_vec();
let http_response = http::Response::builder().status(200).body(data).unwrap();
let uri = req.get_uri().unwrap();
let res = SendChatMessageRequest::parse_response(None, &uri, http_response).unwrap();
assert_eq!(res.data.message_id, None);
assert_eq!(
res.data.drop_reason.unwrap().code,
ChatMessageDropCode::MsgRejected
);
let data = br#"
{
"data": [
{
"message_id": "",
"is_sent": false,
"drop_reason": {
"code": "Foo",
"message": "Super unknown"
}
}
]
}
"#
.to_vec();
let http_response = http::Response::builder().status(200).body(data).unwrap();
let res = SendChatMessageRequest::parse_response(None, &uri, http_response).unwrap();
assert_eq!(res.data.message_id, None);
assert_eq!(
res.data.drop_reason.unwrap().code,
ChatMessageDropCode::Unknown("Foo".to_string())
);
}