use futures_util::SinkExt;
use serde::{Deserialize, Serialize};
use tokio::net::TcpStream;
use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};
use tracing::{error, info};
#[derive(Serialize, Deserialize, Debug)]
pub struct ReportMessage {
pub r#type: String,
pub data: String,
}
pub async fn connect_websocket(
ws_url: &str,
auth_secret: &str,
) -> Option<WebSocketStream<MaybeTlsStream<TcpStream>>> {
match connect_async(ws_url).await {
Ok((mut ws_stream, _)) => {
info!("WebSocket connection established");
let auth_msg = ReportMessage {
r#type: "auth".to_string(),
data: auth_secret.to_string(),
};
match ws_stream
.send(Message::Text(
serde_json::to_string(&auth_msg).unwrap().into(),
))
.await
{
Ok(_) => {
info!("Authentication message sent successfully");
Some(ws_stream)
}
Err(e) => {
error!(error = %e, "Failed to send authentication message");
None
}
}
}
Err(e) => {
error!(error = %e, url = %ws_url, "WebSocket connection failed");
None
}
}
}