Skip to main content

kira_framework/network/connect/
mod.rs

1use std::sync::Arc;
2use async_trait::async_trait;
3use bevy_async_ecs::AsyncWorld;
4use bevy_ecs::prelude::Resource;
5use log::info;
6use tokio::sync::RwLock;
7use tokio_tungstenite::tungstenite::Message;
8use crate::network::actions::{OneBotActionReturn, OneBotActionReturnTrait, OneBotActionTrait};
9use crate::network::events::OneBotEventTrait;
10use crate::pretty_debug::KiraPrettyDebug;
11
12pub mod reverse;
13
14#[async_trait]
15pub trait OneBotConnectTrait {
16    async fn connect(&mut self) -> anyhow::Result<()>;
17    async fn send_event(&self, event: Box<dyn OneBotEventTrait + Send + Sync>) -> anyhow::Result<()>;
18    async fn send_action(&self, action: Box<dyn OneBotActionTrait + Send + Sync>) -> anyhow::Result<()>;
19    async fn recv(&self) -> anyhow::Result<Message>;
20    async fn recv_return(&self) -> anyhow::Result<OneBotActionReturn>;
21}
22
23#[derive(Resource, Clone)]
24pub struct OneBotConnect {
25    connect: Arc<RwLock<Box<dyn OneBotConnectTrait + Sync + Send>>>,
26    world: Option<AsyncWorld>,
27}
28
29impl OneBotConnect {
30    pub fn new<T: OneBotConnectTrait + Sync + Send + 'static>(connect: T) -> Self {
31        Self {
32            connect: Arc::new(RwLock::new(Box::new(connect))),
33            world: None,
34        }
35    }
36
37    pub fn set_world(&mut self, world: AsyncWorld) {
38        self.world = Some(world);
39    }
40
41    pub fn world(&self) -> AsyncWorld {
42        self.world.clone().unwrap()
43    }
44
45    pub async fn connect(&self) -> anyhow::Result<()> {
46        self.connect.write().await.connect().await
47    }
48
49    pub async fn send_action<E: OneBotActionTrait + Send + Sync + 'static>(&self, action: E) -> anyhow::Result<()> {
50        self.connect.read().await.send_action(Box::new(action)).await
51    }
52
53    pub async fn recv(&self) -> anyhow::Result<Message> {
54        self.connect.read().await.recv().await
55    }
56
57    pub async fn recv_return<T: OneBotActionReturnTrait + Send + Sync + 'static + KiraPrettyDebug>(&self) -> anyhow::Result<T> {
58        let ret = self.connect.read().await.recv_return().await?.get_data::<T>()?;
59        let pretty_debug = KiraPrettyDebug::pretty_debug(&ret);
60        if !pretty_debug.is_empty() {
61            info!("{}", pretty_debug);
62        }
63        Ok(ret)
64    }
65}