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 { 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));
}

View file

@ -193,6 +193,7 @@ function logout(socket: Socket) {
async function connected(socket: Socket): Promise<void> {
setTimeout(async () => {
try {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const loggedIn = isLoggedIn();
@ -201,24 +202,23 @@ async function connected(socket: Socket): Promise<void> {
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 });

View file

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

View file

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

View file

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

View file

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

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 },
},
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;
},
);