mod event;
mod kwai;
mod stream;
pub use event::*;
use futures_lite::Stream;
use kwai::ConnectReq;
use reqwest::Proxy;
use serde::Deserialize;
pub use stream::EventStream;
#[derive(Debug, Clone, Copy)]
pub enum AppType {
Game = 0,
Tool = 1,
}
impl Default for AppType {
fn default() -> Self {
Self::Game
}
}
#[derive(Default, Debug)]
pub struct ConnectParams {
pub host: String,
pub app_id: String,
pub code: String,
pub play_id: u32,
pub app_type: AppType,
pub header: Option<String>,
pub role_name: Option<String>,
pub http_proxies: Vec<Proxy>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ConnectResp {
pub ks_uid: u32,
pub user: User,
pub token: String,
}
pub struct Connection {
pub info: ConnectResp,
stream: Option<EventStream>,
app_type: AppType,
host: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct User {
pub id: String,
pub user_name: Option<String>,
pub head_url: Option<String>,
pub gender: Option<String>,
}
#[inline]
pub async fn connect(params: ConnectParams) -> anyhow::Result<Connection> {
let mut http_client_builder = reqwest::ClientBuilder::new();
let req = ConnectReq {
host: params.host.clone(),
app_id: params.app_id,
code: params.code,
play_id: params.play_id,
header: params.header,
role_name: params.role_name,
app_type: params.app_type as u8,
use_sdk: true,
};
for proxy in params.http_proxies {
http_client_builder = http_client_builder.proxy(proxy);
}
let http_client = http_client_builder.build()?;
let connect_resp = kwai::connect(&http_client, &req).await?;
let stream = EventStream::new(
http_client,
&req.host,
params.app_type,
connect_resp.token.clone(),
)?;
Ok(Connection {
info: connect_resp,
app_type: params.app_type,
host: params.host,
stream: Some(stream),
})
}
impl Connection {
pub fn get_msg_stream(&mut self) -> impl Stream<Item = Event> {
self.stream
.take()
.expect("消息流只能获取一次")
.into_stream()
}
#[inline]
pub async fn disconnect(&self) -> anyhow::Result<()> {
kwai::disconnect(&self.host, &self.info.token, self.app_type).await
}
#[inline]
pub async fn update_all_user_panel(&self, panel_id: i32) -> anyhow::Result<()> {
kwai::update_all_user_panel(&self.host, &self.info.token, panel_id).await
}
#[inline]
pub async fn update_user_panel(&self, panel_id: i32, open_id: &str) -> anyhow::Result<()> {
kwai::update_user_panel(&self.host, &self.info.token, panel_id, open_id).await
}
}