From e78d6ddf996156b9b2f5788cd827be93c3203b79 Mon Sep 17 00:00:00 2001 From: Michael Zhang Date: Tue, 9 May 2023 15:19:19 -0500 Subject: [PATCH] Chat ...kinda works? --- client/src-tauri/src/main.rs | 57 +++++++++++++++++++-------- client/src/App.tsx | 3 +- client/src/components/CenterPanel.tsx | 29 ++++++++++++-- client/src/store/messages.ts | 2 +- proto/chat.proto | 2 +- server/src/main.rs | 11 +++++- server/src/mux.rs | 17 +++++++- 7 files changed, 94 insertions(+), 27 deletions(-) diff --git a/client/src-tauri/src/main.rs b/client/src-tauri/src/main.rs index 91198a3..79cc383 100644 --- a/client/src-tauri/src/main.rs +++ b/client/src-tauri/src/main.rs @@ -1,15 +1,16 @@ // Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] -use std::sync::Arc; +use std::{sync::Arc, thread}; use anyhow::Result; use mraow_common::chat_proto::{ - chat_client::ChatClient, ChatMessage, ReceiveMsgsRequest, + chat_client::ChatClient, ChatMessage, ReceiveMsgsRequest, RoomAction, }; +use serde_json::json; use tauri::{ async_runtime::{Mutex, TokioHandle}, - State, + Manager, State, }; use tonic::{transport::channel::Channel, IntoRequest}; use uuid::Uuid; @@ -29,11 +30,18 @@ async fn send_message( let mut client = state.lock().await; let user_id = user_id.inner(); - client.send_msg(ChatMessage { - from_user_id: user_id.0.to_string(), - content: message, - ..Default::default() - }).await.unwrap(); + let resp = client + .send_msg(ChatMessage { + from_user_id: user_id.0.to_string(), + to_room_id: "general".to_string(), + content: message, + ..Default::default() + }) + .await + .unwrap(); + + println!("Sent message to server. {resp:?}"); + /* client .say_hello(HelloRequest { message, @@ -57,20 +65,35 @@ async fn main() -> Result<()> { tauri::Builder::default() .setup(move |app| { + let main_window = app.get_window("main").unwrap(); + tokio::spawn(async move { - let stream = { - let mut client = chat_client2.lock().await; - client - .receive_msgs(ReceiveMsgsRequest { - user_id: uuid.to_string(), - }) - .await - .unwrap() - }; + let mut client = chat_client2.lock().await; + client + .room_action(RoomAction { + room_id: "general".to_string(), + user_id: uuid.to_string(), + action: "join".to_string(), + }) + .await + .unwrap(); + + let stream = client + .receive_msgs(ReceiveMsgsRequest { + user_id: uuid.to_string(), + }) + .await + .unwrap(); + + std::mem::drop(client); let mut stream = stream.into_inner(); while let Ok(Some(message)) = stream.message().await { println!("SHIET message {message:?}"); + + main_window + .emit_all("new-message", json!({ "content" : message.content })) + .unwrap(); } }); diff --git a/client/src/App.tsx b/client/src/App.tsx index 2ca2e7f..d862b71 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,6 +1,5 @@ import { Provider } from "react-redux"; -import { store } from "./store"; -import { useState } from "react"; +import { store, useAppDispatch } from "./store"; import styles from "./App.module.scss"; import LeftSidebar from "./components/LeftSidebar"; diff --git a/client/src/components/CenterPanel.tsx b/client/src/components/CenterPanel.tsx index 02e8a51..a788f3e 100644 --- a/client/src/components/CenterPanel.tsx +++ b/client/src/components/CenterPanel.tsx @@ -1,9 +1,11 @@ import { invoke } from "@tauri-apps/api/tauri"; import styles from "./CenterPanel.module.scss"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useAppDispatch, useAppSelector } from "../store"; import { messageSelectors, messageSlice } from "../store/messages"; import { v4 as uuidv4 } from "uuid"; +import { emit, listen } from "@tauri-apps/api/event"; +import { appWindow, WebviewWindow } from "@tauri-apps/api/window"; export default function CenterPanel() { const [currentMessage, setCurrentMessage] = useState(""); @@ -12,12 +14,32 @@ export default function CenterPanel() { messageSelectors.selectAll(state) ); + useEffect(() => { + let unlisten; + + (async () => { + unlisten = await appWindow.listen("new-message", (event) => { + console.log("NEW EVENT", event); + const id = "lol"; + const time = Date.now(); + const content = event.payload.content; + dispatch(messageSlice.actions.addMessage({ id, time, content })); + }); + + console.log("Listen handler active."); + })(); + + return () => { + if (unlisten) unlisten(); + }; + }); + const onSubmit = (e) => { e.preventDefault(); invoke("send_message", { message: currentMessage }); const id = uuidv4(); - const time = new Date(); + const time = Date.now(); dispatch( messageSlice.actions.addMessage({ id, time, content: currentMessage }) ); @@ -31,7 +53,8 @@ export default function CenterPanel() {
{allMessages.map((msg) => (
- {msg.time.toISOString()} + {new Date(msg.time).toISOString()} +   {msg.content}
))} diff --git a/client/src/store/messages.ts b/client/src/store/messages.ts index a0c7c25..05309d8 100644 --- a/client/src/store/messages.ts +++ b/client/src/store/messages.ts @@ -3,7 +3,7 @@ import { RootState } from "."; export type Message = { id: string; - time: Date; + time: number; content: string; }; diff --git a/proto/chat.proto b/proto/chat.proto index d7b06a3..37547dc 100644 --- a/proto/chat.proto +++ b/proto/chat.proto @@ -37,7 +37,7 @@ message RoomAction { service Chat { // Rooms - rpc roomAction(RoomAction) returns (RoomActionResponse) {} + rpc roomAction(RoomAction) returns (google.protobuf.Empty) {} // Messages rpc sendMsg(ChatMessage) returns (google.protobuf.Empty) {} diff --git a/server/src/main.rs b/server/src/main.rs index b75734f..6ca288e 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -34,9 +34,16 @@ impl Chat for ChatImpl { async fn room_action( &self, request: Request, - ) -> Result, Status> { + ) -> Result, Status> { + let request = request.into_inner(); println!("Join {request:?}"); - todo!() + + let user_id = Uuid::parse_str(&request.user_id).unwrap(); + let user_id = UserId(user_id); + let room_id = RoomId(request.room_id); + self.mux.user_join_room(user_id, room_id); + + Ok(Response::new(())) } async fn send_msg( diff --git a/server/src/mux.rs b/server/src/mux.rs index cb7659b..590f583 100644 --- a/server/src/mux.rs +++ b/server/src/mux.rs @@ -21,10 +21,12 @@ use uuid::Uuid; use crate::ResponseStream; +#[derive(Debug)] pub struct TextMessage { pub content: String, } +#[derive(Debug)] pub enum RoomMessage { Text(TextMessage), } @@ -66,6 +68,8 @@ impl Mux { members.insert(user_id); Room { members } }); + + println!("Joined room. Rooms: {:?}", self.rooms); } pub fn send_message_to_room(&self, room_id: RoomId, message: RoomMessage) { @@ -77,9 +81,11 @@ impl Mux { None => return, }; + println!("Sending message {message:?} to recipients:"); for user_id in recipients { // TODO: This should technically never be None? let user = self.users.get(&user_id).unwrap(); + println!(" - user: {user:?}"); user.tx.send(message.clone()); } @@ -101,8 +107,15 @@ impl Mux { let stream = UnboundedReceiverStream::new(rx); stream - .map(|message| { + .map(move |message| { + println!("Sending message to {user_id:?}: {message:?}"); + + let message = match message.as_ref() { + RoomMessage::Text(v) => v, + }; + let chat_message = ChatMessage { + content: message.content.clone(), ..Default::default() }; @@ -112,10 +125,12 @@ impl Mux { } } +#[derive(Debug)] pub struct Room { members: DashSet, } +#[derive(Debug)] pub struct ConnectedUser { tx: UnboundedSender>, rx: Option>>,