cards/server/src/api/message_handler.rs

87 lines
2.4 KiB
Rust
Raw Normal View History

2024-07-16 21:11:24 -04:00
use crate::api::{greeting, Message, User};
2024-05-04 02:23:40 -04:00
use crate::AppState;
use crate::Arc;
use crate::CAHGame;
2024-05-04 02:32:49 -04:00
use crate::CAHPlayer;
use serde::Deserialize;
/// New game request structure
#[derive(Debug, Deserialize)]
pub struct NewGameRequest {
/// Game name
pub name: String,
/// Game host
pub host: CAHPlayer,
/// Chosen packs
pub packs: Vec<u8>,
}
/// Game join request structure
pub struct GameJoinRequest {
/// Game id
pub id: u8, // increase later
/// Game password
2024-06-22 02:16:35 -04:00
pub password: Option<String>,
2024-05-04 02:32:49 -04:00
/// Player info
pub player: CAHPlayer,
}
2024-06-22 02:16:35 -04:00
/// Create user/login request structure
pub struct UserLoginRequest {
pub username: String,
pub token: String,
}
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) {
tracing::debug!("{:#?}", &new_game);
// create game
if let Ok(new_game_object) = CAHGame::new(new_game) {
2024-05-04 21:28:42 -04:00
let _ = tx.send(format!("{:#?}", &new_game_object.players[0].white));
2024-05-04 02:23:40 -04:00
state.games.lock().unwrap().push(new_game_object);
let _update = tx.send(greeting(&state));
} else {
let _res = tx.send(format!("error creating game"));
}
} else {
// just echo
2024-07-16 21:11:24 -04:00
let msg = format! {"{0}: {1}", who.name, text};
2024-05-04 02:23:40 -04:00
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!(
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-16 21:11:24 -04:00
let msg = format!("{0} left.", who.name);
2024-05-04 02:23:40 -04:00
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);
}
}
}