2024-05-04 02:23:40 -04:00
|
|
|
use crate::api::{greeting, Message, SocketAddr};
|
|
|
|
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
|
|
|
|
pub password: String,
|
|
|
|
/// Player info
|
|
|
|
pub player: CAHPlayer,
|
|
|
|
}
|
|
|
|
|
2024-05-04 02:23:40 -04:00
|
|
|
pub async fn message_handler(message: Message, state: &Arc<AppState>, who: 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);
|
|
|
|
// 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
|
|
|
|
let msg = format! {"{who}: {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 {who} with code: {} and reason: {}",
|
|
|
|
cf.code,
|
|
|
|
cf.reason
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
tracing::debug!("close received without close frame")
|
|
|
|
}
|
|
|
|
let msg = format!("{who} left.");
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|