Message event now asynchonously emitted from /message/send to rtc server
+ Server claims are now also generated per request so this could get some benefit from caching the jwt One idea is to cache a jwt for a temporary amount of time + event! macro also lets us generate json payloads more easily ! Still requiring this module to built under an optional feature however that should be done easily
This commit is contained in:
parent
c6a49a8437
commit
e496fbdd1a
@ -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<u8> = {
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user