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-05-03 23:17:39 -04:00
|
|
|
use std::{net::SocketAddr, sync::Arc};
|
2024-07-21 00:59:21 -04:00
|
|
|
|
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-07-30 01:52:03 -04:00
|
|
|
fn motd() -> String {
|
|
|
|
to_string::<ChatMessage>(&ChatMessage {
|
2024-07-24 22:06:19 -04:00
|
|
|
text: "Greetings from the game server!".to_string(),
|
2024-07-30 01:52:03 -04:00
|
|
|
})
|
|
|
|
.unwrap()
|
2024-05-03 23:17:39 -04:00
|
|
|
}
|
2024-05-04 02:23:40 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
fn server_summary_update(state: &Arc<AppState>) -> String {
|
|
|
|
to_string::<ServerStateSummary>(&ServerStateSummary {
|
2024-07-22 01:32:09 -04:00
|
|
|
online_users: state.users.lock().unwrap().len(),
|
|
|
|
active_games: state.games.lock().unwrap().len(),
|
2024-07-30 01:52:03 -04:00
|
|
|
})
|
|
|
|
.unwrap()
|
2024-07-22 01:32:09 -04:00
|
|
|
}
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
fn chat_update(state: &Arc<AppState>) -> String {
|
2024-07-28 01:38:32 -04:00
|
|
|
let mut names = vec![];
|
|
|
|
|
|
|
|
for user in state.users.lock().unwrap().iter() {
|
|
|
|
names.push(user.1.name.clone());
|
|
|
|
}
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
to_string::<ChatUpdate>(&ChatUpdate {
|
2024-07-28 01:38:32 -04:00
|
|
|
room: "Lobby".to_string(),
|
|
|
|
users: names,
|
2024-07-30 01:52:03 -04:00
|
|
|
})
|
|
|
|
.unwrap()
|
2024-07-28 01:38:32 -04:00
|
|
|
}
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
fn games_update(state: &Arc<AppState>) -> String {
|
2024-07-28 02:36:04 -04:00
|
|
|
let mut names = vec![];
|
|
|
|
|
|
|
|
for game in state.games.lock().unwrap().iter() {
|
|
|
|
names.push(game.name.clone());
|
|
|
|
}
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
to_string::<GamesUpdate>(&GamesUpdate { games: names }).unwrap()
|
2024-07-28 02:36:04 -04:00
|
|
|
}
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
fn announce_join(state: &Arc<AppState>, addr: &SocketAddr) -> String {
|
|
|
|
let msg = format!(
|
|
|
|
"{} joined.",
|
|
|
|
state.users.lock().unwrap().get(addr).unwrap().name
|
|
|
|
);
|
|
|
|
|
|
|
|
tracing::debug!("{}", &msg);
|
|
|
|
|
|
|
|
to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn generate_new_user(state: &Arc<AppState>) -> User {
|
|
|
|
User {
|
2024-07-27 23:23:26 -04:00
|
|
|
name: format!(
|
|
|
|
"{} {}",
|
|
|
|
state.first_names.choose(&mut rand::thread_rng()).unwrap(),
|
|
|
|
state.last_names.choose(&mut rand::thread_rng()).unwrap(),
|
|
|
|
),
|
2024-07-30 01:52:03 -04:00
|
|
|
}
|
|
|
|
}
|
2024-07-22 01:32:09 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
fn client_self_user_update(new_user: &User) -> String {
|
|
|
|
to_string::<UserUpdate>(&UserUpdate {
|
|
|
|
username: new_user.name.clone(),
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
}
|
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
|
|
|
|
let new_user = 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.users.lock().unwrap().insert(*addr, new_user);
|
|
|
|
|
|
|
|
// Hydrate client
|
|
|
|
sender.send(Message::Text(chat_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?;
|
|
|
|
state.tx.send(announce_join(state, addr))?;
|
|
|
|
state.tx.send(server_summary_update(state))?;
|
|
|
|
state.tx.send(chat_update(state))?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-07-22 01:32:09 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
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-22 01:32:09 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
handle_new_user(&mut sender, &state, &addr)
|
|
|
|
.await
|
|
|
|
.expect("Error creating new user!");
|
2024-07-28 01:38:32 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
// Subscribe to global broadcast channel
|
2024-07-22 01:32:09 -04:00
|
|
|
let mut rx = state.tx.subscribe();
|
2024-05-03 18:48:12 -04:00
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
// Submit new messages from this client to broadcast
|
2024-05-03 23:17:39 -04:00
|
|
|
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
|
|
|
// Send messages from broadcast down to this client
|
2024-05-03 23:17:39 -04:00
|
|
|
let mut recv_task = tokio::spawn(async move {
|
|
|
|
while let Some(Ok(message)) = receiver.next().await {
|
2024-07-27 02:51:04 -04:00
|
|
|
message_handler(message, &state, addr).await
|
2024-04-28 04:53:00 -04:00
|
|
|
}
|
2024-05-03 23:17:39 -04:00
|
|
|
});
|
|
|
|
|
2024-07-30 01:52:03 -04:00
|
|
|
// If either task completes then abort the other
|
2024-05-03 23:17:39 -04:00
|
|
|
tokio::select! {
|
|
|
|
_ = (&mut send_task) => recv_task.abort(),
|
|
|
|
_ = (&mut recv_task) => send_task.abort(),
|
|
|
|
};
|
2024-04-27 18:22:35 -04:00
|
|
|
}
|
2024-05-04 02:49:17 -04:00
|
|
|
|
2024-07-22 01:32:09 -04:00
|
|
|
pub async fn websocket_connection_handler(
|
2024-05-04 02:49:17 -04:00
|
|
|
ws: WebSocketUpgrade,
|
|
|
|
// user_agent: Option<TypedHeader<headers::UserAgent>>,
|
|
|
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
|
|
|
State(state): State<Arc<AppState>>,
|
|
|
|
) -> impl IntoResponse {
|
2024-07-27 02:51:04 -04:00
|
|
|
tracing::debug!("New connection from {}", &addr);
|
|
|
|
ws.on_upgrade(move |socket| on_websocket_connection(socket, state, addr))
|
2024-05-04 02:49:17 -04:00
|
|
|
}
|