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>, Error> { let (socket, response) = connect(&wscfg.endpoint).expect("Can't connect"); Ok(socket) } pub async fn websocketinit( ctx: &Arc>, ipeventtx: &Sender, ) -> ( Arc>>>, WebSocket>, ) { 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>>>, txpubsub: Sender, ) { tokio::spawn(async move { loop { let msgs: Option; { 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>, ip: &IpEvent, _ret: &mut Vec, ) { 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:?}") } }; }