2022-06-04 19:34:53 +00:00
|
|
|
use std::io::Write;
|
|
|
|
|
2022-06-05 14:08:13 +00:00
|
|
|
use log::trace;
|
|
|
|
|
2022-06-16 17:31:09 +00:00
|
|
|
use crate::plugins::{CommandManagerType, EventManagerType};
|
2022-06-04 19:34:53 +00:00
|
|
|
|
|
|
|
use super::Client;
|
|
|
|
|
2022-06-05 20:10:23 +00:00
|
|
|
/// Handle Client connection
|
2022-06-04 19:34:53 +00:00
|
|
|
pub async fn handle_connection(
|
|
|
|
mut client: Client,
|
|
|
|
commands: CommandManagerType,
|
2022-06-16 17:31:09 +00:00
|
|
|
events: EventManagerType,
|
2022-06-04 19:34:53 +00:00
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
println!("New Client: {:?}", client.stream.peer_addr()?);
|
|
|
|
|
2022-06-16 17:31:09 +00:00
|
|
|
// run `onConnect` events from plugins
|
|
|
|
check_event(&mut client, &events, "onConnect").await;
|
|
|
|
|
2022-06-04 19:34:53 +00:00
|
|
|
loop {
|
|
|
|
// read client message/buffer
|
2022-06-05 21:13:14 +00:00
|
|
|
let buf = client.read()?;
|
2022-06-04 19:34:53 +00:00
|
|
|
|
2022-06-16 17:31:09 +00:00
|
|
|
// run `onSend` events from plugins
|
|
|
|
check_event(&mut client, &events, "onSend").await;
|
|
|
|
|
2022-06-04 19:34:53 +00:00
|
|
|
// split message by whitespace
|
|
|
|
let args: &Vec<&str> = &buf.split_ascii_whitespace().collect();
|
|
|
|
|
|
|
|
// get command from args
|
|
|
|
let cmd = args[0];
|
|
|
|
|
|
|
|
// search if a command exists
|
2022-06-05 14:08:13 +00:00
|
|
|
for command in commands.commands.iter() {
|
2022-06-04 19:34:53 +00:00
|
|
|
// if this is the entered command
|
|
|
|
if cmd == command.name() {
|
2022-06-05 14:08:13 +00:00
|
|
|
trace!("Executing a command `{}`", command.name());
|
2022-06-16 17:31:09 +00:00
|
|
|
|
|
|
|
// execute command
|
2022-06-04 19:34:53 +00:00
|
|
|
command
|
|
|
|
.execute(&mut client, args[1..args.len()].to_vec(), &commands)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
// don't search for more commands
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// if an I/O or EOF error, abort the connection
|
|
|
|
if client.stream.flush().is_err() {
|
|
|
|
// terminate connection
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2022-06-16 17:31:09 +00:00
|
|
|
|
2022-06-17 11:43:23 +00:00
|
|
|
/// Search for a events and execute it
|
2022-06-16 17:31:09 +00:00
|
|
|
async fn check_event(client: &mut Client, events: &EventManagerType, event_name: &str) {
|
|
|
|
for event in events.events.iter() {
|
|
|
|
// check if this event should be started
|
|
|
|
if event.name() == event_name {
|
|
|
|
trace!("Executing a event `{}`", event.name());
|
|
|
|
|
|
|
|
// execute event
|
|
|
|
event.execute(client).await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|