From 637229c8c873cedca4858615cd45ba201f9e972c Mon Sep 17 00:00:00 2001 From: NigeParis Date: Wed, 17 Dec 2025 17:21:06 +0100 Subject: [PATCH] Work in progress - blocage working on it ./app 206 --- frontend/src/pages/chat/broadcastMsg.ts | 14 ++++-- frontend/src/pages/chat/chat.ts | 44 ++++++++++--------- frontend/src/pages/chat/types_front.ts | 11 ++++- src/chat/src/app.ts | 57 ++++++++++++++++++++++--- src/chat/src/broadcast.ts | 3 ++ src/chat/src/chat_types.ts | 14 +++++- src/chat/src/color.ts | 8 ++++ src/chat/src/filter_Blocked_user.ts | 39 +++++++++++++++++ src/chat/src/getUserById.ts | 10 +++++ src/chat/src/isUser_BlockedBy_me.ts | 32 ++++++++++++++ src/chat/src/routes/broadcast.ts | 2 +- 11 files changed, 201 insertions(+), 33 deletions(-) create mode 100644 src/chat/src/color.ts create mode 100644 src/chat/src/filter_Blocked_user.ts create mode 100644 src/chat/src/getUserById.ts create mode 100644 src/chat/src/isUser_BlockedBy_me.ts diff --git a/frontend/src/pages/chat/broadcastMsg.ts b/frontend/src/pages/chat/broadcastMsg.ts index 51a1130..586243b 100644 --- a/frontend/src/pages/chat/broadcastMsg.ts +++ b/frontend/src/pages/chat/broadcastMsg.ts @@ -1,7 +1,7 @@ import { addMessage } from "./addMessage"; import { Socket } from 'socket.io-client'; import { getUser } from "@app/auth"; - +import type { ClientMessage } from "./types_front"; /** * function sends socket.emit to the backend to active and broadcast a message to all sockets * echos the message with addMessage to the sender @@ -13,15 +13,21 @@ export function broadcastMsg (socket: Socket, msgCommand: string[]): void { addMessage(msgText); const user = getUser(); if (user && socket?.connected) { - const message = { - command: msgCommand, + const message: ClientMessage = { + command: msgCommand[0], destination: '', type: "chat", user: user.name, token: document.cookie, text: msgText, timestamp: Date.now(), - SenderWindowID: socket.id, + SenderWindowID: socket.id ?? "", + SenderUserName: user.name, + SenderUserID: user.id, + userID: '', + frontendUserName: '', + frontendUser: '', + Sendertext: '', }; socket.emit('message', JSON.stringify(message)); } diff --git a/frontend/src/pages/chat/chat.ts b/frontend/src/pages/chat/chat.ts index fe31df4..65f4b3a 100644 --- a/frontend/src/pages/chat/chat.ts +++ b/frontend/src/pages/chat/chat.ts @@ -193,6 +193,7 @@ function logout(socket: Socket) { async function connected(socket: Socket): Promise { + setTimeout(async () => { try { const buddies = document.getElementById('div-buddies') as HTMLDivElement; const loggedIn = isLoggedIn(); @@ -201,24 +202,23 @@ async function connected(socket: Socket): Promise { let oldUser = localStorage.getItem("oldName") ?? ""; console.log('%coldUser:',color.yellow, oldUser); if (loggedIn?.name === undefined) {console.log('');return ;} - setTimeout(() => { oldUser = loggedIn.name ?? ""; - }, 0); - // const res = await client.guestLogin(); - let user = await updateUser(); - console.log('%cUser?name:',color.yellow, user?.name); - localStorage.setItem("oldName", oldUser); - buddies.textContent = ""; - socket.emit('list', { - oldUser: oldUser, - user: user?.name, - }); - } catch (e) { - console.error("Login error:", e); - showError('Failed to login: Unknown error'); - } -}; - + // const res = await client.guestLogin(); + let user = await updateUser(); + console.log('%cUser?name:',color.yellow, user?.name); + localStorage.setItem("oldName", oldUser); + buddies.textContent = ""; + socket.emit('list', { + oldUser: oldUser, + user: user?.name, + }); + } catch (e) { + console.error("Login error:", e); + showError('Failed to login: Unknown error'); + } + }, 16); + }; + async function whoami(socket: Socket) { try { const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement; @@ -281,6 +281,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn let socket = getSocket(); + let blockMessage: boolean; + setTimeout(async () => { // Listen for the 'connect' event socket.on("connect", async () => { @@ -310,6 +312,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn systemWindow.appendChild(messageElement); systemWindow.scrollTop = systemWindow.scrollHeight; }); +}, 0); // Listen for messages from the server "MsgObjectServer" socket.on("MsgObjectServer", (data: { message: ClientMessage}) => { @@ -321,8 +324,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn if (bconnected) { connected(socket); } - - if (chatWindow && data.message.destination === "") { + console.log('stahe eeee :', blockMessage); + if (chatWindow && data.message.destination === "" && !blockMessage) { const messageElement = document.createElement("div"); messageElement.textContent = `${data.message.user}: ${data.message.text}`; chatWindow.appendChild(messageElement); @@ -394,7 +397,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn console.log(' =================== >>> UserTarget:', data.userTarget); console.log(' =================== >>> By:', data.by); let message = ""; - if (data.userState === "block") {message = "un-block"} else{message = "block"} + if (data.userState === "block") {message = "un-block", blockMessage = true} else{message = "block", blockMessage = false} blockUserBtn.textContent = message; } }); @@ -587,5 +590,6 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn }); } } + }; addRoute('/chat', handleChat, { bypass_auth: true }); \ No newline at end of file diff --git a/frontend/src/pages/chat/types_front.ts b/frontend/src/pages/chat/types_front.ts index 913095a..93f9ab6 100644 --- a/frontend/src/pages/chat/types_front.ts +++ b/frontend/src/pages/chat/types_front.ts @@ -1,9 +1,18 @@ export type ClientMessage = { command: string destination: string; + type: string, user: string; + userID: string, + token: string + frontendUserName: string, + frontendUser: string, text: string; - SenderWindowID: string; + SenderWindowID: string, + SenderUserName: string, + SenderUserID: string, + timestamp: number, + Sendertext: string, }; diff --git a/src/chat/src/app.ts b/src/chat/src/app.ts index 8ee238e..fac6cb4 100644 --- a/src/chat/src/app.ts +++ b/src/chat/src/app.ts @@ -20,6 +20,7 @@ import { sendProfil } from './sendProfil'; import { setGameLink } from './setGameLink'; import { nextGame_SocketListener } from './nextGame_SocketListener'; import { list_SocketListener } from './list_SocketListener'; +import { filter_Blocked_user } from './filter_Blocked_user' // colors for console.log export const color = { @@ -196,6 +197,37 @@ async function onReady(fastify: FastifyInstance) { socket.emit('welcome', { msg: 'Welcome to the chat! : ' }); // Send object directly — DO NOT wrap it in a string broadcast(fastify, obj, obj.SenderWindowID); + + const users: User[] = fastify.db.getAllUsers() ?? []; + console.log('DEBUG: senderWindow :', getUserById(users, obj.SenderUserID)?.name); + + + + + fastify.io.fetchSockets().then((sockets) => { + for (const socket of sockets) { + const clientInfo = clientChat.get(socket.id); + if (!clientInfo?.user) { + console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`); + continue; + } + console.log('DEBUG: UserIDWindow :', getUserByName(users, clientInfo.user)?.id); + const IDUser = getUserByName(users, clientInfo.user)?.id; + + console.log(filter_Blocked_user(fastify, obj, IDUser?? "")); + + + } + }); + + + + + + + + + // console.log(color.red, 'DEBUG LOG: connected in the Chat :', connectedUser(fastify.io), color.reset); }); @@ -227,7 +259,7 @@ async function onReady(fastify: FastifyInstance) { if (!clientName) return; console.log(color.green, `Client logging out: ${clientName} (${socket.id})`); - const obj: obj = { + const obj: ClientMessage = { command: '', destination: 'system-info', type: 'chat' as const, @@ -239,6 +271,9 @@ async function onReady(fastify: FastifyInstance) { timestamp: Date.now(), SenderWindowID: socket.id, Sendertext: '', + userID: '', + SenderUserName: '', + SenderUserID: '', }; broadcast(fastify, obj, socket.id); // Optional: remove from map @@ -257,7 +292,7 @@ async function onReady(fastify: FastifyInstance) { if (reason === 'transport error') return; if (clientName !== null) { - const obj: obj = { + const obj: ClientMessage = { command: '', destination: 'system-info', type: 'chat', @@ -269,6 +304,9 @@ async function onReady(fastify: FastifyInstance) { timestamp: Date.now(), SenderWindowID: socket.id, Sendertext: '', + userID: '', + SenderUserName: '', + SenderUserID: '', }; broadcast(fastify, obj, obj.SenderWindowID); @@ -285,7 +323,7 @@ async function onReady(fastify: FastifyInstance) { ); if (clientName !== null) { - const obj: obj = { + const obj: ClientMessage = { command: '', destination: 'system-info', type: 'chat', @@ -297,6 +335,9 @@ async function onReady(fastify: FastifyInstance) { timestamp: Date.now(), SenderWindowID: socket.id, Sendertext: '', + userID: '', + SenderUserName: '', + SenderUserID: '', }; // console.log(color.blue, 'DEBUG LOG: BROADCASTS OUT :', obj.SenderWindowID); @@ -316,7 +357,7 @@ async function onReady(fastify: FastifyInstance) { ); if (clientName !== null) { - const obj: obj = { + const obj: ClientMessage = { command: prvMessage.command, destination: 'privateMsg', type: 'chat', @@ -328,6 +369,9 @@ async function onReady(fastify: FastifyInstance) { timestamp: Date.now(), SenderWindowID: socket.id, Sendertext: '', + userID: '', + SenderUserName: '', + SenderUserID:'', }; // console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID); sendPrivMessage(fastify, obj, obj.SenderWindowID); @@ -553,7 +597,7 @@ async function onReady(fastify: FastifyInstance) { `Client entered the Chat: ${clientName} (${socket.id})`, ); if (clientName !== null) { - const obj: obj = { + const obj: ClientMessage = { command: '', destination: 'system-info', type: 'chat', @@ -565,6 +609,9 @@ async function onReady(fastify: FastifyInstance) { timestamp: Date.now(), SenderWindowID: socket.id, Sendertext: "", + userID: '', + SenderUserName: '', + SenderUserID: '', }; broadcast(fastify, obj, obj.SenderWindowID); } diff --git a/src/chat/src/broadcast.ts b/src/chat/src/broadcast.ts index 1d697fa..e028d7d 100644 --- a/src/chat/src/broadcast.ts +++ b/src/chat/src/broadcast.ts @@ -1,6 +1,7 @@ import type { ClientMessage } from './chat_types'; import { clientChat, color } from './app'; import { FastifyInstance } from 'fastify'; +import { getUserById } from './getUserById'; export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender?: string) { fastify.io.fetchSockets().then((sockets) => { @@ -13,6 +14,8 @@ export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender? console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`); continue; } + // console.log('BLOCKED MAYBE', getUserById(sender)); + // console.log('TARGET',socket.id ); // Emit structured JSON object socket.emit('MsgObjectServer', { message: data }); // Debug logs diff --git a/src/chat/src/chat_types.ts b/src/chat/src/chat_types.ts index 0377659..05a938e 100644 --- a/src/chat/src/chat_types.ts +++ b/src/chat/src/chat_types.ts @@ -1,11 +1,21 @@ export type ClientMessage = { command: string destination: string; + type: string, user: string; + userID: string, + token: string + frontendUserName: string, + frontendUser: string, text: string; - SenderWindowID: string; + SenderWindowID: string, + SenderUserName: string, + SenderUserID: string, + timestamp: number, + Sendertext: string, }; + export type ClientProfil = { command: string, destination: string, @@ -21,4 +31,4 @@ export type ClientProfil = { Sendertext: string, innerHtml?: string, -}; \ No newline at end of file +}; diff --git a/src/chat/src/color.ts b/src/chat/src/color.ts new file mode 100644 index 0000000..cb87c2c --- /dev/null +++ b/src/chat/src/color.ts @@ -0,0 +1,8 @@ +// colors for console.log +export const color = { + red: '\x1b[31m', + green: '\x1b[32m', + yellow: '\x1b[33m', + blue: '\x1b[34m', + reset: '\x1b[0m', +}; \ No newline at end of file diff --git a/src/chat/src/filter_Blocked_user.ts b/src/chat/src/filter_Blocked_user.ts new file mode 100644 index 0000000..3f96bef --- /dev/null +++ b/src/chat/src/filter_Blocked_user.ts @@ -0,0 +1,39 @@ +import type { ClientMessage, ClientProfil } from './chat_types'; +import { FastifyInstance } from 'fastify'; +import type { User } from '@shared/database/mixin/user'; +import { getUserById } from './getUserById'; +import { isUser_BlockedBy_me } from './isUser_BlockedBy_me'; + +/** + * function to check if blocked or not - checks with ID + * @param fastify + * @param data + * @returns true or false - true if blocked user by a user + */ + +export function filter_Blocked_user(fastify: FastifyInstance, data: ClientMessage, id: string): boolean { + + const users: User[] = fastify.db.getAllUsers() ?? []; + const UserToBlock: string = id; + const UserAskingToBlock: User | null = getUserById(users,`${data.SenderUserID}`); + if (!UserAskingToBlock ) { + // console.log('SOMETHING NULL', data); + // console.log('UsetToBlock', UserToBlock?.id); + // console.log('UsetToBlock', UserToBlock?.name); + // console.log('UsetAskingToBlock', UserAskingToBlock?.id); + // console.log('UsetAskingToBlock', UserAskingToBlock?.name); + console.log(''); + + + return false; + } + if(isUser_BlockedBy_me(fastify, UserAskingToBlock!.id, UserToBlock)) + { + return true; + } + else + { + return false; + } +} + diff --git a/src/chat/src/getUserById.ts b/src/chat/src/getUserById.ts new file mode 100644 index 0000000..a276238 --- /dev/null +++ b/src/chat/src/getUserById.ts @@ -0,0 +1,10 @@ +import type { User } from '@shared/database/mixin/user'; +/** + * function get the object user in an array of users[] by name + * @param users + * @param name + * @returns + */ +export function getUserById(users: User[], id: string) { + return users.find(user => user.id === id) || null; +}; diff --git a/src/chat/src/isUser_BlockedBy_me.ts b/src/chat/src/isUser_BlockedBy_me.ts new file mode 100644 index 0000000..dcd7bb4 --- /dev/null +++ b/src/chat/src/isUser_BlockedBy_me.ts @@ -0,0 +1,32 @@ +import { FastifyInstance } from 'fastify'; +import type { User } from '@shared/database/mixin/user'; +import type { BlockedData } from '@shared/database/mixin/blocked'; +import { isBlocked } from './isBlocked'; +import { getUserById } from './getUserById'; +import { color } from './color'; + +/** + * checks the Db for the two matching Ids + * @param fastify + * @param blockedBy_Id + * @param isBlocked_Id + * @returns Null if not blocked + */ + +export function isUser_BlockedBy_me(fastify: FastifyInstance, blockedBy_Id : string, isBlocked_Id: string): string { + const users: User[] = fastify.db.getAllUsers() ?? []; + if (!users) return ''; + const UserToBlock: User | null = getUserById(users, `${isBlocked_Id}`); + const UserAskingToBlock: User | null = getUserById(users, `${blockedBy_Id}`); + if (!UserToBlock) {console.log(color.blue, `'User: ${UserAskingToBlock?.id} has not blocked' ${isBlocked_Id}`); return ""}; + if (!UserAskingToBlock) {console.log(color.blue, `'User: ${UserToBlock?.id} has not blocked by' ${blockedBy_Id}`); return ""}; + const usersBlocked: BlockedData[] = fastify.db.getAllBlockedUsers() ?? []; + const userAreBlocked: boolean = isBlocked(UserAskingToBlock, UserToBlock, usersBlocked); + if (userAreBlocked) { + console.log(color.yellow, `'User :${UserAskingToBlock.name}) Hhas UN blocked ${UserToBlock.name}`) + return UserAskingToBlock.name; + } + console.log(color.blue, `'User :${UserAskingToBlock.name}) has BBBblocked ${UserToBlock.name}`) + + return ""; +}; diff --git a/src/chat/src/routes/broadcast.ts b/src/chat/src/routes/broadcast.ts index 9bd0ec2..de46038 100644 --- a/src/chat/src/routes/broadcast.ts +++ b/src/chat/src/routes/broadcast.ts @@ -19,7 +19,7 @@ const route: FastifyPluginAsync = async (fastify): Promise => { config: { requireAuth: false }, }, async function(req, res) { - broadcast(this, { command: '', destination: '', user: 'CMwaLeSever!!', text: req.body.message, SenderWindowID: 'server' }); + //broadcast(this, { command: '', destination: '', user: 'CMwaLeSever!!', text: req.body.message, SenderWindowID: 'server' }); void res; }, );