cards/src/api.rs

93 lines
2.7 KiB
Rust
Raw Normal View History

2024-04-30 02:28:43 -04:00
use crate::AppState;
2024-05-01 04:56:58 -04:00
use crate::CAHd_game::*;
2024-04-28 04:53:00 -04:00
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
State,
2024-04-27 18:22:35 -04:00
},
2024-04-28 04:53:00 -04:00
response::IntoResponse,
2024-04-27 18:22:35 -04:00
};
2024-04-28 04:53:00 -04:00
use futures::{sink::SinkExt, stream::StreamExt};
2024-05-03 18:48:12 -04:00
use serde::Deserialize;
2024-04-30 02:28:43 -04:00
use std::sync::Arc;
2024-04-27 18:22:35 -04:00
2024-05-03 18:48:12 -04:00
/// 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-04-28 04:53:00 -04:00
pub async fn websocket_handler(
ws: WebSocketUpgrade,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| websocket(socket, state))
}
2024-04-27 18:22:35 -04:00
2024-04-28 04:53:00 -04:00
pub async fn websocket(stream: WebSocket, state: Arc<AppState>) {
// By splitting, we can send and receive at the same time.
let (mut sender, mut receiver) = stream.split();
2024-05-03 18:48:12 -04:00
let _greeting = sender
.send(Message::Text(format!(
"Greetings! \n\
{:#?} Card packs loaded\n\
{:#?} Current active games",
state.all_cards.lock().unwrap().len(),
state.games.lock().unwrap().len(),
)))
.await;
2024-04-28 04:53:00 -04:00
// Loop until a text message is found.
while let Some(Ok(message)) = receiver.next().await {
2024-05-01 04:56:58 -04:00
match message {
Message::Text(text) => {
tracing::debug!("Text: {}", text);
2024-05-03 19:03:24 -04:00
2024-05-02 00:39:34 -04:00
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
2024-05-03 19:13:00 -04:00
tracing::debug!("{:#?}", &new_game);
state.games.lock().unwrap().push(CAHGame::new(new_game).expect("error creating game"));
2024-05-02 00:39:34 -04:00
} else {
2024-05-03 19:03:24 -04:00
// just echo
let _res = sender.send(Message::Text(text)).await;
2024-05-02 00:39:34 -04:00
}
2024-05-01 04:56:58 -04:00
}
Message::Binary(data) => {
tracing::debug!("Binary: {:?}", data)
}
Message::Close(c) => {
if let Some(cf) = c {
tracing::debug!(
"Close received with code: {} and reason: {}",
cf.code,
cf.reason
)
} else {
2024-05-03 18:48:12 -04:00
tracing::debug!("close received without close frame")
2024-05-01 04:56:58 -04:00
}
}
Message::Pong(ping) => {
2024-05-03 18:48:12 -04:00
tracing::debug!("Pong received with: {:?}", ping);
2024-05-01 04:56:58 -04:00
}
Message::Ping(pong) => {
2024-05-03 18:48:12 -04:00
tracing::debug!("Pong received with: {:?}", pong);
2024-04-28 04:53:00 -04:00
}
}
}
2024-04-27 18:22:35 -04:00
}