106 lines
2.9 KiB
Rust
106 lines
2.9 KiB
Rust
|
use crate::config::{Context, WebSocketCfg};
|
||
|
use crate::ip::IpEvent;
|
||
|
use crate::utils::gethostname;
|
||
|
use std::net::TcpStream;
|
||
|
use tungstenite::stream::*;
|
||
|
use tungstenite::*;
|
||
|
|
||
|
use std::sync::Arc;
|
||
|
use tokio::sync::mpsc::Sender;
|
||
|
use tokio::sync::RwLock;
|
||
|
|
||
|
pub async fn websocketconnect<'a>(
|
||
|
wscfg: &WebSocketCfg,
|
||
|
) -> Result<WebSocket<MaybeTlsStream<TcpStream>>, Error> {
|
||
|
let (socket, response) = connect(&wscfg.endpoint).expect("Can't connect");
|
||
|
Ok(socket)
|
||
|
}
|
||
|
|
||
|
pub async fn websocketinit(
|
||
|
ctx: &Arc<RwLock<Context>>,
|
||
|
ipeventtx: &Sender<IpEvent>,
|
||
|
) -> (
|
||
|
Arc<RwLock<WebSocket<MaybeTlsStream<TcpStream>>>>,
|
||
|
WebSocket<MaybeTlsStream<TcpStream>>,
|
||
|
) {
|
||
|
let ctxarc = Arc::clone(&ctx);
|
||
|
|
||
|
let wsreqsocket;
|
||
|
let wssubsocket;
|
||
|
let wssubsocketcb;
|
||
|
{
|
||
|
let ctx = ctxarc.read().await;
|
||
|
wsreqsocket = websocketconnect(&ctx.cfg.ws.get("reqrep").unwrap())
|
||
|
.await
|
||
|
.unwrap();
|
||
|
wssubsocket = Arc::new(RwLock::new(
|
||
|
websocketconnect(&ctx.cfg.ws.get("pubsub").unwrap())
|
||
|
.await
|
||
|
.unwrap(),
|
||
|
));
|
||
|
|
||
|
wssubsocketcb = wssubsocket.clone();
|
||
|
}
|
||
|
|
||
|
wslistenpubsub(wssubsocket, ipeventtx.clone()).await;
|
||
|
return (wssubsocketcb, wsreqsocket);
|
||
|
}
|
||
|
|
||
|
async fn wslistenpubsub(
|
||
|
socket: Arc<RwLock<WebSocket<MaybeTlsStream<TcpStream>>>>,
|
||
|
txpubsub: Sender<IpEvent>,
|
||
|
) {
|
||
|
tokio::spawn(async move {
|
||
|
loop {
|
||
|
let msgs: Option<String>;
|
||
|
{
|
||
|
let mut socket = socket.write().await;
|
||
|
msgs = match socket.read_message() {
|
||
|
Ok(s) => {
|
||
|
println!("msg: {}", s);
|
||
|
None
|
||
|
}
|
||
|
Err(e) => {
|
||
|
println!("error: {e:?}");
|
||
|
socket.close(None).unwrap();
|
||
|
return;
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
match msgs {
|
||
|
Some(ss) => {
|
||
|
let tosend: IpEvent = serde_json::from_str(ss.as_str()).unwrap();
|
||
|
if tosend.ipdata.hostname != gethostname(true)
|
||
|
|| tosend.msgtype == "init".to_string()
|
||
|
{
|
||
|
txpubsub.send(tosend).await.unwrap();
|
||
|
}
|
||
|
}
|
||
|
None => {}
|
||
|
};
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
pub async fn send_to_ipbl_websocket(
|
||
|
reqsocket: &mut WebSocket<MaybeTlsStream<TcpStream>>,
|
||
|
ip: &IpEvent,
|
||
|
_ret: &mut Vec<String>,
|
||
|
) {
|
||
|
let msg = format!("{val}", val = serde_json::to_string(&ip).unwrap());
|
||
|
match reqsocket.write_message(Message::Text(msg)) {
|
||
|
Ok(_) => {}
|
||
|
Err(e) => {
|
||
|
println!("{e:?}")
|
||
|
}
|
||
|
};
|
||
|
match reqsocket.read_message() {
|
||
|
Ok(o) => {
|
||
|
println!("{o}")
|
||
|
}
|
||
|
Err(e) => {
|
||
|
println!("{e:?}")
|
||
|
}
|
||
|
};
|
||
|
}
|