diff --git a/json-api/src/rtc.rs b/json-api/src/rtc.rs index f992475..85e8f54 100644 --- a/json-api/src/rtc.rs +++ b/json-api/src/rtc.rs @@ -12,20 +12,65 @@ * is sufficiently large & securely transferred on both parties behalf */ - -use websocket::ClientBuilder; -use websocket::r#async::client::{Client, ClientNew}; -use websocket::r#async::TcpStream; -use websocket::futures::{Future, Stream, Sink}; -use websocket::Message; -use websocket::url::Url; - +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::Message; +use futures::{StreamExt, SinkExt}; +use serde::Serialize; +use serde_json::json; +use jsonwebtoken::{ + Header, Algorithm, EncodingKey +}; +lazy_static! { + static ref HMAC_SECRET: Vec = { + std::fs::read("wss-hmac.secret").expect("Couldn't get HMAC secret") + }; + static ref WSS_KEY: EncodingKey = { + EncodingKey::from_secret(&HMAC_SECRET) + }; +} + +macro_rules! event { + ($type:literal, $payload:expr) => { + json!({"type": $type, $type: $payload}) + } +} + +#[derive(Serialize)] +struct Claim { + nbf: i64 +} + +impl Claim { + pub fn new() -> Self { + let now = (SystemTime::now() + Duration::from_secs(0)) + .duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; + let now = now / 1000; + Self { + nbf: now + } + } +} pub async fn new_message(message: db::Message) { - // just open and close for now - let (mut ws, _) = connect_async("ws://localhost:5648").await.unwrap(); - ws.close(None); + let claim = Claim::new(); + let header = Header::new(Algorithm::HS512); + let jwt = jsonwebtoken::encode(&header, &claim, &WSS_KEY).unwrap(); + + match connect_async(format!("ws://localhost:5648/jwt/{}", jwt)).await { + Ok((ws, _read)) => { + let (mut write, _read) = ws.split(); + let m = event!("message", &message); + let m = m.to_string(); + + if let Err(e) = write.send(Message::text(m)).await { + eprintln!("[RTC-COMM-ERR] {}", e) + } + }, + Err(e) => { + eprintln!("unable to connect to rtc: {}", e); + } + }; }