Work in progress - blocage working on it ./app 206

This commit is contained in:
NigeParis 2025-12-17 17:21:06 +01:00
parent a1d6c4ae9c
commit 637229c8c8
11 changed files with 201 additions and 33 deletions

View file

@ -1,7 +1,7 @@
import { addMessage } from "./addMessage"; import { addMessage } from "./addMessage";
import { Socket } from 'socket.io-client'; import { Socket } from 'socket.io-client';
import { getUser } from "@app/auth"; 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 * function sends socket.emit to the backend to active and broadcast a message to all sockets
* echos the message with addMessage to the sender * echos the message with addMessage to the sender
@ -13,15 +13,21 @@ export function broadcastMsg (socket: Socket, msgCommand: string[]): void {
addMessage(msgText); addMessage(msgText);
const user = getUser(); const user = getUser();
if (user && socket?.connected) { if (user && socket?.connected) {
const message = { const message: ClientMessage = {
command: msgCommand, command: msgCommand[0],
destination: '', destination: '',
type: "chat", type: "chat",
user: user.name, user: user.name,
token: document.cookie, token: document.cookie,
text: msgText, text: msgText,
timestamp: Date.now(), 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)); socket.emit('message', JSON.stringify(message));
} }

View file

@ -193,6 +193,7 @@ function logout(socket: Socket) {
async function connected(socket: Socket): Promise<void> { async function connected(socket: Socket): Promise<void> {
setTimeout(async () => {
try { try {
const buddies = document.getElementById('div-buddies') as HTMLDivElement; const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const loggedIn = isLoggedIn(); const loggedIn = isLoggedIn();
@ -201,9 +202,7 @@ async function connected(socket: Socket): Promise<void> {
let oldUser = localStorage.getItem("oldName") ?? ""; let oldUser = localStorage.getItem("oldName") ?? "";
console.log('%coldUser:',color.yellow, oldUser); console.log('%coldUser:',color.yellow, oldUser);
if (loggedIn?.name === undefined) {console.log('');return ;} if (loggedIn?.name === undefined) {console.log('');return ;}
setTimeout(() => {
oldUser = loggedIn.name ?? ""; oldUser = loggedIn.name ?? "";
}, 0);
// const res = await client.guestLogin(); // const res = await client.guestLogin();
let user = await updateUser(); let user = await updateUser();
console.log('%cUser?name:',color.yellow, user?.name); console.log('%cUser?name:',color.yellow, user?.name);
@ -217,7 +216,8 @@ async function connected(socket: Socket): Promise<void> {
console.error("Login error:", e); console.error("Login error:", e);
showError('Failed to login: Unknown error'); showError('Failed to login: Unknown error');
} }
}; }, 16);
};
async function whoami(socket: Socket) { async function whoami(socket: Socket) {
try { try {
@ -281,6 +281,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
let socket = getSocket(); let socket = getSocket();
let blockMessage: boolean;
setTimeout(async () => {
// Listen for the 'connect' event // Listen for the 'connect' event
socket.on("connect", async () => { socket.on("connect", async () => {
@ -310,6 +312,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
systemWindow.appendChild(messageElement); systemWindow.appendChild(messageElement);
systemWindow.scrollTop = systemWindow.scrollHeight; systemWindow.scrollTop = systemWindow.scrollHeight;
}); });
}, 0);
// Listen for messages from the server "MsgObjectServer" // Listen for messages from the server "MsgObjectServer"
socket.on("MsgObjectServer", (data: { message: ClientMessage}) => { socket.on("MsgObjectServer", (data: { message: ClientMessage}) => {
@ -321,8 +324,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
if (bconnected) { if (bconnected) {
connected(socket); connected(socket);
} }
console.log('stahe eeee :', blockMessage);
if (chatWindow && data.message.destination === "") { if (chatWindow && data.message.destination === "" && !blockMessage) {
const messageElement = document.createElement("div"); const messageElement = document.createElement("div");
messageElement.textContent = `${data.message.user}: ${data.message.text}`; messageElement.textContent = `${data.message.user}: ${data.message.text}`;
chatWindow.appendChild(messageElement); chatWindow.appendChild(messageElement);
@ -394,7 +397,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
console.log(' =================== >>> UserTarget:', data.userTarget); console.log(' =================== >>> UserTarget:', data.userTarget);
console.log(' =================== >>> By:', data.by); console.log(' =================== >>> By:', data.by);
let message = ""; 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; blockUserBtn.textContent = message;
} }
}); });
@ -587,5 +590,6 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
}); });
} }
} }
}; };
addRoute('/chat', handleChat, { bypass_auth: true }); addRoute('/chat', handleChat, { bypass_auth: true });

View file

@ -1,9 +1,18 @@
export type ClientMessage = { export type ClientMessage = {
command: string command: string
destination: string; destination: string;
type: string,
user: string; user: string;
userID: string,
token: string
frontendUserName: string,
frontendUser: string,
text: string; text: string;
SenderWindowID: string; SenderWindowID: string,
SenderUserName: string,
SenderUserID: string,
timestamp: number,
Sendertext: string,
}; };

View file

@ -20,6 +20,7 @@ import { sendProfil } from './sendProfil';
import { setGameLink } from './setGameLink'; import { setGameLink } from './setGameLink';
import { nextGame_SocketListener } from './nextGame_SocketListener'; import { nextGame_SocketListener } from './nextGame_SocketListener';
import { list_SocketListener } from './list_SocketListener'; import { list_SocketListener } from './list_SocketListener';
import { filter_Blocked_user } from './filter_Blocked_user'
// colors for console.log // colors for console.log
export const color = { export const color = {
@ -196,6 +197,37 @@ async function onReady(fastify: FastifyInstance) {
socket.emit('welcome', { msg: 'Welcome to the chat! : ' }); socket.emit('welcome', { msg: 'Welcome to the chat! : ' });
// Send object directly — DO NOT wrap it in a string // Send object directly — DO NOT wrap it in a string
broadcast(fastify, obj, obj.SenderWindowID); 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); // 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; if (!clientName) return;
console.log(color.green, `Client logging out: ${clientName} (${socket.id})`); console.log(color.green, `Client logging out: ${clientName} (${socket.id})`);
const obj: obj = { const obj: ClientMessage = {
command: '', command: '',
destination: 'system-info', destination: 'system-info',
type: 'chat' as const, type: 'chat' as const,
@ -239,6 +271,9 @@ async function onReady(fastify: FastifyInstance) {
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
Sendertext: '', Sendertext: '',
userID: '',
SenderUserName: '',
SenderUserID: '',
}; };
broadcast(fastify, obj, socket.id); broadcast(fastify, obj, socket.id);
// Optional: remove from map // Optional: remove from map
@ -257,7 +292,7 @@ async function onReady(fastify: FastifyInstance) {
if (reason === 'transport error') return; if (reason === 'transport error') return;
if (clientName !== null) { if (clientName !== null) {
const obj: obj = { const obj: ClientMessage = {
command: '', command: '',
destination: 'system-info', destination: 'system-info',
type: 'chat', type: 'chat',
@ -269,6 +304,9 @@ async function onReady(fastify: FastifyInstance) {
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
Sendertext: '', Sendertext: '',
userID: '',
SenderUserName: '',
SenderUserID: '',
}; };
broadcast(fastify, obj, obj.SenderWindowID); broadcast(fastify, obj, obj.SenderWindowID);
@ -285,7 +323,7 @@ async function onReady(fastify: FastifyInstance) {
); );
if (clientName !== null) { if (clientName !== null) {
const obj: obj = { const obj: ClientMessage = {
command: '', command: '',
destination: 'system-info', destination: 'system-info',
type: 'chat', type: 'chat',
@ -297,6 +335,9 @@ async function onReady(fastify: FastifyInstance) {
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
Sendertext: '', Sendertext: '',
userID: '',
SenderUserName: '',
SenderUserID: '',
}; };
// console.log(color.blue, 'DEBUG LOG: BROADCASTS OUT :', obj.SenderWindowID); // console.log(color.blue, 'DEBUG LOG: BROADCASTS OUT :', obj.SenderWindowID);
@ -316,7 +357,7 @@ async function onReady(fastify: FastifyInstance) {
); );
if (clientName !== null) { if (clientName !== null) {
const obj: obj = { const obj: ClientMessage = {
command: prvMessage.command, command: prvMessage.command,
destination: 'privateMsg', destination: 'privateMsg',
type: 'chat', type: 'chat',
@ -328,6 +369,9 @@ async function onReady(fastify: FastifyInstance) {
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
Sendertext: '', Sendertext: '',
userID: '',
SenderUserName: '',
SenderUserID:'',
}; };
// console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID); // console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID);
sendPrivMessage(fastify, obj, obj.SenderWindowID); sendPrivMessage(fastify, obj, obj.SenderWindowID);
@ -553,7 +597,7 @@ async function onReady(fastify: FastifyInstance) {
`Client entered the Chat: ${clientName} (${socket.id})`, `Client entered the Chat: ${clientName} (${socket.id})`,
); );
if (clientName !== null) { if (clientName !== null) {
const obj: obj = { const obj: ClientMessage = {
command: '', command: '',
destination: 'system-info', destination: 'system-info',
type: 'chat', type: 'chat',
@ -565,6 +609,9 @@ async function onReady(fastify: FastifyInstance) {
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
Sendertext: "", Sendertext: "",
userID: '',
SenderUserName: '',
SenderUserID: '',
}; };
broadcast(fastify, obj, obj.SenderWindowID); broadcast(fastify, obj, obj.SenderWindowID);
} }

View file

@ -1,6 +1,7 @@
import type { ClientMessage } from './chat_types'; import type { ClientMessage } from './chat_types';
import { clientChat, color } from './app'; import { clientChat, color } from './app';
import { FastifyInstance } from 'fastify'; import { FastifyInstance } from 'fastify';
import { getUserById } from './getUserById';
export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender?: string) { export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender?: string) {
fastify.io.fetchSockets().then((sockets) => { 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)`); console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`);
continue; continue;
} }
// console.log('BLOCKED MAYBE', getUserById(sender));
// console.log('TARGET',socket.id );
// Emit structured JSON object // Emit structured JSON object
socket.emit('MsgObjectServer', { message: data }); socket.emit('MsgObjectServer', { message: data });
// Debug logs // Debug logs

View file

@ -1,11 +1,21 @@
export type ClientMessage = { export type ClientMessage = {
command: string command: string
destination: string; destination: string;
type: string,
user: string; user: string;
userID: string,
token: string
frontendUserName: string,
frontendUser: string,
text: string; text: string;
SenderWindowID: string; SenderWindowID: string,
SenderUserName: string,
SenderUserID: string,
timestamp: number,
Sendertext: string,
}; };
export type ClientProfil = { export type ClientProfil = {
command: string, command: string,
destination: string, destination: string,

8
src/chat/src/color.ts Normal file
View file

@ -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',
};

View file

@ -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;
}
}

View file

@ -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;
};

View file

@ -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 "";
};

View file

@ -19,7 +19,7 @@ const route: FastifyPluginAsync = async (fastify): Promise<void> => {
config: { requireAuth: false }, config: { requireAuth: false },
}, },
async function(req, res) { 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; void res;
}, },
); );