feat(plugins): implement events

- Events: onConnect and onSend now works
This commit is contained in:
MedzikUser 2022-08-13 12:06:53 +02:00
parent 6f7edf3d30
commit f27df56c47
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
5 changed files with 37 additions and 7 deletions

View File

@ -36,8 +36,20 @@ impl Command for PluginTest {
} }
} }
#[async_trait]
impl Event for PluginTest {
fn event(&self) -> EventType {
EventType::OnConnect
}
async fn execute(&self, client: &Client) -> anyhow::Result<()> {
client.send("Hello!")
}
}
#[no_mangle] #[no_mangle]
pub fn plugin_entry(registrar: &mut dyn Registrar) { pub fn plugin_entry(registrar: &mut dyn Registrar) {
registrar.register_plugins(Box::new(PluginTest)); registrar.register_plugins(Box::new(PluginTest));
registrar.register_commands(Box::new(PluginTest)); registrar.register_commands(Box::new(PluginTest));
registrar.register_events(Box::new(PluginTest));
} }

View File

@ -3,6 +3,7 @@
# stable # stable
edition = "2021" edition = "2021"
newline_style = "Unix" newline_style = "Unix"
match_block_trailing_comma = true
# nightly # nightly
group_imports = "StdExternalCrate" group_imports = "StdExternalCrate"

View File

@ -29,6 +29,7 @@ pub trait Command: Any + Send + Sync {
} }
/// All possible to run events. /// All possible to run events.
#[derive(Debug, PartialEq, Eq)]
pub enum EventType { pub enum EventType {
/// On client connected. /// On client connected.
OnConnect, OnConnect,
@ -42,7 +43,7 @@ pub trait Event: Any + Send + Sync {
/// Type of the event. /// Type of the event.
fn event(&self) -> EventType; fn event(&self) -> EventType;
/// Event function. /// Event function.
async fn execute(&self) -> anyhow::Result<()>; async fn execute(&self, client: &Client) -> anyhow::Result<()>;
} }
pub trait Registrar { pub trait Registrar {

View File

@ -9,7 +9,7 @@ use std::{
use tungstenite::{accept, Message, WebSocket}; use tungstenite::{accept, Message, WebSocket};
use super::run::PLUGINS_MANAGER; use super::run::PLUGINS_MANAGER;
use crate::plugins::manager::PluginsManagerType; use crate::plugins::{manager::PluginsManagerType, prelude::EventType};
/// Max length of a TCP and UDP packet /// Max length of a TCP and UDP packet
pub const MAX_PACKET_LEN: usize = 65536; pub const MAX_PACKET_LEN: usize = 65536;
@ -110,14 +110,14 @@ impl Client {
// decode buffer (&[u8]) to a String // decode buffer (&[u8]) to a String
String::from_utf8(buf.to_vec())? String::from_utf8(buf.to_vec())?
} },
ClientStream::WebSocket(stream) => { ClientStream::WebSocket(stream) => {
// read the message from the stream // read the message from the stream
let msg = stream.lock().unwrap().read_message()?; let msg = stream.lock().unwrap().read_message()?;
// decode message to a String // decode message to a String
msg.to_string() msg.to_string()
} },
}; };
// remove new line characters // remove new line characters
@ -145,7 +145,7 @@ impl Client {
ClientStream::TCP(stream) => stream.as_ref().write_all(buf)?, ClientStream::TCP(stream) => stream.as_ref().write_all(buf)?,
ClientStream::WebSocket(stream) => { ClientStream::WebSocket(stream) => {
stream.lock().unwrap().write_message(Message::from(msg))? stream.lock().unwrap().write_message(Message::from(msg))?
} },
} }
Ok(()) Ok(())
@ -165,7 +165,7 @@ impl Client {
pub fn flush(&self) -> anyhow::Result<()> { pub fn flush(&self) -> anyhow::Result<()> {
match &self.stream { match &self.stream {
ClientStream::TCP(stream) => stream.as_ref().flush()?, ClientStream::TCP(stream) => stream.as_ref().flush()?,
ClientStream::WebSocket(_stream) => {} ClientStream::WebSocket(_stream) => {},
} }
Ok(()) Ok(())
@ -180,4 +180,14 @@ impl Client {
Ok(()) Ok(())
} }
pub async fn run_events(&self, event_type: EventType) -> anyhow::Result<()> {
for event in self.plugins_manager.events.iter() {
if event.event() == event_type {
event.execute(self).await?;
}
}
Ok(())
}
} }

View File

@ -6,7 +6,7 @@ use lazy_static::lazy_static;
use tracing::{error, info}; use tracing::{error, info};
use crate::{ use crate::{
plugins::{self, manager::PluginsManagerType}, plugins::{self, manager::PluginsManagerType, prelude::EventType},
server::Client, server::Client,
CLIENTS, CLIENT_NEXT, CLIENTS, CLIENT_NEXT,
}; };
@ -46,9 +46,15 @@ async fn process(client: Client) -> anyhow::Result<()> {
info!("Processing client connection: {}", client_addr); info!("Processing client connection: {}", client_addr);
// run `onConnect` events
client.run_events(EventType::OnConnect).await?;
loop { loop {
let buf = client.read()?; let buf = client.read()?;
// run `onSend` events
client.run_events(EventType::OnSend).await?;
let mut args: Vec<&str> = buf.split_ascii_whitespace().collect(); let mut args: Vec<&str> = buf.split_ascii_whitespace().collect();
// if client sent an empty buffer // if client sent an empty buffer