servers/src/tcp/handle_connection.rs

96 lines
2.7 KiB
Rust
Raw Normal View History

2022-06-04 19:34:53 +00:00
use std::io::Write;
use log::{trace, error};
use crate::plugins::PluginManagerType;
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,
plugin_manager: PluginManagerType,
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, &plugin_manager, "onConnect").await;
2022-06-16 17:31:09 +00:00
2022-06-04 19:34:53 +00:00
loop {
// read client message/buffer
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, &plugin_manager, "onSend").await;
2022-06-16 17:31:09 +00:00
// split message by whitespaces
let args: Vec<&str> = buf.split_ascii_whitespace().collect();
// client sent an empty buffer
if args.is_empty() {
client.send("empty buffer").expect("send message");
// don't execute the following commands because it causes panic
continue;
}
2022-06-04 19:34:53 +00:00
// get command from args
let cmd = args[0];
// search if a command exists
for command in plugin_manager.commands.iter() {
2022-06-04 19:34:53 +00:00
// if this is the entered command
if cmd == command.name() {
trace!("Executing a command `{}`", command.name());
2022-06-16 17:31:09 +00:00
// execute command
let out = command
.execute(&mut client, args[1..args.len()].to_vec(), &plugin_manager)
2022-06-04 19:34:53 +00:00
.await;
match out {
Ok(_) => (),
Err(err) => {
error!("failed to execute command `{cmd}`, error message = `{err}`");
client.send(&format!("error: {err}")).expect("send message to client");
},
}
2022-06-04 19:34:53 +00:00
// 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
async fn check_event(client: &mut Client, events: &PluginManagerType, event_name: &str) {
2022-06-16 17:31:09 +00:00
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
let out = event.execute(client).await;
match out {
Ok(_) => (),
Err(err) => {
error!("failed to execute event `{event_name}`, error message = `{err}`");
client.send(&format!("error: {err}")).expect("send message to client");
},
}
2022-06-16 17:31:09 +00:00
}
}
}