use crate::api::*; use crate::AppState; use crate::Arc; 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."); // this is a broadcast let _ = tx.send(game_json); } else { tracing::error!("Failed to convert Game object to JSON.") } state.games.lock().unwrap().push(new_game_object); let _ = tx.send(serde_json::to_string(&server_sum_update(state)).unwrap()); // let _update = tx.send(motd()); } else { let _res = tx.send(String::from("error creating game")); } } else if let Ok(chat_message) = serde_json::from_str::(&text) { let msg = format! {"{0}: {1}", who.name, chat_message.text}; tracing::debug!("{msg}"); let _res = tx.send(msg); } else { tracing::debug!("Unhandled message: {}", &text); } } 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); let _ = state.users.lock().unwrap().remove(who); let _ = tx.send(serde_json::to_string(&server_sum_update(state)).unwrap()); } Message::Pong(ping) => { tracing::debug!("Pong received with: {:?}", ping); } Message::Ping(pong) => { tracing::debug!("Pong received with: {:?}", pong); } } }