81 lines
3.4 KiB
Rust
81 lines
3.4 KiB
Rust
use serde_json::to_string;
|
|
|
|
use crate::api::*;
|
|
use crate::AppState;
|
|
use crate::Arc;
|
|
|
|
pub async fn message_handler(message: Message, state: &Arc<AppState>, addr: SocketAddr) {
|
|
let tx = &state.tx;
|
|
|
|
match message {
|
|
Message::Text(text) => {
|
|
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
|
|
tracing::debug!("New game request received.");
|
|
// create game
|
|
if let Ok(new_game_object) = Game::new(new_game) {
|
|
if let Ok(game_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(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::<ChatMessage>(&text) {
|
|
let msg = format! {"{0}: {1}", state.users.lock().unwrap().get(&addr).unwrap().name, chat_message.text};
|
|
tracing::debug!("{msg}");
|
|
let _res = tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap());
|
|
} else if let Ok(user_log_in) = serde_json::from_str::<UserLogIn>(&text) {
|
|
let old_name = state.users.lock().unwrap().get(&addr).unwrap().name.clone();
|
|
let new_name = user_log_in.username.clone();
|
|
state.users.lock().unwrap().get_mut(&addr).unwrap().change_name(user_log_in.username);
|
|
let msg = format! {
|
|
"{0} changed name to {1}.",
|
|
old_name,
|
|
new_name
|
|
};
|
|
tracing::debug!("{msg}");
|
|
let _res = tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap());
|
|
} 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}",
|
|
state.users.lock().unwrap().get(&addr).unwrap().name,
|
|
cf.code,
|
|
cf.reason
|
|
)
|
|
} else {
|
|
tracing::debug!("close received without close frame")
|
|
}
|
|
let msg = ChatMessage {
|
|
text: format!("{0} left.", state.users.lock().unwrap().get(&addr).unwrap().name),
|
|
};
|
|
tracing::debug!("{}", msg.text);
|
|
let _ = tx.send(to_string::<ChatMessage>(&msg).unwrap());
|
|
state.users.lock().unwrap().remove(&addr).unwrap();
|
|
let _ = tx.send(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);
|
|
}
|
|
}
|
|
}
|