cards/server/src/websocket.rs

335 lines
9 KiB
Rust
Raw Normal View History

use crate::websocket::meta::*;
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;
use crate::NewUser;
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::{SinkExt, StreamExt};
use lib::*;
2024-07-30 03:22:32 -04:00
use serde_json::{from_str, to_string};
2024-08-06 00:33:37 -04:00
use std::{
net::SocketAddr,
sync::{Arc, RwLock},
};
use tokio::sync::{broadcast::Sender, mpsc};
pub mod meta;
pub mod user;
2024-07-30 03:22:32 -04:00
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();
2024-08-06 02:26:57 -04:00
// Create channel for direct messages
let (dm_tx, mut dm_rx) = mpsc::channel(30);
let _ = state
.users_tx
.send(NewUser {
sender: dm_tx,
addr,
})
.await;
2024-08-05 01:55:05 -04:00
// Subscribe to receive from global broadcast channel
2024-08-07 05:30:30 -04:00
let mut rx = state.broadcast_channel.subscribe();
2024-08-05 01:55:05 -04:00
// Send messages to this client
let mut send_task = tokio::spawn(async move {
2024-08-07 05:30:30 -04:00
let mut broadcast = None;
let mut dm = None;
loop {
2024-08-07 05:30:30 -04:00
tokio::select! {
b = rx.recv() => broadcast = Some(b.unwrap()),
d = dm_rx.recv() => dm = d,
};
if let Some(msg) = &dm {
if sender.send(Message::Text(msg.to_string())).await.is_err() {
break;
2024-08-07 05:30:30 -04:00
} else {
dm = Option::None;
}
2024-08-07 05:30:30 -04:00
} else if let Some(msg) = &broadcast {
if sender.send(Message::Text(msg.to_string())).await.is_err() {
} else {
broadcast = Option::None;
}
2024-08-05 01:55:05 -04:00
}
}
});
// 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(),
};
}
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<()> {
2024-08-07 05:30:30 -04:00
let tx = &state.broadcast_channel;
2024-08-02 00:41:48 -04:00
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-06 00:33:37 -04:00
state
.games
.write()
.unwrap()
.insert(new_game_object.name.clone(), RwLock::new(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
}