2018-03-29 17:40:56 -04:00
|
|
|
use std::{
|
2018-04-03 06:03:08 -04:00
|
|
|
io::{Write, Read},
|
2018-03-29 17:40:56 -04:00
|
|
|
marker::Sized,
|
2018-04-03 06:03:08 -04:00
|
|
|
fmt::Debug,
|
|
|
|
path::PathBuf,
|
2018-03-29 17:40:56 -04:00
|
|
|
};
|
|
|
|
|
2018-04-03 06:03:08 -04:00
|
|
|
use models::{Payload, Message, OpCode};
|
2018-03-29 17:40:56 -04:00
|
|
|
use error::Result;
|
|
|
|
|
2018-03-22 17:54:49 -04:00
|
|
|
|
|
|
|
pub trait Connection
|
|
|
|
where Self: Sized
|
|
|
|
{
|
2018-04-03 06:03:08 -04:00
|
|
|
type Socket: Write + Read;
|
|
|
|
|
|
|
|
|
|
|
|
fn socket(&mut self) -> &mut Self::Socket;
|
|
|
|
|
|
|
|
fn ipc_path() -> PathBuf;
|
|
|
|
|
2018-03-22 17:54:49 -04:00
|
|
|
fn connect() -> Result<Self>;
|
|
|
|
|
2018-04-03 06:03:08 -04:00
|
|
|
fn socket_path(n: u8) -> PathBuf {
|
|
|
|
Self::ipc_path().join(format!("discord-ipc-{}", n))
|
|
|
|
}
|
|
|
|
|
2018-03-23 17:24:06 -04:00
|
|
|
fn send<T>(&mut self, opcode: OpCode, payload: T) -> Result<()>
|
2018-04-03 06:03:08 -04:00
|
|
|
where T: Payload + Debug
|
|
|
|
{
|
|
|
|
debug!("payload: {:#?}", payload);
|
|
|
|
match Message::new(opcode, payload).encode() {
|
|
|
|
Err(why) => error!("{:?}", why),
|
|
|
|
Ok(bytes) => {
|
|
|
|
self.socket().write_all(bytes.as_ref())?;
|
|
|
|
debug!("sent opcode: {:?}", opcode);
|
|
|
|
self.recv()?;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(())
|
|
|
|
}
|
2018-03-22 17:54:49 -04:00
|
|
|
|
2018-04-03 06:03:08 -04:00
|
|
|
fn recv(&mut self) -> Result<Vec<u8>> {
|
|
|
|
let mut buf: Vec<u8> = vec![0; 1024];
|
|
|
|
let n = self.socket().read(buf.as_mut_slice())?;
|
|
|
|
buf.resize(n, 0);
|
|
|
|
debug!("{:?}", Message::decode(&buf));
|
|
|
|
Ok(buf)
|
|
|
|
}
|
2018-03-22 17:54:49 -04:00
|
|
|
}
|