use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
#[async_trait]
pub trait ActionHandler<A, R>
where
A: DeserializeOwned + std::fmt::Debug + Send + 'static,
R: Serialize + std::fmt::Debug + Send + 'static,
{
async fn handle(&self, action: A) -> R;
}
#[async_trait]
pub trait EventHandler<E>
where
E: Clone + DeserializeOwned + Send + 'static + std::fmt::Debug,
{
async fn handle(&self, event: E);
}
pub struct DefaultHandler;
impl DefaultHandler {
pub fn arc() -> Arc<Self> {
Arc::new(Self)
}
}
#[async_trait]
impl ActionHandler<crate::Action, crate::ActionResps> for DefaultHandler {
async fn handle(&self, action: crate::Action) -> crate::ActionResps {
use crate::{
action_resp::{ActionResp, ActionRespContent},
Action,
};
match action {
Action::GetVersion(_) => {
ActionResp::success(ActionRespContent::Version(get_version().await))
}
_ => ActionResp::unsupported_action(),
}
}
}
#[async_trait]
impl EventHandler<crate::Event> for DefaultHandler {
async fn handle(&self, event: crate::Event) {
use crate::EventContent;
use colored::*;
use tracing::info;
match &event.content {
EventContent::Meta(m) => info!(
target: "Walle-core",
"[{}] MetaEvent -> Type {}",
event.self_id.red(),
m.detail_type().green()
),
EventContent::Message(m) => {
let alt = if m.alt_message.is_empty() {
let mut t = format!("{:?}", m.message);
if t.len() > 15 {
let _ = t.split_off(15);
}
t
} else {
m.alt_message.clone()
};
info!(
target: "Walle-core",
"[{}] MessageEvent -> from {} alt {}",
event.self_id.red(),
m.user_id.blue(),
alt.green()
)
}
EventContent::Notice(_) => {
info!(target: "Walle-core","[{}] NoticeEvent ->", event.self_id.red())
}
EventContent::Request(_) => {
info!(target: "Walle-core","[{}]RequestEvent ->", event.self_id.red())
}
}
}
}
async fn get_version() -> crate::action_resp::VersionContent {
crate::action_resp::VersionContent::default()
}