use crate::api::{greeting, Message, User}; use crate::AppState; use crate::Arc; use anyhow::Result; use lib::models::*; pub async fn message_handler(message: Message, state: &Arc, who: &User) { let tx = &state.tx; match message { Message::Text(text) => { if let Ok(new_game) = serde_json::from_str::(&text) { tracing::debug!("New game request received."); // create game if let Ok(new_game_object) = Game::new(new_game) { if let Ok(game_json) = serde_json::to_string(&new_game_object) { tracing::debug!("Sent new game JSON."); let _ = tx.send(game_json); } else { tracing::error!("Failed to convert Game object to JSON.") } state.games.lock().unwrap().push(new_game_object); let _update = tx.send(greeting(state)); } else { let _res = tx.send(String::from("error creating game")); } } else { // just echo let msg = format! {"{0}: {1}", who.name, text}; tracing::debug!("{msg}"); let _res = tx.send(msg); } } Message::Binary(data) => { tracing::debug!("Binary: {:?}", data) } Message::Close(c) => { if let Some(cf) = c { tracing::debug!( "Close received from {0} with code: {1} and reason: {2}", who.addr, cf.code, cf.reason ) } else { tracing::debug!("close received without close frame") } let msg = format!("{0} left.", who.name); tracing::debug!("{msg}"); let _ = tx.send(msg); } Message::Pong(ping) => { tracing::debug!("Pong received with: {:?}", ping); } Message::Ping(pong) => { tracing::debug!("Pong received with: {:?}", pong); } } }