cards/server/src/api/message_handler.rs
2024-07-20 23:00:19 -04:00

86 lines
2.4 KiB
Rust

use crate::api::{greeting, Message, User};
use crate::AppState;
use crate::Arc;
use crate::CAHGame;
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
pub password: Option<String>,
/// Player info
pub player: CAHPlayer,
}
/// Create user/login request structure
pub struct UserLoginRequest {
pub username: String,
pub token: String,
}
pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User) {
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) {
let _ = tx.send(format!("{:#?}", &new_game_object.players[0].white));
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
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);
}
}
}