basic setup pong - frontend and backend with simplw socket message and fastify route

This commit is contained in:
NigeParis 2025-12-13 12:08:12 +01:00 committed by Maix0
parent 5354c01bad
commit 6e6162c3f0
19 changed files with 60 additions and 641 deletions

View file

@ -56,6 +56,7 @@
<script type="module" src="/src/routing"></script>
<script type="module" src="/src/toast"></script>
<script type="module" src="/src/auth"></script>
<script type="module" src="/src/pong/"></script>
</body>
</html>

View file

@ -3,8 +3,8 @@ import { Socket } from 'socket.io-client';
import { getUser } from "@app/auth";
/**
* function sends socket.emit to the backend to active and broadcast a message to all sockets
* echos the message with addMessage to the sender
* function sends socket.emit to the backend to active and a broadcast message to all sockets
* echos addPongMessage() the message with addMessage to the sender
* @param socket
* @param msgCommand
*/

View file

@ -2,19 +2,28 @@
<div id="mainbox" class="mainboxDisplay">
<button id="b-whoami" class="btn-style absolute top-4 left-6">Who am i</button>
<h1 class="text-3xl font-bold text-gray-800">
Pong Box<span id="t-username"></span>
Pong Box<span id="t-username"></span>
</h1><br>
<!-- Horizontal Message Box -->
<div id="system-box" class="system-info">System: connecting ... </div>
<!-- Pong Box -->
<p>try this in a terminal</p>
</br>
<p>curl -k --data-raw '{"message": "Message SENT from the terminal en REMOTE"}' 'https://local.maix.me:8888/api/pong/broadcast' -H "Content-Type: application/json"</p>
<div class="flex justify-center mt-2">
<div id="g-textBoxes" class="flex flex-col">
<div id="t-chatbox" class="chatbox-style"></div>
<div id="t-input-send" class="flex gap-1 mt-2">
<div id="pongspace" class="flex flex-col">
<div id="pongbox" class="pongbox-style">
<div class="pong-field">
<div class="pong-center-line"></div>
<div class="pong-bat left"></div>
<div class="pong-bat right"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View file

@ -1,2 +1 @@
import './pong.css';

View file

@ -80,7 +80,8 @@
bg-gray-200 w-[850px]
p-6 rounded-xl
shadow-2xl
text-center z-50;
text-center
z-50;
}
.mainboxDisplay button {
@ -88,18 +89,49 @@
cursor-pointer
}
.title {
.pongbox-style {
@apply
text-6xl
font-bold
text-gray-800
h-[450px]
w-[800px]
bg-gray-400
text-6xl
flex
items-center
justify-center;
}
p {
.text-style {
@apply
text-black
}
.pong-field {
@apply relative w-[800px] h-[450px] bg-black;
}
.pong-bat {
@apply absolute w-[12px] h-[80px] bg-white;
}
.pong-bat.left {
@apply left-4 top-1/2 -translate-y-1/2;
}
.pong-bat.right {
@apply right-4 top-1/2 -translate-y-1/2;
}
.pong-center-line {
@apply
absolute
left-1/2
top-0
h-full
w-[4px]
-translate-x-1/2
bg-[linear-gradient(to_bottom,white_50%,transparent_50%)]
bg-[length:4px_20px];
}

View file

@ -89,7 +89,6 @@ export { app };
declare module 'fastify' {
interface FastifyInstance {
io: Server<{
hello: (message: string) => string;
MsgObjectServer: (data: { message: ClientMessage }) => void;
privMessage: (data: string) => void;
profilMessage: (data: ClientProfil) => void;

View file

@ -6,20 +6,12 @@ import * as auth from '@shared/auth';
import * as swagger from '@shared/swagger';
import * as utils from '@shared/utils';
import { Server, Socket } from 'socket.io';
import type { User } from '@shared/database/mixin/user';
import type { BlockedData } from '@shared/database/mixin/blocked';
import { broadcast } from './broadcast';
import type { ClientProfil, ClientMessage } from './chat_types';
import { sendPrivMessage } from './sendPrivMessage';
import { sendBlocked } from './sendBlocked';
import { sendInvite } from './sendInvite';
import { getUserByName } from './getUserByName';
import { makeProfil } from './makeProfil';
import { isBlocked } from './isBlocked';
import { sendProfil } from './sendProfil';
import { setGameLink } from './setGameLink';
import { nextGame_SocketListener } from './nextGame_SocketListener';
import { list_SocketListener } from './list_SocketListener';
// colors for console.log
export const color = {
@ -42,22 +34,6 @@ interface ClientInfo {
function setAboutPlayer(about: string): string {
if (!about) {
about = 'Player is good Shape - This is a default description';
}
return about;
};
// function setGameLink(link: string): string {
// if (!link) {
// link = '<a href=\'https://google.com\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>Click me</a>';
// }
// return link;
// };
export const clientChat = new Map<string, ClientInfo>();
// @ts-expect-error: import.meta.glob is a vite thing. Typescript doesn't know this...
@ -98,27 +74,14 @@ export { app };
declare module 'fastify' {
interface FastifyInstance {
io: Server<{
hello: (message: string) => string;
MsgObjectServer: (data: { message: ClientMessage }) => void;
privMessage: (data: string) => void;
profilMessage: (data: ClientProfil) => void;
inviteGame: (data: ClientProfil) => void;
blockUser: (data: ClientProfil) => void;
privMessageCopy: (msg: string) => void;
nextGame: (nextGame: string) => void;
message: (msg: string) => void;
listBud: (msg: string) => void;
client_entered: (userName: string, user: string) => void;
client_left: (userName: string, why: string) => void;
list: (oldUser: string, user: string) => void;
updateClientName: (oldUser: string, user: string) => void;
}>;
}
}
async function onReady(fastify: FastifyInstance) {
// shows address for connection au server transcendance
const session = process.env.SESSION_MANAGER ?? '';
if (session) {
@ -131,311 +94,19 @@ async function onReady(fastify: FastifyInstance) {
fastify.io.on('connection', (socket: Socket) => {
socket.on('message', (message: string) => {
//console.info(color.blue, 'DEBUG LOG: Socket connected!', color.reset, socket.id);
// console.log( color.blue, 'DEBUG LOG: Received message from client', color.reset, message);
const obj: ClientMessage = JSON.parse(message) as ClientMessage;
clientChat.set(socket.id, { user: obj.user, lastSeen: Date.now() });
// console.log(color.green, 'DEBUG LOG: Message from client', color.reset, `Sender: login name: ${obj.user} - windowID ${obj.SenderWindowID} - text message: ${obj.text}`);
socket.emit('welcome', {msg: 'Welcome to the chat! : '});
// Send object directly — DO NOT wrap it in a string
broadcast(fastify, obj, obj.SenderWindowID);
// console.log(color.red, 'DEBUG LOG: connected in the Chat :', connectedUser(fastify.io), color.reset);
});
nextGame_SocketListener(fastify, socket);
list_SocketListener(fastify, socket);
// socket.on('list', (object) => {
// const userFromFrontend = object || null;
// const client = clientChat.get(socket.id) || null;
// //console.log(color.red, 'DEBUG LOG: list activated', userFromFrontend, color.reset, socket.id);
// if (userFromFrontend.oldUser !== userFromFrontend.user) {
// //console.log(color.red, 'DEBUG LOG: list activated', userFromFrontend.oldUser, color.reset);
// // if (client?.user === null) {
// // console.log('ERROR: clientName is NULL');
// // return;
// // };
// if (client) {
// client.user = userFromFrontend.user;
// }
// }
// connectedUser(fastify.io, socket.id);
// });
socket.on('updateClientName', (object) => {
const userFromFrontend = object || null;
const client = clientChat.get(socket.id) || null;
// console.log(color.red, 'DEBUG LOG: whoAMi activated', userFromFrontend, color.reset, socket.id);
if (userFromFrontend.oldUser !== userFromFrontend.user) {
// console.log(color.red, 'DEBUG LOG: whoAMi activated', userFromFrontend.oldUser, color.reset);
// if (client === null) {
// console.log('ERROR: clientName is NULL');
// return;
// };
if (client) {
client.user = userFromFrontend.user;
console.log(color.green, `'DEBUG LOG: client.user is, '${client.user}'`);
}
}
});
socket.on('logout', () => {
const clientInfo = clientChat.get(socket.id);
const clientName = clientInfo?.user;
if (!clientName) return;
console.log(color.green, `Client logging out: ${clientName} (${socket.id})`);
const obj = {
command: '',
destination: 'system-info',
type: 'chat' as const,
user: clientName,
token: '',
text: 'LEFT the chat',
timestamp: Date.now(),
SenderWindowID: socket.id,
};
broadcast(fastify, obj, socket.id);
// Optional: remove from map
clientChat.delete(socket.id);
// Ensure socket is fully disconnected
if (socket.connected) socket.disconnect(true);
});
socket.on('disconnecting', (reason) => {
const clientName = clientChat.get(socket.id)?.user || null;
console.log(
color.green,
`Client disconnecting: ${clientName} (${socket.id}) reason:`,
reason,
);
if (reason === 'transport error') return;
if (clientName !== null) {
const obj = {
command: '',
destination: 'system-info',
type: 'chat',
user: clientName,
token: '',
text: 'LEFT the chat',
timestamp: Date.now(),
SenderWindowID: socket.id,
};
broadcast(fastify, obj, obj.SenderWindowID);
}
});
socket.on('client_left', (data) => {
const clientName = clientChat.get(socket.id)?.user || null;
const leftChat = data || null;
console.log(
color.green,
`Left the Chat User: ${clientName} id Socket: ${socket.id} reason:`,
leftChat.why,
);
if (clientName !== null) {
const obj = {
command: '',
destination: 'system-info',
type: 'chat',
user: clientName,
token: '',
text: 'LEFT the chat but the window is still open',
timestamp: Date.now(),
SenderWindowID: socket.id,
};
//console.log(color.blue, 'DEBUG LOG: BROADCASTS OUT :', obj.SenderWindowID);
broadcast(fastify, obj, obj.SenderWindowID);
// clientChat.delete(obj.user);
}
});
socket.on('privMessage', (data) => {
const clientName: string = clientChat.get(socket.id)?.user || '';
const prvMessage: ClientMessage = JSON.parse(data) || '';
console.log(
color.blue,
`DEBUG LOG: ClientName: '${clientName}' id Socket: '${socket.id}' target Name:`,
prvMessage.command,
);
if (clientName !== null) {
const obj = {
command: prvMessage.command,
destination: 'privateMsg',
type: 'chat',
user: clientName,
token: '',
text: prvMessage.text,
timestamp: Date.now(),
SenderWindowID: socket.id,
};
// console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID);
sendPrivMessage(fastify, obj, obj.SenderWindowID);
// clientChat.delete(obj.user);
}
});
socket.on('profilMessage', async (data: string) => {
const clientName: string = clientChat.get(socket.id)?.user || '';
const profilMessage: ClientMessage = JSON.parse(data) || '';
const users: User[] = fastify.db.getAllUsers() ?? [];
// console.log(color.yellow, 'DEBUG LOG: ALL USERS EVER CONNECTED:', users);
// console.log(color.blue, `DEBUG LOG: ClientName: '${clientName}' id Socket: '${socket.id}' target profil:`, profilMessage.user);
const profile: ClientProfil = await makeProfil(fastify, profilMessage.user, socket);
if (clientName !== null) {
const testuser: User | null = getUserByName(users, profilMessage.user);
console.log(color.yellow, 'user:', testuser?.name ?? 'Guest');
console.log(color.blue, 'DEBUG - profil message MESSAGE OUT :', profile.SenderWindowID);
sendProfil(fastify, profile, profile.SenderWindowID);
// clientChat.delete(obj.user);
}
});
socket.on('inviteGame', async (data: string) => {
const clientName: string = clientChat.get(socket.id)?.user || '';
const profilInvite: ClientProfil = JSON.parse(data) || '';
// const users: User[] = fastify.db.getAllUsers() ?? [];
const inviteHtml: string = 'invites you to a game ' + setGameLink('');
if (clientName !== null) {
// const testuser: User | null = getUserByName(users, profilInvite.user ?? '');
// console.log(color.yellow, 'user:', testuser?.name ?? 'Guest');
sendInvite(fastify, inviteHtml, profilInvite);
}
});
socket.on('blockUser', async (data: string) => {
const clientName: string = clientChat.get(socket.id)?.user || '';
const profilBlock: ClientProfil = JSON.parse(data) || '';
const users: User[] = fastify.db.getAllUsers() ?? [];
const UserToBlock: User | null = getUserByName(users, `${profilBlock.user}`);
const UserAskingToBlock: User | null = getUserByName(users, `${profilBlock.SenderName}`);
console.log(color.yellow, `user to block: ${profilBlock.user}`);
console.log(color.yellow, UserToBlock);
console.log(color.yellow, `user Asking to block: ${profilBlock.SenderName}`);
console.log(color.yellow, UserAskingToBlock);
const usersBlocked: BlockedData[] = fastify.db.getAllBlockedUsers() ?? [];
if (!UserAskingToBlock || !UserToBlock || !usersBlocked) return;
const userAreBlocked: boolean = isBlocked(UserAskingToBlock, UserToBlock, usersBlocked);
if (userAreBlocked) {
console.log(color.green, 'Both users are blocked as requested');
// return true; // or any other action you need to take
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);
if (clientName !== null) {
const blockedMessage = `'I have un-blocked you'`;
if (clientName !== null) {
const obj = {
command: 'message',
destination: 'privateMsg',
type: 'chat',
user: clientName,
token: '',
text: '',
timestamp: Date.now(),
SenderWindowID: socket.id,
Sendertext: 'You have un-blocked',
};
// console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID);
socket.emit('privMessageCopy', `${obj.Sendertext}: ${UserToBlock.name}💚`);
// clientChat.delete(obj.user);
}
// profilBlock.Sendertext = `'You have un-blocked '`;
sendBlocked(fastify, blockedMessage, profilBlock);
}
} else {
console.log(color.red, 'The users are not blocked in this way');
console.log(color.red, "ALL BLOCKED USERS:", usersBlocked);
fastify.db.addBlockedUserFor(UserAskingToBlock!.id, UserToBlock!.id);
const usersBlocked2 = fastify.db.getAllBlockedUsers();
console.log(color.green, 'ALL BLOCKED USERS:', usersBlocked2);
if (clientName !== null) {
const blockedMessage = `'I have blocked you'`;
profilBlock.Sendertext = `'You have blocked '`;
if (clientName !== null) {
const obj = {
command: 'message',
destination: 'privateMsg',
type: 'chat',
user: clientName,
token: '',
text: '',
timestamp: Date.now(),
SenderWindowID: socket.id,
Sendertext: 'You have blocked',
};
// console.log(color.blue, 'DEBUG LOG: PRIV MESSAGE OUT :', obj.SenderWindowID);
socket.emit('privMessageCopy', `${obj.Sendertext}: ${UserToBlock.name}`);
// clientChat.delete(obj.user);
}
sendBlocked(fastify, blockedMessage, profilBlock);
}
}
});
socket.on('client_entered', (data) => {
// data may be undefined (when frontend calls emit with no payload)
const userNameFromFrontend = data?.userName || null;
const userFromFrontend = data?.user || null;
let clientName = clientChat.get(socket.id)?.user || null;
// const client = clientChat.get(socket.id) || null;
let text = 'is back in the chat';
if (clientName === null) {
console.log('ERROR: clientName is NULL'); return;
};
// if (client === null) {
// console.log('ERROR: client is NULL'); return;
// };
if (userNameFromFrontend !== userFromFrontend) {
text = `'is back in the chat, I used to be called '${userNameFromFrontend}`;
clientName = userFromFrontend;
if (clientName === null) {
console.log('ERROR: clientName is NULL'); return;
};
// if (client) {
// client.user = clientName;
// }
}
console.log(
color.green,
`Client entered the Chat: ${clientName} (${socket.id})`,
);
if (clientName !== null) {
const obj = {
command: '',
destination: 'system-info',
type: 'chat',
user: clientName,
frontendUserName: userNameFromFrontend,
frontendUser: userFromFrontend,
token: '',
text: text,
timestamp: Date.now(),
SenderWindowID: socket.id,
};
broadcast(fastify, obj, obj.SenderWindowID);
}
});
});
}

View file

@ -1,25 +0,0 @@
import { FastifyInstance } from 'fastify';
import { clientChat, color } from './app';
/**
* function broadcast a clickable link
* @param fastify
* @param gameLink
*/
export async function broadcastNextGame(fastify: FastifyInstance, gameLink?: Promise<string>) {
const link = gameLink ? await gameLink : undefined;
console.log(color.green, 'link===========> ', link);
const sockets = await fastify.io.fetchSockets();
// fastify.io.fetchSockets().then((sockets) => {
for (const socket of sockets) {
const clientInfo = clientChat.get(socket.id);
if (!clientInfo?.user) {
console.log(color.yellow, `DEBUG LOG: Skipping socket ${socket.id} (no user found)`);
continue;
}
if (link) {
socket.emit('nextGame', link);
}
// console.log(color.green, `'DEBUG LOG: Broadcast to:', ${data.command} message: ${data.text}`);
}
};

View file

@ -1,48 +0,0 @@
import { clientChat } from './app';
import { Server, Socket } from 'socket.io';
/**
* function check users connected to the chat with a socket and makes a seen list
* calls listBud socket listener to update Ping Buddies List and calls listBuddies()
* @param io
* @param target
* @returns the number connected
*/
export function connectedUser(io?: Server, target?: string): number {
let count = 0;
const seen = new Set<string>();
// <- only log/count unique usernames
for (const [socketId, username] of clientChat) {
// Basic checks
if (typeof socketId !== 'string' || socketId.length === 0) {
clientChat.delete(socketId);
continue;
}
if (typeof username.user !== 'string' || username.user.length === 0) {
clientChat.delete(socketId);
continue;
}
// If we have the io instance, attempt to validate the socket is still connected
if (io && typeof io.sockets?.sockets?.get === 'function') {
const socket = io.sockets.sockets.get(socketId) as Socket | undefined;
// If socket not found or disconnected, remove from map and skip
if (!socket || socket.disconnected) {
clientChat.delete(socketId);
continue;
}
// Skip duplicates (DO NOT delete them — just don't count)
if (seen.has(username.user)) {
continue;
}
// socket exists and is connected
seen.add(username.user);
count++;
const targetSocketId = target;
io.to(targetSocketId!).emit('listBud', username.user);
continue;
}
count++;
}
return count;
}

View file

@ -1,6 +0,0 @@
/**
/* TODO find the description info for profil / or profil game link and return
**/
export function createNextGame() {
return '<a href=\'https://localhost:8888/app/\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>The next Game is Starting click here to watch</a>';
};

View file

@ -1,12 +0,0 @@
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 getUserByName(users: User[], name: string) {
return users.find(user => user.name === name) || null;
}

View file

@ -1,17 +0,0 @@
import type { User } from '@shared/database/mixin/user';
import type { BlockedData } from '@shared/database/mixin/blocked';
/**
* function compares the four ids of two users and returns true if
* UserA1 = UserB1 and UserB1 = UserB2
* @param UserAskingToBlock
* @param UserToBlock
* @param usersBlocked
* @returns
*/
export function isBlocked(UserAskingToBlock: User, UserToBlock: User, usersBlocked: BlockedData[]): boolean {
return usersBlocked.some(blocked =>
blocked.blocked === UserToBlock?.id &&
blocked.user === UserAskingToBlock?.id);
}

View file

@ -1,29 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { Socket } from 'socket.io';
import { clientChat } from './app';
import { connectedUser } from './connectedUser';
// import { color } from './app';
export function list_SocketListener(fastify: FastifyInstance, socket: Socket) {
socket.on('list', (object) => {
const userFromFrontend = object || null;
const client = clientChat.get(socket.id) || null
//console.log(color.red, 'DEBUG LOG: list activated', userFromFrontend, color.reset, socket.id)
if (userFromFrontend.oldUser !== userFromFrontend.user) {
//console.log(color.red, 'DEBUG LOG: list activated', userFromFrontend.oldUser, color.reset);
if (client?.user === null) {
console.log('ERROR: clientName is NULL');
return;
};
if (client) {
client.user = userFromFrontend.user;
}
}
connectedUser(fastify.io, socket.id);
});
}

View file

@ -1,41 +0,0 @@
import { FastifyInstance } from 'fastify';
import type { ClientProfil } from './chat_types';
import type { User } from '@shared/database/mixin/user';
import { getUserByName } from './getUserByName';
import { Socket } from 'socket.io';
/**
* function makeProfil - translates the Users[] to a one user looking by name
* and puts it into ClientProfil format
* @param fastify
* @param user
* @param socket
* @returns
*/
export async function makeProfil(fastify: FastifyInstance, user: string, socket: Socket): Promise <ClientProfil> {
let clientProfil!: ClientProfil;
const users: User[] = fastify.db.getAllUsers() ?? [];
const allUsers: User | null = getUserByName(users, user);
// console.log(color.yellow, `DEBUG LOG: 'userFound is:'${allUsers?.name}`);
if (user === allUsers?.name) {
// console.log(color.yellow, `DEBUG LOG: 'login Name: '${allUsers.login}' user: '${user}'`);
clientProfil =
{
command: 'makeProfil',
destination: 'profilMsg',
type: 'chat' as const,
user: `${allUsers.name}`,
loginName: `${allUsers?.login ?? 'Guest'}`,
userID: `${allUsers?.id ?? ''}`,
text: '',
timestamp: Date.now(),
SenderWindowID: socket.id,
SenderName: '',
Sendertext: '',
innerHtml: '',
};
}
return clientProfil;
};

View file

@ -1,20 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { broadcastNextGame } from './broadcastNextGame';
import { Socket } from 'socket.io';
import { createNextGame } from './createNextGame';
import { sendGameLinkToChatService } from './sendGameLinkToChatService';
/**
* function listens to the socket for a nextGame emit
* once triggered it broadcasts the pop up
* TODO plug this into backend of the game Chat
* @param fastify
* @param socket
*/
export function nextGame_SocketListener(fastify: FastifyInstance, socket: Socket) {
socket.on('nextGame', () => {
const link = createNextGame();
const game: Promise<string> = sendGameLinkToChatService(link);
broadcastNextGame(fastify, game);
});
}

View file

@ -1,29 +0,0 @@
import type { ClientProfil } from './chat_types';
import { clientChat, color } from './app';
import { FastifyInstance } from 'fastify';
/**
* function looks for the online (socket) for user to block, when found send ordre to block or unblock user
* @param fastify
* @param blockedMessage
* @param profil
*/
export function sendBlocked(fastify: FastifyInstance, blockedMessage: string, profil: ClientProfil) {
fastify.io.fetchSockets().then((sockets) => {
let targetSocket;
for (const socket of sockets) {
const clientInfo: string = clientChat.get(socket.id)?.user || '';
if (clientInfo === profil.user) {
console.log(color.yellow, 'DEBUG LOG: User found online to block:', profil.user);
targetSocket = socket || '';
break;
}
}
profil.text = blockedMessage ?? '';
// console.log(color.red, 'DEBUG LOG:',profil.Sendertext);
if (targetSocket) {
targetSocket.emit('blockUser', profil);
}
});
}

View file

@ -1,7 +0,0 @@
/**
/* EXPERIMENTAL: how to send a starting game link to chat
**/
export async function sendGameLinkToChatService(link: string) :Promise<string> {
const payload = { link };
return JSON.stringify(payload);
}

View file

@ -1,39 +0,0 @@
import type { ClientMessage } from './chat_types';
import { clientChat, color } from './app';
import { FastifyInstance } from 'fastify';
/**
* function looks up the socket of a user online in the chat and sends a message
* it also sends a copy of the message to the sender
* @param fastify
* @param data
* @param sender
*/
export function sendPrivMessage(fastify: FastifyInstance, data: ClientMessage, sender?: string) {
fastify.io.fetchSockets().then((sockets) => {
const senderSocket = sockets.find(socket => socket.id === sender);
for (const socket of sockets) {
if (socket.id === sender) continue;
const clientInfo = clientChat.get(socket.id);
if (!clientInfo?.user) {
console.log(color.yellow, `DEBUG LOG: Skipping socket ${socket.id} (no user found)`);
continue;
}
const user: string = clientChat.get(socket.id)?.user ?? '';
const atUser = `@${user}`;
if (atUser !== data.command || atUser === '') {
console.log(color.yellow, `DEBUG LOG: User: '${atUser}' command NOT FOUND: '${data.command[0]}' `);
continue;
}
if (data.text !== '') {
socket.emit('MsgObjectServer', { message: data });
console.log(color.yellow, `DEBUG LOG: User: '${atUser}' command FOUND: '${data.command}' `);
if (senderSocket) {
senderSocket.emit('privMessageCopy', `${data.command}: ${data.text}🔒`);
}
}
console.log(color.green, `DEBUG LOG: 'Priv to:', ${data.command} message: ${data.text}`);
}
});
}

View file

@ -1,19 +0,0 @@
import { FastifyInstance } from 'fastify';
import type { ClientProfil } from './chat_types';
/**
* function takes a user profil and sends it to the asker by window id
* @param fastify
* @param profil
* @param SenderWindowID
*/
export function sendProfil(fastify: FastifyInstance, profil: ClientProfil, SenderWindowID?: string) {
fastify.io.fetchSockets().then((sockets) => {
const senderSocket = sockets.find(socket => socket.id === SenderWindowID);
if (senderSocket) {
// console.log(color.yellow, 'DEBUG LOG: profil.info:', profil.user);
senderSocket.emit('profilMessage', profil);
}
});
}