use serde_json::json;
use crate::api::chatroom::ChatRoom;
use crate::model::redpacket::{GestureType, RedPacket, RedPacketInfo};
use crate::utils::error::Error;
use crate::utils::post;
pub struct Redpacket {
api_key: String,
chatroom: ChatRoom,
}
impl Redpacket {
pub fn new(api_key: String) -> Self {
Self {
api_key: api_key.clone(),
chatroom: ChatRoom::new(api_key),
}
}
pub async fn open(
&self,
oid: &str,
gesture: Option<GestureType>,
) -> Result<RedPacketInfo, Error> {
let url = "chat-room/red-packet/open".to_string();
let data = json!({
"oId": oid,
"gesture": gesture.map(|g| g as u8),
"apiKey": self.api_key
});
let resp = post(&url, Some(data)).await?;
if let Some(code) = resp.get("code").and_then(|c| c.as_i64())
&& code != 0
{
return Err(Error::Api(
resp["msg"].as_str().unwrap_or("API error").to_string(),
));
}
let red_packet_info: RedPacketInfo = RedPacketInfo::from_value(&resp)?;
Ok(red_packet_info)
}
pub async fn send(&self, redpacket: &RedPacket) -> Result<(), Error> {
let data = json!({
"type": redpacket.r#type.as_str(),
"money": redpacket.money,
"count": redpacket.count,
"msg": redpacket.msg,
"recivers": redpacket.recivers,
"gesture": redpacket.gesture.clone().map(|g| g as u8),
"apiKey": self.api_key
});
self.chatroom
.send(format!("[redpacket]{}[/redpacket]", data))
.await?;
Ok(())
}
}