diff --git a/frontend/src/pages/chat/chat.html b/frontend/src/pages/chat/chat.html index 49a0547..48445b8 100644 --- a/frontend/src/pages/chat/chat.html +++ b/frontend/src/pages/chat/chat.html @@ -1,25 +1,18 @@ -
-
- - - -

- Chat Box -


- - - - -

Welcome,

- - -
-
-
- - -
-
-

From this Chat Box you can send messages to other players

-
-
\ No newline at end of file +
+
+ +

+ Chat Box +


+ +

Welcome,

+
+
+
+ + +
+
+

From this Chat Box you can send messages to other players

+
+
\ No newline at end of file diff --git a/frontend/src/pages/chat/chat.ts b/frontend/src/pages/chat/chat.ts index 1833249..59806f1 100644 --- a/frontend/src/pages/chat/chat.ts +++ b/frontend/src/pages/chat/chat.ts @@ -5,9 +5,6 @@ import client from '@app/api' import { getUser, updateUser } from "@app/auth"; import io from "socket.io-client"; - -// const socket = io("wss://localhost:8888"); - const socket = io("wss://localhost:8888", { path: "/api/chat/socket.io/", secure: false, @@ -19,13 +16,11 @@ socket.on("connect", async () => { console.log("I AM Connected to the server: ", socket.id); // Emit a custom event 'coucou' with some data //socket.emit("coucou", { message: " Nigel from coucou!" }); - console.log('sent console.log coucou'); //socket.emit('testend', socket.id); // Send a message to the server //socket.send(" from the client: " + `${socket.id}`); }); - // Listen for messages from the server "MsgObjectServer" socket.on("MsgObjectServer", (data) => { console.log("Message Obj Recieved:", data.message); @@ -46,8 +41,6 @@ socket.on("MsgObjectServer", (data) => { console.log("Getuser():", getUser()); }); - - type Providers = { name: string, display_name: string, @@ -62,104 +55,80 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn return { html: authHtml, postInsert: async (app) => { + const sendButton = document.getElementById('b-send') as HTMLButtonElement; + const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement; + const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement; + const clearText = document.getElementById('b-logout') as HTMLButtonElement; + const bwhoami = document.getElementById('b-whoami') as HTMLButtonElement; + const username = document.getElementById('username') as HTMLDivElement; - const sendButton = document.getElementById('b-send') as HTMLButtonElement; - const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement; - const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement; - const clearText = document.getElementById('b-logout') as HTMLButtonElement; - const bwhoami = document.getElementById('b-whoami') as HTMLButtonElement; - const username = document.getElementById('username') as HTMLDivElement; + const addMessage = (text: string) => { + if (!chatWindow) return; + const messageElement = document.createElement("div"); + messageElement.textContent = text; + chatWindow.appendChild(messageElement); + chatWindow.scrollTop = chatWindow.scrollHeight; + }; + // Send button + sendButton?.addEventListener("click", () => { + if (sendtextbox && sendtextbox.value.trim()) { + const msgText = sendtextbox.value.trim(); + addMessage(msgText); - - - const addMessage = (text: string) => { - if (!chatWindow) return; - const messageElement = document.createElement("div"); - messageElement.textContent = text; - chatWindow.appendChild(messageElement); - chatWindow.scrollTop = chatWindow.scrollHeight; - }; - - // Send button - sendButton?.addEventListener("click", () => { - if (sendtextbox && sendtextbox.value.trim()) { - const msgText = sendtextbox.value.trim(); - addMessage(msgText); - - const user = getUser(); - if (user && socket?.connected) { - const message = { - type: "chat", - user: user.name, - token: document.cookie, - text: msgText, - timestamp: Date.now(), + const user = getUser(); + if (user && socket?.connected) { + const message = { + type: "chat", + user: user.name, + token: document.cookie, + text: msgText, + timestamp: Date.now(), SenderWindowID: socket.id, - }; - socket.send(JSON.stringify(message)); - } - - sendtextbox.value = ""; - } - }); + }; + socket.send(JSON.stringify(message)); + } + sendtextbox.value = ""; + } + }); - // Clear Text button - clearText?.addEventListener("click", () => { - if (chatWindow) { - chatWindow.innerHTML = ''; - } - }); + // Clear Text button + clearText?.addEventListener("click", () => { + if (chatWindow) { + chatWindow.innerHTML = ''; + } + }); - // Enter key to send message - sendtextbox!.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { - sendButton?.click(); - } - }); + // Enter key to send message + sendtextbox!.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + sendButton?.click(); + } + }); - chatWindow.textContent = "World"; - - // Whoami button to display user name - bwhoami?.addEventListener('click', async () => { - try { - const res = await client.guestLogin(); - switch (res.kind) { - case 'success': { - let user = await updateUser(); - if (user === null) - return showError('Failed to get user: no user ?'); - setTitle(`Welcome ${user.guest ? '[GUEST] ' : ''}${user.name}`); - break; - } - case 'failed': { - showError(`Failed to login: ${res.msg}`); - } + // Whoami button to display user name + bwhoami?.addEventListener('click', async () => { + try { + const res = await client.guestLogin(); + switch (res.kind) { + case 'success': { + let user = await updateUser(); + if (user === null) + return showError('Failed to get user: no user ?'); + setTitle(`Welcome ${user.guest ? '[GUEST] ' : ''}${user.name}`); + break; + } + case 'failed': { + showError(`Failed to login: ${res.msg}`); } - } catch (e) { - console.error("Login error:", e); - showError('Failed to login: Unknown error'); } - }); - - - - + } catch (e) { + console.error("Login error:", e); + showError('Failed to login: Unknown error'); + } + }); } } - - }; -addRoute('/chat', handleChat, { bypass_auth: true }); - // const value = await client.chatTest(); - // if (value.kind === "success") { - // console.log(value.payload); - // } - // else if (value.kind === "notLoggedIn") { - - // } else { - // console.log('unknown response: ', value); - // } - - // Helper to add a message locally \ No newline at end of file +addRoute('/chat', handleChat, { bypass_auth: true }); \ No newline at end of file diff --git a/src/chat/src/routes/nginx-chat.ts b/src/chat/src/routes/nginx-chat.ts index 096f7b3..60526b9 100644 --- a/src/chat/src/routes/nginx-chat.ts +++ b/src/chat/src/routes/nginx-chat.ts @@ -3,15 +3,6 @@ import { MakeStaticResponse, typeResponse } from '@shared/utils'; import { Type } from '@sinclair/typebox'; import * as fsocketio from 'fastify-socket.io'; - -// const fastify = Fastify(); - -// const io = new Server(fastify.server, { -// path: '/app/chat/socket.io/', -// cors: { origin: '*' }, -// }); - - export const ChatRes = { 200: typeResponse('success', 'chat.success', { name: Type.String(), @@ -20,14 +11,11 @@ export const ChatRes = { }), }; - export type ChatResType = MakeStaticResponse; const route: FastifyPluginAsync = async (fastify): Promise => { await fastify.register(fsocketio.default); - - // fastify.get( // '/api/chat/test', // { @@ -43,4 +31,4 @@ const route: FastifyPluginAsync = async (fastify): Promise => { // }, // ); }; -export default route; +export default route; \ No newline at end of file diff --git a/src/chat/src/socket.ts b/src/chat/src/socket.ts index b11cb33..205e5f5 100644 --- a/src/chat/src/socket.ts +++ b/src/chat/src/socket.ts @@ -17,72 +17,43 @@ declare module 'fastify' { testend: (sock_id_client: string) => void, }> } -} - - - - +}; export function setupSocketIo(fastify: import('fastify').FastifyInstance): void { fastify.ready((err) => { if (err) throw err; - // function broadcast(message: any, sender?: any) { - - // fastify.io.fetchSockets().then((sockets) => { - // console.log("Connected clients:", sockets.length); - // for (const s of sockets) { - - // if (s.id !== sender) { - // s.emit('MsgObjectServer',{ message: `${message}` }); - // console.log("Socket ID:", s.id); - // console.log("Rooms:", [...s.rooms]); - // console.log("Sender:", sender ? sender : 'none'); - // console.log("ID:", message.text ? message.text : 'none'); - // } - // } - // }); - // } - - -function broadcast(data: any, sender?: string) { - fastify.io.fetchSockets().then((sockets) => { - console.log("Connected clients:", sockets.length); - - for (const s of sockets) { - if (s.id !== sender) { - // Send REAL JSON object - s.emit("MsgObjectServer", { message: data }); - - console.log(" emit window socket ID:", s.id); - console.log(" emit window ID:", [...s.rooms]); - console.log(" Sender window ID:", sender ? sender : "none"); - console.log(" text recieved:", data.text ? data.text : "none"); - console.log(color.red, "data:", color.reset, data ? data : "none"); - } - } - }); -} - - + // Broadcast function to send messages to all connected clients except the sender + function broadcast(data: any, sender?: string) { + fastify.io.fetchSockets().then((sockets) => { + console.log("Connected clients:", sockets.length); + for (const s of sockets) { + if (s.id !== sender) { + // Send REAL JSON object + s.emit("MsgObjectServer", { message: data }); + console.log(" emit window socket ID:", s.id); + console.log(" emit window ID:", [...s.rooms]); + console.log(" Sender window ID:", sender ? sender : "none"); + console.log(" text recieved:", data.text ? data.text : "none"); + console.log(color.red, "data:", color.reset, data ? data : "none"); + } + } + }); + }; // console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(fastify.io))); fastify.io.on('connection', (socket : Socket) => { console.info(color.blue, 'Socket connected!', color.reset, socket.id); socket.on("message", (message: string) => { console.log(color.blue, `Received message from client`, color.reset, message); - const obj = JSON.parse(message); // { userID, text } - console.log(color.green, `Message from client`, color.reset, `${obj.userID}: ${obj.text}`); + const obj = JSON.parse(message); // { userID, text } + console.log(color.green, `Message from client`, color.reset, `${obj.userID}: ${obj.text}`); - // Send object directly — DO NOT wrap it in a string - broadcast(obj, obj.SenderWindowID); + // Send object directly — DO NOT wrap it in a string + broadcast(obj, obj.SenderWindowID); }); - - - - socket.on('testend', (sock_id_cl : string) => { console.log('testend received from client socket id:', sock_id_cl); }); @@ -90,12 +61,6 @@ function broadcast(data: any, sender?: string) { console.log("Client is disconnecting:", socket.id, "reason:", reason); console.log('Socket AAAAAAAActing because:', socket.connected); }); - - - }); - - }); - - }; - \ No newline at end of file + }); +}; \ No newline at end of file