cards/server/src/api/message_handler.rs

71 lines
2.6 KiB
Rust
Raw Normal View History

2024-07-24 22:06:19 -04:00
use serde_json::to_string;
2024-07-22 01:32:09 -04:00
use crate::api::*;
2024-05-04 02:23:40 -04:00
use crate::AppState;
use crate::Arc;
2024-06-22 02:16:35 -04:00
2024-07-16 21:11:24 -04:00
pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User) {
2024-05-04 02:23:40 -04:00
let tx = &state.tx;
match message {
Message::Text(text) => {
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
2024-07-21 22:48:15 -04:00
tracing::debug!("New game request received.");
2024-05-04 02:23:40 -04:00
// create game
2024-07-21 22:48:15 -04:00
if let Ok(new_game_object) = Game::new(new_game) {
2024-07-24 22:06:19 -04:00
if let Ok(game_json) = to_string(&new_game_object) {
2024-07-21 23:28:06 -04:00
tracing::debug!("Sent new game JSON.");
2024-07-21 23:38:59 -04:00
// this is a broadcast
2024-07-21 23:28:06 -04:00
let _ = tx.send(game_json);
} else {
tracing::error!("Failed to convert Game object to JSON.")
}
2024-05-04 02:23:40 -04:00
state.games.lock().unwrap().push(new_game_object);
2024-07-24 22:06:19 -04:00
let _ = tx.send(to_string(&server_sum_update(state)).unwrap());
2024-07-22 01:32:09 -04:00
// let _update = tx.send(motd());
2024-05-04 02:23:40 -04:00
} else {
2024-07-21 00:59:21 -04:00
let _res = tx.send(String::from("error creating game"));
2024-05-04 02:23:40 -04:00
}
2024-07-24 19:21:16 -04:00
} else if let Ok(chat_message) = serde_json::from_str::<ChatMessage>(&text) {
let msg = format! {"{0}: {1}", who.name, chat_message.text};
2024-05-04 02:23:40 -04:00
tracing::debug!("{msg}");
2024-07-24 22:06:19 -04:00
let _res = tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap());
2024-07-24 19:21:16 -04:00
} else {
tracing::debug!("Unhandled message: {}", &text);
2024-05-04 02:23:40 -04:00
}
}
Message::Binary(data) => {
tracing::debug!("Binary: {:?}", data)
}
Message::Close(c) => {
if let Some(cf) = c {
tracing::debug!(
2024-07-16 21:11:24 -04:00
"Close received from {0} with code: {1} and reason: {2}",
who.addr,
2024-05-04 02:23:40 -04:00
cf.code,
cf.reason
)
} else {
tracing::debug!("close received without close frame")
}
2024-07-24 22:06:19 -04:00
let msg = ChatMessage {
text: format!("{0} left.", who.name),
};
tracing::debug!("{}", msg.text);
let _ = tx.send(to_string::<ChatMessage>(&msg).unwrap());
2024-07-22 01:32:09 -04:00
let _ = state.users.lock().unwrap().remove(who);
2024-07-24 22:06:19 -04:00
let _ = tx.send(to_string(&server_sum_update(state)).unwrap());
2024-05-04 02:23:40 -04:00
}
Message::Pong(ping) => {
tracing::debug!("Pong received with: {:?}", ping);
}
Message::Ping(pong) => {
tracing::debug!("Pong received with: {:?}", pong);
}
}
}