circe/src/lib.rs

145 lines
3.6 KiB
Rust

use std::borrow::Cow;
use std::io::{Error, Read, Write};
use std::net::TcpStream;
pub struct Client {
stream: TcpStream,
config: Config,
}
pub struct Config {
username: String,
nickname: String,
mode: String,
}
#[derive(Debug)]
pub enum CapMode {
LS,
END,
}
#[derive(Debug)]
pub enum Command {
PING(String),
PONG(String),
CAP(CapMode),
USER(String, String, String, String),
NICK(String),
OTHER(String),
}
impl Command {
fn from_str(s: &str) -> Self {
let new = s.trim();
if new.starts_with("PING") {
let command: String = String::from(new.split_whitespace().collect::<Vec<&str>>()[1]);
return Self::PING(command);
}
Self::OTHER(new.to_string())
}
}
impl Client {
pub fn new(host: &str, port: u16, config: Config) -> Result<Self, Error> {
let stream = TcpStream::connect(format!("{}:{}", host, port))?;
Ok(Self { stream, config })
}
pub fn identify(&mut self) -> Result<(), Error> {
self.write_command(Command::CAP(CapMode::END))?;
self.write_command(Command::USER(
self.config.username.clone(),
"*".into(),
"*".into(),
self.config.username.clone(),
))?;
self.write_command(Command::NICK(self.config.nickname.clone()))?;
Ok(())
}
// temporarily pub, change this later
pub fn read_string(&mut self) -> Option<String> {
let mut buffer = [0u8; 512];
match self.stream.read(&mut buffer) {
Ok(_) => {}
Err(_) => return None,
};
Some(String::from_utf8_lossy(&buffer).into())
}
pub fn read(&mut self) -> Result<Command, ()> {
if let Some(string) = self.read_string() {
return Ok(Command::from_str(&string));
}
Err(())
}
fn write(&mut self, data: &str) -> Result<(), Error> {
let formatted = {
let new = format!("{}\r\n", data);
Cow::Owned(new) as Cow<str>
};
self.stream.write(formatted.as_bytes())?;
Ok(())
}
pub fn write_command(&mut self, command: Command) -> Result<(), Error> {
use Command::*;
let computed = match command {
CAP(mode) => {
use CapMode::*;
Cow::Borrowed(match mode {
LS => "CAP LS 302",
END => "CAP END",
}) as Cow<str>
}
USER(username, s1, s2, realname) => {
let formatted = format!("USER {} {} {} :{}", username, s1, s2, realname);
Cow::Owned(formatted) as Cow<str>
}
NICK(nickname) => {
let formatted = format!("NICK {}", nickname);
Cow::Owned(formatted) as Cow<str>
}
PING(code) => {
let formatted = format!("PING {}", code);
Cow::Owned(formatted) as Cow<str>
}
PONG(code) => {
let formatted = format!("PONG {}", code);
Cow::Owned(formatted) as Cow<str>
}
OTHER(_) => {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Cannot write commands of type OTHER",
));
}
};
self.write(&computed)?;
Ok(())
}
}
impl Config {
pub fn new(username: &str, nickname: Option<&str>, mode: Option<&str>) -> Self {
Self {
username: username.into(),
nickname: nickname.unwrap_or(username).into(),
mode: mode.unwrap_or("").into(),
}
}
}