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
|
|
|
path::PathBuf,
|
2018-03-29 17:40:56 -04:00
|
|
|
};
|
|
|
|
|
2018-04-05 20:12:59 -04:00
|
|
|
use serde::Serialize;
|
|
|
|
|
|
|
|
use models::message::{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-05 20:12:59 -04:00
|
|
|
where T: Serialize
|
2018-04-03 06:03:08 -04:00
|
|
|
{
|
2018-04-05 20:12:59 -04:00
|
|
|
let message = Message::new(opcode, payload);
|
|
|
|
debug!("{:?}", message);
|
|
|
|
match message.encode() {
|
2018-04-03 06:03:08 -04:00
|
|
|
Err(why) => error!("{:?}", why),
|
|
|
|
Ok(bytes) => {
|
|
|
|
self.socket().write_all(bytes.as_ref())?;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(())
|
|
|
|
}
|
2018-03-22 17:54:49 -04:00
|
|
|
|
2018-04-05 20:12:59 -04:00
|
|
|
fn recv(&mut self) -> Result<Message> {
|
2018-04-03 06:03:08 -04:00
|
|
|
let mut buf: Vec<u8> = vec![0; 1024];
|
|
|
|
let n = self.socket().read(buf.as_mut_slice())?;
|
|
|
|
buf.resize(n, 0);
|
2018-04-05 20:12:59 -04:00
|
|
|
let message = Message::decode(&buf)?;
|
|
|
|
debug!("{:?}", message);
|
|
|
|
Ok(message)
|
2018-04-03 06:03:08 -04:00
|
|
|
}
|
2018-03-22 17:54:49 -04:00
|
|
|
}
|