proper chat and message handling

This commit is contained in:
Adam 2024-07-24 22:06:19 -04:00
parent 0679e8b672
commit bd029be93c
5 changed files with 74 additions and 57 deletions

View file

@ -7,6 +7,7 @@ use lib::models::*;
#[component] #[component]
pub fn Chat() -> impl IntoView { pub fn Chat() -> impl IntoView {
let websocket = expect_context::<WebSocketContext>(); let websocket = expect_context::<WebSocketContext>();
let chat_context = expect_context::<ReadSignal<Option<ChatMessage>>>();
// Chat stuff // Chat stuff
let (chat_history, set_chat_history) = create_signal::<Vec<String>>(vec![]); let (chat_history, set_chat_history) = create_signal::<Vec<String>>(vec![]);
@ -38,34 +39,23 @@ pub fn Chat() -> impl IntoView {
}) })
}); });
// let chat = move || { // Handle incoming chat messages
// if let Some(ye) = chat_input_ref.get() {
// &websocket.send(&ye.value());
// };
// };
// This should be done elsewhere
create_effect(move |_| { create_effect(move |_| {
websocket.message.with(move |message_raw| { chat_context.with(move |chat_message| {
// Send all messages as strings into chat box if let Some(message) = chat_message {
if let Some(message) = message_raw { update_chat_history(&set_chat_history, format!("{}\n", message.text));
if let Ok(_game) = serde_json::from_str::<Game>(message) {
logging::log!("Game object received at chat component");
} else if let Ok(_state_summary) =
serde_json::from_str::<ServerStateSummary>(message)
{
logging::log!("State Summary received at chat component");
} else {
update_chat_history(&set_chat_history, format!("{}\n", message));
}
} }
}) })
}); });
// Handle sending messages
let send_message = move |_| { let send_message = move |_| {
websocket.send(&serde_json::to_string(&ChatMessage { websocket.send(
text: chat_input_ref.get().unwrap().value(), &serde_json::to_string(&ChatMessage {
}).unwrap()); text: chat_input_ref.get().unwrap().value(),
})
.unwrap(),
);
chat_input_ref.get().unwrap().set_value(""); chat_input_ref.get().unwrap().set_value("");
logging::log!("Send Message"); logging::log!("Send Message");
}; };

View file

@ -8,19 +8,19 @@ use serde_json::to_string;
#[derive(Clone)] #[derive(Clone)]
pub struct WebSocketContext { pub struct WebSocketContext {
pub ready_state: Signal<ConnectionReadyState>, pub ready_state: Signal<ConnectionReadyState>,
pub message: Signal<Option<String>>, // pub message: Signal<Option<String>>,
send: Rc<dyn Fn(&str)>, send: Rc<dyn Fn(&str)>,
} }
impl WebSocketContext { impl WebSocketContext {
pub fn new( pub fn new(
ready_state: Signal<ConnectionReadyState>, ready_state: Signal<ConnectionReadyState>,
message: Signal<Option<String>>, // message: Signal<Option<String>>,
send: Rc<dyn Fn(&str)>, send: Rc<dyn Fn(&str)>,
) -> Self { ) -> Self {
Self { Self {
ready_state, ready_state,
message, // message,
send, send,
} }
} }
@ -44,7 +44,7 @@ pub fn Websocket() -> impl IntoView {
provide_context(WebSocketContext::new( provide_context(WebSocketContext::new(
ready_state, ready_state,
message, // message,
Rc::new(send.clone()), Rc::new(send.clone()),
)); ));
@ -58,6 +58,7 @@ pub fn Websocket() -> impl IntoView {
let open_connection = move |_| { let open_connection = move |_| {
open(); open();
}; };
let fake_new_game_request = NewGameRequest { let fake_new_game_request = NewGameRequest {
name: String::from("Ligma"), name: String::from("Ligma"),
host: Player { host: Player {
@ -80,34 +81,47 @@ pub fn Websocket() -> impl IntoView {
send(&to_string(&fake_new_game_request).unwrap()); send(&to_string(&fake_new_game_request).unwrap());
}; };
// handle incoming messages // Contexts for message handler
let (state_summary, set_state_summary) =
create_signal::<Option<ServerStateSummary>>(Option::None);
let (game_object, set_game_object) = create_signal::<Option<Game>>(Option::None);
let (chat_message, set_chat_message) = create_signal::<Option<ChatMessage>>(Option::None);
// make this a proper message handler provide_context::<ReadSignal<Option<Game>>>(game_object);
provide_context::<ReadSignal<Option<ChatMessage>>>(chat_message);
provide_context::<ReadSignal<Option<ServerStateSummary>>>(state_summary);
// Message handler
create_effect(move |_| { create_effect(move |_| {
message.with(move |message_raw| { message.with(move |message_raw| {
// Send all messages as strings into chat box // Send all messages as strings into chat box
if let Some(message) = message_raw { if let Some(message) = message_raw {
if let Ok(_game) = serde_json::from_str::<Game>(message) { if let Ok(game) = serde_json::from_str::<Game>(message) {
logging::log!("Game object received."); set_game_object(Some(game));
} else if let Ok(state_summary) = } else if let Ok(state_summary) =
serde_json::from_str::<ServerStateSummary>(message) serde_json::from_str::<ServerStateSummary>(message)
{ {
logging::log!( set_state_summary(Some(state_summary));
"Users: {}\nGames: {}", } else if let Ok(chat_message) = serde_json::from_str::<ChatMessage>(message) {
state_summary.online_users, set_chat_message(Some(chat_message));
state_summary.active_games
);
set_online_users(state_summary.online_users);
set_active_games(state_summary.active_games);
} else { } else {
logging::log!("Send {} to Chat component", message); logging::log!("Unhandled message: {}", message);
// update_chat_history(&set_chat_history, format!("{}\n", message));
} }
} }
}) })
}); });
// Update server info -> move this to a new component
create_effect(move |_| {
state_summary.with(move |state_summary| {
if let Some(state_summary) = state_summary {
set_online_users(state_summary.online_users);
set_active_games(state_summary.active_games);
}
})
});
view! { view! {
<div class="w-auto"> <div class="w-auto">
<hr/> <hr/>

View file

@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use std::net::SocketAddr; use std::net::SocketAddr;
/// Chat message /// Chat message
#[derive(Serialize, Deserialize, Debug)] #[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ChatMessage { pub struct ChatMessage {
pub text: String, pub text: String,
} }

View file

@ -8,15 +8,16 @@ use axum::{
}; };
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
use lib::models::*; use lib::models::*;
use serde_json::to_string;
use std::{net::SocketAddr, sync::Arc}; use std::{net::SocketAddr, sync::Arc};
pub mod message_handler; pub mod message_handler;
use crate::message_handler::*; use crate::message_handler::*;
fn motd() -> String { fn motd() -> ChatMessage {
format!( ChatMessage {
"Greetings from the game server!" text: "Greetings from the game server!".to_string(),
) }
} }
fn server_sum_update(state: &Arc<AppState>) -> ServerStateSummary { fn server_sum_update(state: &Arc<AppState>) -> ServerStateSummary {
@ -36,18 +37,26 @@ pub async fn on_websocket_connection(stream: WebSocket, state: Arc<AppState>, wh
let (mut sender, mut receiver) = stream.split(); let (mut sender, mut receiver) = stream.split();
// hydrate user // hydrate user
let _ = &sender.send(Message::Text(motd())).await; let _ = &sender
let _ = &sender.send(Message::Text(serde_json::to_string(&server_sum_update(&state)).unwrap())).await; .send(Message::Text(to_string::<ChatMessage>(&motd()).unwrap()))
.await;
let _ = &sender
.send(Message::Text(
to_string(&server_sum_update(&state)).unwrap(),
))
.await;
// ANNOUNCE THY PRESENCE // ANNOUNCE THY PRESENCE
let msg = format!("{} joined.", who.name); let msg = ChatMessage {
tracing::debug!("{msg}"); text: format!("{} joined.", who.name),
let _ = &state.tx.send(msg); };
tracing::debug!("{}", msg.text);
let _ = &state.tx.send(to_string::<ChatMessage>(&msg).unwrap());
// Broadcast server state summary update // Broadcast server state summary update
let _ = &state let _ = &state
.tx .tx
.send(serde_json::to_string(&server_sum_update(&state)).unwrap()); .send(to_string(&server_sum_update(&state)).unwrap());
// subscribe to broadcast channel // subscribe to broadcast channel
let mut rx = state.tx.subscribe(); let mut rx = state.tx.subscribe();

View file

@ -1,3 +1,5 @@
use serde_json::to_string;
use crate::api::*; use crate::api::*;
use crate::AppState; use crate::AppState;
use crate::Arc; use crate::Arc;
@ -11,7 +13,7 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
tracing::debug!("New game request received."); tracing::debug!("New game request received.");
// create game // create game
if let Ok(new_game_object) = Game::new(new_game) { if let Ok(new_game_object) = Game::new(new_game) {
if let Ok(game_json) = serde_json::to_string(&new_game_object) { if let Ok(game_json) = to_string(&new_game_object) {
tracing::debug!("Sent new game JSON."); tracing::debug!("Sent new game JSON.");
// this is a broadcast // this is a broadcast
let _ = tx.send(game_json); let _ = tx.send(game_json);
@ -19,7 +21,7 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
tracing::error!("Failed to convert Game object to JSON.") tracing::error!("Failed to convert Game object to JSON.")
} }
state.games.lock().unwrap().push(new_game_object); state.games.lock().unwrap().push(new_game_object);
let _ = tx.send(serde_json::to_string(&server_sum_update(state)).unwrap()); let _ = tx.send(to_string(&server_sum_update(state)).unwrap());
// let _update = tx.send(motd()); // let _update = tx.send(motd());
} else { } else {
let _res = tx.send(String::from("error creating game")); let _res = tx.send(String::from("error creating game"));
@ -27,7 +29,7 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
} else if let Ok(chat_message) = serde_json::from_str::<ChatMessage>(&text) { } else if let Ok(chat_message) = serde_json::from_str::<ChatMessage>(&text) {
let msg = format! {"{0}: {1}", who.name, chat_message.text}; let msg = format! {"{0}: {1}", who.name, chat_message.text};
tracing::debug!("{msg}"); tracing::debug!("{msg}");
let _res = tx.send(msg); let _res = tx.send(to_string::<ChatMessage>(&ChatMessage { text: msg }).unwrap());
} else { } else {
tracing::debug!("Unhandled message: {}", &text); tracing::debug!("Unhandled message: {}", &text);
} }
@ -48,11 +50,13 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
} else { } else {
tracing::debug!("close received without close frame") tracing::debug!("close received without close frame")
} }
let msg = format!("{0} left.", who.name); let msg = ChatMessage {
tracing::debug!("{msg}"); text: format!("{0} left.", who.name),
let _ = tx.send(msg); };
tracing::debug!("{}", msg.text);
let _ = tx.send(to_string::<ChatMessage>(&msg).unwrap());
let _ = state.users.lock().unwrap().remove(who); let _ = state.users.lock().unwrap().remove(who);
let _ = tx.send(serde_json::to_string(&server_sum_update(state)).unwrap()); let _ = tx.send(to_string(&server_sum_update(state)).unwrap());
} }
Message::Pong(ping) => { Message::Pong(ping) => {