cards/server/src/api.rs

201 lines
5.8 KiB
Rust
Raw Normal View History

2024-05-03 23:17:39 -04:00
use crate::AppState;
2024-07-30 01:52:03 -04:00
use anyhow::Result;
2024-05-04 02:46:10 -04:00
use axum::{
extract::{
ws::{Message, WebSocket},
ConnectInfo, State, WebSocketUpgrade,
},
response::IntoResponse,
};
2024-07-30 01:52:03 -04:00
use futures::stream::SplitSink;
2024-05-04 02:46:10 -04:00
use futures::{SinkExt, StreamExt};
2024-07-21 02:35:13 -04:00
use lib::models::*;
2024-07-27 23:23:26 -04:00
use rand::seq::SliceRandom;
2024-07-24 22:06:19 -04:00
use serde_json::to_string;
2024-08-02 21:08:42 -04:00
use std::{
net::SocketAddr,
sync::{Arc, RwLock},
};
2024-05-04 02:23:40 -04:00
pub mod message_handler;
use crate::message_handler::*;
2024-04-27 18:22:35 -04:00
2024-08-02 00:41:48 -04:00
/// 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))
2024-07-28 01:38:32 -04:00
}
2024-08-02 00:41:48 -04:00
/// 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();
2024-07-28 02:36:04 -04:00
2024-08-02 00:41:48 -04:00
// Set up new user
handle_new_user(&mut sender, &state, &addr)
.await
.expect("Error creating new user!");
2024-07-28 02:36:04 -04:00
2024-08-02 00:41:48 -04:00
// Subscribe to receive from global broadcast channel
let mut rx = state.tx.subscribe();
2024-07-30 01:52:03 -04:00
2024-08-02 00:41:48 -04:00
// 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;
}
}
});
2024-07-30 01:52:03 -04:00
2024-08-02 00:41:48 -04:00
// 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!")
}
});
2024-07-22 01:32:09 -04:00
2024-08-02 00:41:48 -04:00
// If either task completes then abort the other
tokio::select! {
_ = (&mut send_task) => recv_task.abort(),
_ = (&mut recv_task) => send_task.abort(),
};
2024-07-30 01:52:03 -04:00
}
2024-04-28 04:53:00 -04:00
2024-07-30 01:52:03 -04:00
/// Create, Register, and Hydrate new user
async fn handle_new_user(
sender: &mut SplitSink<WebSocket, Message>,
state: &Arc<AppState>,
addr: &SocketAddr,
) -> Result<()> {
// Create
2024-08-02 21:01:52 -04:00
let new_user = Arc::new(RwLock::new(generate_new_user(state)));
2024-07-30 01:52:03 -04:00
// 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
2024-08-03 00:42:32 -04:00
state.online_users.write().unwrap().insert(*addr, new_user);
2024-07-30 01:52:03 -04:00
// Hydrate client
2024-07-30 21:27:09 -04:00
// this should probably be combined and sent as one
2024-08-02 02:46:07 -04:00
sender.send(Message::Text(chat_meta_update(state))).await?;
2024-07-30 01:52:03 -04:00
sender.send(Message::Text(motd())).await?;
sender
2024-08-02 02:46:07 -04:00
.send(Message::Text(server_summary_update(state)))
2024-07-30 01:52:03 -04:00
.await?;
2024-08-02 02:46:07 -04:00
sender.send(Message::Text(games_update(state))).await?;
2024-08-04 03:13:34 -04:00
sender.send(Message::Text(cards_meta_update(state))).await?;
2024-08-02 00:41:48 -04:00
// Broadcast new user's existence
// this should probably be combined and sent as one
2024-08-02 02:46:07 -04:00
state.tx.send(announce_join(state, addr))?;
state.tx.send(server_summary_update(state))?;
state.tx.send(chat_meta_update(state))?;
2024-07-30 01:52:03 -04:00
Ok(())
}
2024-07-22 01:32:09 -04:00
2024-08-02 00:41:48 -04:00
/// 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(),
),
}
}
2024-07-22 01:32:09 -04:00
2024-08-02 00:41:48 -04:00
/// Generate message to notify client of user changes
2024-08-02 21:01:52 -04:00
fn client_self_user_update(new_user: &Arc<RwLock<User>>) -> String {
2024-08-02 00:41:48 -04:00
to_string::<UserUpdate>(&UserUpdate {
2024-08-02 21:01:52 -04:00
username: new_user.read().unwrap().name.clone(),
2024-08-02 00:41:48 -04:00
})
.unwrap()
}
2024-07-28 01:38:32 -04:00
2024-08-02 00:41:48 -04:00
/// 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![];
2024-05-03 18:48:12 -04:00
2024-08-03 00:42:32 -04:00
for user in state.online_users.read().unwrap().iter() {
2024-08-02 21:01:52 -04:00
names.push(user.1.read().unwrap().name.clone());
2024-08-02 00:41:48 -04:00
}
2024-05-03 23:17:39 -04:00
2024-08-02 00:41:48 -04:00
to_string::<ChatUpdate>(&ChatUpdate {
room: "Lobby".to_string(),
users: names,
})
.unwrap()
}
2024-05-03 23:17:39 -04:00
2024-08-04 03:13:34 -04:00
/// Generage cards meta message
fn cards_meta_update(state: &Arc<AppState>) -> String {
tracing::debug!("sending cards meta");
to_string::<CardPacksMeta>(&state.packs_meta).unwrap()
}
2024-08-02 00:41:48 -04:00
/// Generate message-of-the-day server greeting
fn motd() -> String {
to_string::<ChatMessage>(&ChatMessage {
text: "Greetings from the game server!".to_string(),
})
.unwrap()
2024-04-27 18:22:35 -04:00
}
2024-05-04 02:49:17 -04:00
2024-08-02 00:41:48 -04:00
/// Generate server summary update - mostly debug stuff
fn server_summary_update(state: &Arc<AppState>) -> String {
2024-08-03 00:42:32 -04:00
let online_users = state.online_users.read().unwrap().len();
let active_games = state.games.read().unwrap().len();
2024-08-02 00:41:48 -04:00
to_string::<ServerStateSummary>(&ServerStateSummary {
2024-08-02 02:35:31 -04:00
online_users,
active_games,
2024-08-02 00:41:48 -04:00
})
.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![];
2024-08-03 00:42:32 -04:00
for game in state.games.read().unwrap().iter() {
2024-08-02 02:35:31 -04:00
names.push(format!(
"Name: {} Host: {}",
game.name,
2024-08-02 21:01:52 -04:00
game.host.read().unwrap().name
2024-08-02 02:35:31 -04:00
));
2024-08-02 00:41:48 -04:00
}
to_string::<GamesUpdate>(&GamesUpdate { games: names }).unwrap()
}
/// Generate chatroom join announcement
fn announce_join(state: &Arc<AppState>, addr: &SocketAddr) -> String {
let msg = format!(
"{} joined.",
2024-08-02 02:35:31 -04:00
state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-08-02 02:35:31 -04:00
.unwrap()
.get(addr)
.unwrap()
2024-08-02 21:01:52 -04:00
.read()
2024-08-02 02:35:31 -04:00
.unwrap()
.name
2024-08-02 00:41:48 -04:00
);
tracing::debug!("{}", &msg);
to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap()
2024-05-04 02:49:17 -04:00
}