e2e-irc/src/message_stream.rs

47 lines
1.4 KiB
Rust

use ircparser;
use std::io::{Read, Write};
struct MessageStream<'a, StreamType: Write + Read + ?Sized> {
stream: Box<StreamType>,
reciver: &'a str,
sender: &'a str,
}
trait Stream: Write + Read {}
impl Write for MessageStream<'_, dyn Stream> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let to_send = "PRIVMSG".to_owned() + self.sender + &String::from_utf8_lossy(buf) + "\n";
self.stream.write(to_send.as_bytes())?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.stream.flush()
}
}
impl Read for MessageStream<'_, dyn Stream> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut readed = String::new();
let _ = self.stream.read_to_string(&mut readed);
let commands = ircparser::parse(&readed).unwrap();
let mut messages: Vec<String> = vec![];
for command in commands {
let command_string = &command.command;
let command_reciver = &command.params[0];
let command_sender = command.source.unwrap_or("".to_string());
if command_string == "PRIVMSG"
&& command_reciver == self.sender
&& command_sender.starts_with(&format!(":{}", self.reciver))
{
messages.push(command.params[1].clone());
}
}
Ok(messages.join("\n").as_bytes().read(buf)?)
}
}