WIP Blocked users and clean up obj { } its in constitant

This commit is contained in:
NigeParis 2025-12-17 09:57:41 +01:00
parent 556138d624
commit f5366bf9e1
4 changed files with 129 additions and 76 deletions

View file

@ -23,6 +23,14 @@ export const color = {
reset: '',
};
export type blockedUnBlocked =
{
userState: string,
userTarget: string,
by: string,
};
// get the name of the machine used to connect
const machineHostName = window.location.hostname;
console.log('connect to login at %chttps://' + machineHostName + ':8888/app/login',color.yellow);
@ -64,22 +72,6 @@ function actionBtnPopUpInvite(invite: ClientProfil, senderSocket: Socket) {
}, 0)
};
// async function windowStateHidden() {
// const socketId = __socket || undefined;
// // let oldName = localStorage.getItem("oldName") ?? undefined;
// let oldName: string;
// if (socketId === undefined) return;
// let userName = await updateUser();
// oldName = userName?.name ?? "";
// if (oldName === "") return;
// localStorage.setItem('oldName', oldName);
// socketId.emit('client_left', {
// user: userName?.name,
// why: 'tab window hidden - socket not dead',
// });
// return;
// };
async function windowStateVisable() {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
@ -141,36 +133,6 @@ function parseCmdMsg(msgText: string): string[] | undefined {
return command;
}
// async function listBuddies(socket: Socket, buddies: HTMLDivElement, listBuddies: string) {
// if (!buddies) return;
// const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
// const buddiesElement = document.createElement("div-buddies-list");
// buddiesElement.textContent = listBuddies + '\n';
// const user = getUser()?.name ?? "";
// buddies.appendChild(buddiesElement);
// buddies.scrollTop = buddies.scrollHeight;
// console.log(`Added buddies: ${listBuddies}`);
// buddiesElement.style.cursor = "pointer";
// buddiesElement.addEventListener("click", () => {
// navigator.clipboard.writeText(listBuddies);
// if (listBuddies !== user && user !== "") {
// sendtextbox.value = `@${listBuddies}: `;
// console.log("Copied to clipboard:", listBuddies);
// sendtextbox.focus();
// }
// });
// buddiesElement.addEventListener("dblclick", () => {
// console.log("Open profile:", listBuddies);
// getProfil(socket, listBuddies);
// sendtextbox.value = "";
// });
// }
function waitSocketConnected(socket: Socket): Promise<void> {
return new Promise(resolve => {
if (socket.connected) return resolve();
@ -270,30 +232,6 @@ async function whoami(socket: Socket) {
}
};
// async function openProfilePopup(profil: ClientProfil) {
// const modalname = document.getElementById("modal-name") ?? null;
// if (modalname)
// modalname.innerHTML = `
// <div class="profile-info">
// <div-profil-name id="profilName"> Profil of ${profil.user} </div>
// <div-login-name id="loginName"> Login Name: '${profil.loginName ?? 'Guest'}' </div>
// </br>
// <div-login-name id="loginName"> Login ID: '${profil.userID ?? ''}' </div>
// </br>
// <button id="popup-b-clear" class="btn-style popup-b-clear">Clear Text</button>
// <button id="popup-b-invite" class="btn-style popup-b-invite">U Game ?</button>
// <button id="popup-b-block" class="btn-style popup-b-block">Block User</button>
// <div id="profile-about">About: '${profil.text}' </div>
// </div>
// `;
// const profilList = document.getElementById("profile-modal") ?? null;
// if (profilList)
// profilList.classList.remove("hidden");
// // The popup now exists → attach the event
// }
let count = 0;
function incrementCounter(): number {
count += 1;
@ -336,6 +274,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
await waitSocketConnected(socket);
console.log("I AM Connected to the server:", socket.id);
const user = getUser()?.name;
const userID = getUser()?.id;
// Ensure we have a user AND socket is connected
if (!user || !socket.connected) return;
const message = {
@ -347,6 +286,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
text: " has Just ARRIVED in the chat",
timestamp: Date.now(),
SenderWindowID: socket.id,
SenderID: userID,
};
socket.emit('message', JSON.stringify(message));
const messageElement = document.createElement("div");
@ -397,7 +338,12 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
});
socket.on('profilMessage', (profil: ClientProfil) => {
profil.SenderID = getUser()?.id ?? "";
profil.SenderName = getUser()?.name ?? "";
openProfilePopup(profil);
console.log(`DEBUG LOG: userId:${profil.userID}: senderID ${profil.SenderID}' senderID:${getUser()?.id}`);
console.log(`DEBUG LOG: user:${profil.user}: sender:${profil.SenderName}' senderID:${getUser()?.name}`);
socket.emit('check_Block_button', profil);
actionBtnPopUpClear(profil, socket);
actionBtnPopUpInvite(profil, socket);
actionBtnPopUpBlock(profil, socket);
@ -416,13 +362,25 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
let icon = '⛔';
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
const messageElement = document.createElement("div");
if (`${blocked.text}` === '\'I have un-blocked you\'' ) { icon = '💚'};
if (`${blocked.text}` === 'I have un-blocked you' ) { icon = '💚'};
messageElement.innerText =`${icon}${blocked.SenderName}: ${blocked.text}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
});
socket.on('blockBtn', (data: blockedUnBlocked) => {
const blockUserBtn = document.querySelector("#popup-b-block");
if (blockUserBtn) {
console.log(' =================== >>> User State:', data.userState);
console.log(' =================== >>> UserTarget:', data.userTarget);
console.log(' =================== >>> By:', data.by);
let message = "";
if (data.userState === "block") {message = "un-block"} else{message = "block"}
blockUserBtn.textContent = message;
}
});
socket.on('logout', () => {
@ -553,6 +511,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
break;
default:
const user = getUser()?.name;
const userID = getUser()?.id;
// Ensure we have a user AND socket is connected
if (!user || !socket.connected) return;
const message = {
@ -564,6 +523,8 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
text: msgCommand[1],
timestamp: Date.now(),
SenderWindowID: socket.id,
SenderID: userID,
};
//socket.emit('MsgObjectServer', message);
socket.emit('privMessage', JSON.stringify(message));

View file

@ -18,6 +18,7 @@ export type ClientProfil = {
timestamp: number,
SenderWindowID:string,
SenderName: string,
SenderID: string,
Sendertext: string,
innerHtml?: string,
};

View file

@ -39,6 +39,32 @@ interface ClientInfo {
lastSeen: number;
}
export type blockedUnBlocked =
{
userState: string,
userTarget: string,
by: string,
};
export type obj =
{
command: string,
destination: string,
type: string,
user: string,
frontendUserName: string,
frontendUser: string,
token: string,
text: string,
timestamp: number,
SenderWindowID: string,
Sendertext: string,
};
// function setAboutPlayer(about: string): string {
// if (!about) {
// about = 'Player is good Shape - This is a default description';
@ -107,10 +133,45 @@ declare module 'fastify' {
client_left: (userName: string, why: string) => void;
list: (oldUser: string, user: string) => void;
updateClientName: (oldUser: string, user: string) => void;
blockBtn: (data: blockedUnBlocked) => void;
check_Block_button: (data: blockedUnBlocked) => void;
}>;
}
}
/**
* function get the object user in an array of users[] by name
* @param users
* @param name
* @returns
*/
function getUserById(users: User[], id: string) {
return users.find(user => user.id === id) || null;
};
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 "";
};
async function onReady(fastify: FastifyInstance) {
@ -141,6 +202,8 @@ async function onReady(fastify: FastifyInstance) {
list_SocketListener(fastify, socket);
// socket.on('list', (object) => {
// const userFromFrontend = object || null;
@ -264,15 +327,18 @@ async function onReady(fastify: FastifyInstance) {
);
if (clientName !== null) {
const obj = {
const obj: obj = {
command: prvMessage.command,
destination: 'privateMsg',
type: 'chat',
user: clientName,
token: '',
text: prvMessage.text,
frontendUserName: '',
frontendUser: '',
timestamp: Date.now(),
SenderWindowID: socket.id,
Sendertext: '',
};
// console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID);
sendPrivMessage(fastify, obj, obj.SenderWindowID);
@ -309,6 +375,8 @@ async function onReady(fastify: FastifyInstance) {
}
});
socket.on('blockUser', async (data: string) => {
const clientName: string = clientChat.get(socket.id)?.user || '';
const profilBlock: ClientProfil = JSON.parse(data) || '';
@ -320,10 +388,13 @@ async function onReady(fastify: FastifyInstance) {
console.log(color.yellow, UserToBlock);
console.log(color.yellow, `user Asking to block: ${profilBlock.SenderName}`);
console.log(color.yellow, UserAskingToBlock);
console.log(color.red, clientName);
const usersBlocked: BlockedData[] = fastify.db.getAllBlockedUsers() ?? [];
if (!UserAskingToBlock || !UserToBlock || !usersBlocked) return;
const userAreBlocked: boolean = isBlocked(UserAskingToBlock, UserToBlock, usersBlocked);
isUser_BlockedBy_me(fastify, UserAskingToBlock!.id, UserToBlock!.id);
if (userAreBlocked) {
console.log(color.green, 'Both users are blocked as requested');
@ -333,17 +404,19 @@ async function onReady(fastify: FastifyInstance) {
console.log(color.red, 'ALL BLOCKED USERS:', usersBlocked);
fastify.db.removeBlockedUserFor(UserAskingToBlock!.id, UserToBlock!.id);
const usersBlocked2 = fastify.db.getAllBlockedUsers();
console.log(color.green, 'remove ALL BLOCKED USERS:', usersBlocked2);
console.log(color.green, 'remove A BLOCKED USER:', usersBlocked2);
if (clientName !== null) {
const blockedMessage = 'I have un-blocked you';
if (clientName !== null) {
const obj = {
const obj: obj = {
command: 'message',
destination: 'privateMsg',
type: 'chat',
user: clientName,
token: '',
text: '',
frontendUserName: '',
frontendUser: '',
timestamp: Date.now(),
SenderWindowID: socket.id,
Sendertext: 'You have un-blocked',
@ -354,6 +427,14 @@ async function onReady(fastify: FastifyInstance) {
}
// profilBlock.Sendertext = `'You have un-blocked '`;
sendBlocked(fastify, blockedMessage, profilBlock);
const message: blockedUnBlocked =
{
userState: "un-block",
userTarget: "",
by: "",
};
socket.emit('blockBtn', message);
}
}
else {
@ -367,7 +448,7 @@ async function onReady(fastify: FastifyInstance) {
const blockedMessage = 'I have blocked you';
profilBlock.Sendertext = 'You have blocked ';
if (clientName !== null) {
const obj = {
const obj: obj = {
command: 'message',
destination: 'privateMsg',
type: 'chat',
@ -383,6 +464,14 @@ async function onReady(fastify: FastifyInstance) {
// clientChat.delete(obj.user);
}
sendBlocked(fastify, blockedMessage, profilBlock);
const message: blockedUnBlocked =
{
userState: "block",
userTarget: UserToBlock.name,
by: UserAskingToBlock.name,
};
socket.emit('blockBtn', message);
}
}
});
@ -416,7 +505,7 @@ async function onReady(fastify: FastifyInstance) {
`Client entered the Chat: ${clientName} (${socket.id})`,
);
if (clientName !== null) {
const obj = {
const obj: obj = {
command: '',
destination: 'system-info',
type: 'chat',
@ -427,6 +516,7 @@ async function onReady(fastify: FastifyInstance) {
text: text,
timestamp: Date.now(),
SenderWindowID: socket.id,
Sendertext: "",
};
broadcast(fastify, obj, obj.SenderWindowID);
}

View file

@ -17,6 +17,7 @@ export type ClientProfil = {
timestamp: number,
SenderWindowID:string,
SenderName: string,
SenderID: string,
Sendertext: string,
innerHtml?: string,