cards/server/src/websocket.rs

348 lines
9.5 KiB
Rust
Raw Normal View History

2024-08-05 01:55:05 -04:00
use crate::meta::*;
use crate::user::*;
2024-05-04 02:23:40 -04:00
use crate::AppState;
2024-08-05 01:55:05 -04:00
use crate::Game;
use crate::NewGameManifest;
2024-07-30 03:22:32 -04:00
use anyhow::Result;
2024-07-30 22:40:34 -04:00
use axum::extract::ws::CloseFrame;
2024-08-05 01:55:05 -04:00
use axum::{
extract::{
ws::{Message, WebSocket},
ConnectInfo, State, WebSocketUpgrade,
},
response::IntoResponse,
};
use futures::stream::SplitSink;
use futures::{SinkExt, StreamExt};
use lib::*;
2024-07-30 03:22:32 -04:00
use serde_json::{from_str, to_string};
2024-08-05 01:55:05 -04:00
use std::{
net::SocketAddr,
sync::{Arc, RwLock},
};
2024-07-30 03:22:32 -04:00
use tokio::sync::broadcast::Sender;
2024-08-05 01:55:05 -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| websocket_on_connection(socket, state, addr))
}
/// This runs right after a WebSocket connection is established
pub async fn websocket_on_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
user_handle_new(&mut sender, &state, &addr)
.await
.expect("Error creating new user!");
// Subscribe to receive from global broadcast channel
let mut rx = state.tx.subscribe();
// Send messages to this client
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;
}
}
});
// Receive messages from this client
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(message)) = receiver.next().await {
websocket_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
pub async fn user_handle_new(
sender: &mut SplitSink<WebSocket, Message>,
state: &Arc<AppState>,
addr: &SocketAddr,
) -> Result<()> {
// Create
let new_user = Arc::new(RwLock::new(User::new(state)));
// Notify client of new username
sender
.send(Message::Text(user_client_self_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(meta_chat_update(state))).await?;
sender.send(Message::Text(meta_motd())).await?;
sender
.send(Message::Text(meta_server_summary_update(state)))
.await?;
sender
.send(Message::Text(meta_games_browser_update(state)))
.await?;
sender
.send(Message::Text(meta_new_game_card_packs(state)))
.await?;
// Broadcast new user's existence
// this should probably be combined and sent as one
state.tx.send(meta_announce_user_join(state, addr))?;
state.tx.send(meta_server_summary_update(state))?;
state.tx.send(meta_chat_update(state))?;
Ok(())
}
2024-08-02 00:41:48 -04:00
/// Handle incoming messages over the WebSocket
2024-08-05 01:55:05 -04:00
pub async fn websocket_message_handler(
2024-08-02 00:41:48 -04:00
state: Arc<AppState>,
addr: SocketAddr,
message: Message,
) -> Result<()> {
let tx = &state.tx;
match message {
Message::Text(text) => match text {
_new_game if let Ok(_new_game) = from_str::<NewGameRequest>(&text) => {
tracing::debug!("New game request received.");
2024-08-05 01:55:05 -04:00
game_handle_new_game(_new_game, &state, tx, addr)?;
2024-08-02 00:41:48 -04:00
}
_chat_message if let Ok(_chat_message) = from_str::<ChatMessage>(&text) => {
2024-08-05 01:55:05 -04:00
websocket_handle_chat_message(_chat_message, &state, tx, addr)?;
2024-08-02 00:41:48 -04:00
}
_user_log_in if let Ok(_user_log_in) = from_str::<UserLogIn>(&text) => {
2024-08-05 01:55:05 -04:00
websocket_handle_user_log_in(_user_log_in, &state, tx, addr)?;
2024-08-02 00:41:48 -04:00
}
_ => {
tracing::debug!("Unhandled text message: {}", &text);
}
},
Message::Binary(data) => {
tracing::debug!("Binary: {:?}", data)
}
Message::Close(close_frame) => {
2024-08-05 01:55:05 -04:00
websocket_handle_close(close_frame, &state, tx, addr)?;
2024-08-02 00:41:48 -04:00
}
Message::Pong(ping) => {
tracing::debug!("Pong received with: {:?}", ping);
}
Message::Ping(pong) => {
tracing::debug!("Pong received with: {:?}", pong);
}
}
Ok(())
}
2024-07-30 03:29:20 -04:00
/// This runs when a NewGameRequest is received
2024-08-05 01:55:05 -04:00
fn game_handle_new_game(
2024-07-30 03:22:32 -04:00
new_game: NewGameRequest,
state: &Arc<AppState>,
tx: &Sender<String>,
2024-08-01 23:47:28 -04:00
addr: SocketAddr,
2024-07-30 03:22:32 -04:00
) -> Result<()> {
2024-08-01 23:47:28 -04:00
let manifest = NewGameManifest {
name: new_game.name,
2024-08-02 02:35:31 -04:00
host: state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-08-02 02:35:31 -04:00
.unwrap()
.get(&addr)
.unwrap()
.clone(),
2024-08-01 23:47:28 -04:00
};
2024-08-04 03:13:34 -04:00
tracing::debug!("Game Packs {:?}", new_game.packs);
2024-08-01 23:47:28 -04:00
// create game
2024-08-02 02:35:31 -04:00
if let Ok(new_game_object) = Game::new(manifest) {
2024-08-03 00:42:32 -04:00
state.games.write().unwrap().push(new_game_object);
2024-08-05 01:55:05 -04:00
tx.send(meta_games_browser_update(state))?;
tx.send(meta_server_summary_update(state))?;
2024-08-02 02:35:31 -04:00
}
2024-07-30 03:22:32 -04:00
Ok(())
}
2024-07-30 03:29:20 -04:00
/// This runs when a ChatMessage is received
2024-08-05 01:55:05 -04:00
fn websocket_handle_chat_message(
2024-07-30 03:22:32 -04:00
chat_message: ChatMessage,
state: &Arc<AppState>,
tx: &Sender<String>,
addr: SocketAddr,
) -> Result<()> {
2024-08-03 00:42:32 -04:00
let msg = format! {"{0}: {1}", state.online_users.read().unwrap().get(&addr).unwrap().read().unwrap().name, chat_message.text};
2024-07-30 03:22:32 -04:00
tracing::debug!("{msg}");
tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg })?)?;
Ok(())
}
2024-06-22 02:16:35 -04:00
2024-07-30 03:29:20 -04:00
/// This runs when a UserLogIn is received
2024-08-05 01:55:05 -04:00
fn websocket_handle_user_log_in(
2024-07-30 03:22:32 -04:00
user_log_in: UserLogIn,
state: &Arc<AppState>,
tx: &Sender<String>,
addr: SocketAddr,
) -> Result<()> {
2024-07-31 21:19:29 -04:00
let old_name = state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-07-30 03:22:32 -04:00
.unwrap()
2024-07-31 21:19:29 -04:00
.get(&addr)
2024-07-30 03:22:32 -04:00
.unwrap()
2024-08-02 21:01:52 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
2024-07-31 21:19:29 -04:00
.name
.clone();
let new_name = user_log_in.username.clone();
2024-07-30 22:40:34 -04:00
2024-08-03 00:42:32 -04:00
if state.offline_users.read().unwrap().contains_key(&new_name) {
2024-07-31 21:19:29 -04:00
state
.online_users
2024-08-03 00:42:32 -04:00
.write()
2024-07-31 21:19:29 -04:00
.unwrap()
.insert(
addr,
state
.offline_users
2024-08-03 00:42:32 -04:00
.write()
2024-07-31 21:19:29 -04:00
.unwrap()
.remove(&new_name)
.unwrap(),
)
.unwrap();
let msg = format! {
"{0} changed name to {1}. Welcome back!",
old_name,
new_name
};
tracing::debug!("{msg}");
2024-08-05 00:08:29 -04:00
} else if state.reserved_names.read().unwrap().contains(&new_name) {
tracing::debug!("name is taken");
2024-07-31 21:19:29 -04:00
} else {
state
.online_users
2024-08-03 00:42:32 -04:00
.write()
2024-07-31 21:19:29 -04:00
.unwrap()
.get_mut(&addr)
.unwrap()
2024-08-02 21:01:52 -04:00
.write()
2024-08-02 01:20:54 -04:00
.unwrap()
2024-07-31 21:19:29 -04:00
.change_name(user_log_in.username);
let msg = format! {
"{0} changed name to {1}.",
old_name,
new_name
};
2024-08-05 00:08:29 -04:00
// Reserve name
state
.reserved_names
.write()
.unwrap()
.insert(new_name.clone());
2024-07-31 21:19:29 -04:00
tracing::debug!("{msg}");
tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg })?)?;
2024-08-05 00:08:29 -04:00
tracing::debug!("Name {} reserved.", &new_name);
2024-07-31 21:19:29 -04:00
}
2024-07-30 22:40:34 -04:00
2024-07-31 21:19:29 -04:00
tracing::debug!(
"Online Users: {} Offline Users: {}",
2024-08-03 00:42:32 -04:00
state.online_users.read().unwrap().len(),
state.offline_users.read().unwrap().len()
2024-07-31 21:19:29 -04:00
);
2024-08-05 01:55:05 -04:00
tx.send(meta_games_browser_update(state))?;
tx.send(meta_chat_update(state))?;
2024-08-05 00:08:29 -04:00
// send the user their new name
2024-07-30 03:22:32 -04:00
Ok(())
}
2024-07-30 22:40:34 -04:00
/// This runs when a connection closes
2024-08-05 01:55:05 -04:00
fn websocket_handle_close(
2024-07-30 22:40:34 -04:00
close_frame: Option<CloseFrame>,
state: &Arc<AppState>,
tx: &Sender<String>,
addr: SocketAddr,
) -> Result<()> {
if let Some(cf) = close_frame {
tracing::debug!(
"Close received from {0} with code: {1} and reason: {2}",
2024-08-02 01:20:54 -04:00
state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
.get(&addr)
.unwrap()
2024-08-02 21:01:52 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
.name,
2024-07-30 22:40:34 -04:00
cf.code,
cf.reason
)
} else {
tracing::debug!("close received without close frame")
}
let msg = ChatMessage {
text: format!(
"{0} left.",
2024-08-02 01:20:54 -04:00
state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
.get(&addr)
.unwrap()
2024-08-02 21:01:52 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
.name
2024-07-30 22:40:34 -04:00
),
};
tracing::debug!("{}", msg.text);
tx.send(to_string::<ChatMessage>(&msg)?)?;
2024-07-31 21:19:29 -04:00
let name = state
.online_users
2024-08-03 00:42:32 -04:00
.read()
2024-07-31 21:19:29 -04:00
.unwrap()
.get(&addr)
.unwrap()
2024-08-02 21:01:52 -04:00
.read()
2024-08-02 01:20:54 -04:00
.unwrap()
2024-07-31 21:19:29 -04:00
.name
.clone();
2024-08-03 00:42:32 -04:00
state.offline_users.write().unwrap().insert(
2024-07-31 21:19:29 -04:00
name.clone(),
2024-08-03 00:42:32 -04:00
state.online_users.write().unwrap().remove(&addr).unwrap(),
2024-07-31 21:19:29 -04:00
);
2024-08-05 01:55:05 -04:00
tx.send(meta_server_summary_update(state))?;
tx.send(meta_chat_update(state))?;
2024-07-30 22:40:34 -04:00
2024-07-30 03:22:32 -04:00
Ok(())
2024-05-04 02:23:40 -04:00
}