cards/server/src/api.rs
2024-08-04 03:13:34 -04:00

200 lines
5.8 KiB
Rust

use crate::AppState;
use anyhow::Result;
use axum::{
extract::{
ws::{Message, WebSocket},
ConnectInfo, State, WebSocketUpgrade,
},
response::IntoResponse,
};
use futures::stream::SplitSink;
use futures::{SinkExt, StreamExt};
use lib::models::*;
use rand::seq::SliceRandom;
use serde_json::to_string;
use std::{
net::SocketAddr,
sync::{Arc, RwLock},
};
pub mod message_handler;
use crate::message_handler::*;
/// Establish the WebSocket connection
pub async fn websocket_connection_handler(
ws: WebSocketUpgrade,
// user_agent: Option<TypedHeader<headers::UserAgent>>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
tracing::debug!("New connection from {}", &addr);
ws.on_upgrade(move |socket| on_websocket_connection(socket, state, addr))
}
/// This runs right after a WebSocket connection is established
pub async fn on_websocket_connection(stream: WebSocket, state: Arc<AppState>, addr: SocketAddr) {
// Split channels to send and receive asynchronously.
let (mut sender, mut receiver) = stream.split();
// Set up new user
handle_new_user(&mut sender, &state, &addr)
.await
.expect("Error creating new user!");
// Subscribe to receive from global broadcast channel
let mut rx = state.tx.subscribe();
// Submit new messages from this client to broadcast
let mut send_task = tokio::spawn(async move {
while let Ok(msg) = rx.recv().await {
if sender.send(Message::Text(msg)).await.is_err() {
break;
}
}
});
// Pass messages from broadcast down to this client
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(message)) = receiver.next().await {
message_handler(state.clone(), addr, message)
.await
.expect("Message Handler exploded!")
}
});
// If either task completes then abort the other
tokio::select! {
_ = (&mut send_task) => recv_task.abort(),
_ = (&mut recv_task) => send_task.abort(),
};
}
/// Create, Register, and Hydrate new user
async fn handle_new_user(
sender: &mut SplitSink<WebSocket, Message>,
state: &Arc<AppState>,
addr: &SocketAddr,
) -> Result<()> {
// Create
let new_user = Arc::new(RwLock::new(generate_new_user(state)));
// Notify client of new username
sender
.send(Message::Text(client_self_user_update(&new_user)))
.await?;
// Register using `addr` as key until something longer lived exists
state.online_users.write().unwrap().insert(*addr, new_user);
// Hydrate client
// this should probably be combined and sent as one
sender.send(Message::Text(chat_meta_update(state))).await?;
sender.send(Message::Text(motd())).await?;
sender
.send(Message::Text(server_summary_update(state)))
.await?;
sender.send(Message::Text(games_update(state))).await?;
sender.send(Message::Text(cards_meta_update(state))).await?;
// Broadcast new user's existence
// this should probably be combined and sent as one
state.tx.send(announce_join(state, addr))?;
state.tx.send(server_summary_update(state))?;
state.tx.send(chat_meta_update(state))?;
Ok(())
}
/// Create a new user object from incoming data
fn generate_new_user(state: &Arc<AppState>) -> User {
User {
name: format!(
"{} {}",
state.first_names.choose(&mut rand::thread_rng()).unwrap(),
state.last_names.choose(&mut rand::thread_rng()).unwrap(),
),
}
}
/// Generate message to notify client of user changes
fn client_self_user_update(new_user: &Arc<RwLock<User>>) -> String {
to_string::<UserUpdate>(&UserUpdate {
username: new_user.read().unwrap().name.clone(),
})
.unwrap()
}
/// Generate chatroom metadata update
fn chat_meta_update(state: &Arc<AppState>) -> String {
// this may get expensive if there are many users
let mut names = vec![];
for user in state.online_users.read().unwrap().iter() {
names.push(user.1.read().unwrap().name.clone());
}
to_string::<ChatUpdate>(&ChatUpdate {
room: "Lobby".to_string(),
users: names,
})
.unwrap()
}
/// Generage cards meta message
fn cards_meta_update(state: &Arc<AppState>) -> String {
tracing::debug!("sending cards meta");
to_string::<CardPacksMeta>(&state.packs_meta).unwrap()
}
/// Generate message-of-the-day server greeting
fn motd() -> String {
to_string::<ChatMessage>(&ChatMessage {
text: "Greetings from the game server!".to_string(),
})
.unwrap()
}
/// Generate server summary update - mostly debug stuff
fn server_summary_update(state: &Arc<AppState>) -> String {
let online_users = state.online_users.read().unwrap().len();
let active_games = state.games.read().unwrap().len();
to_string::<ServerStateSummary>(&ServerStateSummary {
online_users,
active_games,
})
.unwrap()
}
/// Generate games list update
fn games_update(state: &Arc<AppState>) -> String {
// this may get expensive if there are many games
let mut names = vec![];
for game in state.games.read().unwrap().iter() {
names.push(format!(
"Name: {} Host: {}",
game.name,
game.host.read().unwrap().name
));
}
to_string::<GamesUpdate>(&GamesUpdate { games: names }).unwrap()
}
/// Generate chatroom join announcement
fn announce_join(state: &Arc<AppState>, addr: &SocketAddr) -> String {
let msg = format!(
"{} joined.",
state
.online_users
.read()
.unwrap()
.get(addr)
.unwrap()
.read()
.unwrap()
.name
);
tracing::debug!("{}", &msg);
to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap()
}