diff --git a/frontend/src/pages/chat/chat.ts b/frontend/src/pages/chat/chat.ts index 92c0aaa..3fda3e7 100644 --- a/frontend/src/pages/chat/chat.ts +++ b/frontend/src/pages/chat/chat.ts @@ -48,6 +48,165 @@ export function getSocket(): Socket { return __socket; }; +function inviteToPlayPong(profil: ClientProfil, senderSocket: Socket) { + profil.SenderName = getUser()?.name ?? ''; + if (profil.SenderName === profil.user) return; + addMessage(`You invited to play: ${profil.user}🏓`) + senderSocket.emit('inviteGame', JSON.stringify(profil)); +}; + +function actionBtnPopUpInvite(invite: ClientProfil, senderSocket: Socket) { + setTimeout(() => { + const InvitePongBtn = document.querySelector("#popup-b-invite"); + InvitePongBtn?.addEventListener("click", () => { + inviteToPlayPong(invite, senderSocket); + }); + }, 0) +}; + +async function windowStateVisable() { + + const buddies = document.getElementById('div-buddies') as HTMLDivElement; + const socketId = __socket || undefined; + let oldName = localStorage.getItem("oldName") || undefined; + + if (socketId === undefined || oldName === undefined) {return;}; + let user = await updateUser(); + if(user === null) return; + socketId.emit('client_entered', { + userName: oldName, + user: user?.name, + }); + buddies.innerHTML = ''; + buddies.textContent = ''; + setTitle('Chat Page'); + return; +}; + +function parseCmdMsg(msgText: string): string[] | undefined { + + if (!msgText?.trim()) return; + msgText = msgText.trim(); + const command: string[] = ['', '']; + if (!msgText.startsWith('@')) { + command[0] = '@msg'; + command[1] = msgText; + return command; + } + const noArgCommands = ['@quit', '@help', '@cls']; + if (noArgCommands.includes(msgText)) { + command[0] = msgText; + command[1] = ''; + return command; + } + + const ArgCommands = ['@profile', '@block']; + const userName = msgText.indexOf(" "); + const cmd2 = msgText.slice(0, userName).trim() ?? ""; + const user = msgText.slice(userName + 1).trim(); + if (ArgCommands.includes(cmd2)) { + command[0] = cmd2; + command[1] = user; + return command; + } + const colonIndex = msgText.indexOf(":"); + if (colonIndex === -1) { + command[0] = msgText; + command[1] = ''; + return command; + } + const cmd = msgText.slice(0, colonIndex).trim(); + const rest = msgText.slice(colonIndex + 1).trim(); + command[0] = cmd; + command[1] = rest; + return command; +} + +function waitSocketConnected(socket: Socket): Promise { + return new Promise(resolve => { + if (socket.connected) return resolve(); + socket.on("connect", () => resolve()); + }); +}; + +function quitChat (socket: Socket) { + + try { + const systemWindow = document.getElementById('system-box') as HTMLDivElement; + const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement; + if (socket) { + logout(socket); + setTitle('Chat Page'); + connected(socket); + } else { + getSocket(); + } + } catch (e) { + showError('Failed to Quit Chat: Unknown error'); + } + +}; + +function logout(socket: Socket) { + socket.emit("logout"); // notify server + socket.disconnect(); // actually close the socket + localStorage.clear(); + if (__socket !== undefined) + __socket.close(); +}; + + +async function connected(socket: Socket): Promise { + + setTimeout(async () => { + try { + const buddies = document.getElementById('div-buddies') as HTMLDivElement; + const loggedIn = isLoggedIn(); + if (!loggedIn) throw('Not Logged in'); + let oldUser = localStorage.getItem("oldName") ?? ""; + if (loggedIn?.name === undefined) {return ;}; + oldUser = loggedIn.name ?? ""; + // const res = await client.guestLogin(); + let user = await updateUser(); + localStorage.setItem("oldName", oldUser); + buddies.textContent = ""; + socket.emit('list', { + oldUser: oldUser, + user: user?.name, + }); + } catch (e) { + showError('Failed to login: Unknown error'); + } + }, 16); + }; + +let count = 0; +function incrementCounter(): number { + count += 1; + return count; +} + +async function openMessagePopup(message: any) { + + const modalmessage = document.getElementById("modal-message") ?? null; + if(!message) return + const obj = message; + if (modalmessage) { + const messageElement = document.createElement("div"); + messageElement.innerHTML = ` +
Next Game Message ${incrementCounter()}: ${obj.nextGame}
+ `; + modalmessage.appendChild(messageElement); + modalmessage.scrollTop = modalmessage.scrollHeight; + + } + const gameMessage = document.getElementById("game-modal") ?? null; + if (gameMessage) { + gameMessage.classList.remove("hidden"); + } +} + function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn { let socket = getSocket(); let blockMessage: boolean; diff --git a/src/chat/src/routes/broadcast.ts b/src/chat/src/routes/broadcast.ts index e33cbed..d795dfd 100644 --- a/src/chat/src/routes/broadcast.ts +++ b/src/chat/src/routes/broadcast.ts @@ -1,5 +1,6 @@ import { FastifyPluginAsync } from 'fastify'; import { Static, Type } from 'typebox'; +import { broadcastNextGame} from '../broadcastNextGame'; export const ChatReq = Type.Object({ message: Type.String(), @@ -7,46 +8,42 @@ export const ChatReq = Type.Object({ export type ChatReq = Static; -const route: FastifyPluginAsync = async (fastify): Promise => { - fastify.post<{ Body: ChatReq }>( - '/api/chat/broadcast', - { - schema: { - body: ChatReq, - hide: true, - }, - config: { requireAuth: false }, - }, - async function(req, res) { - // broadcast(this, { command: '', destination: '', user: 'CMwaLeSever!!', text: req.body.message, SenderWindowID: 'server' }); - void res; - }, - ); -}; -export default route; - // const route: FastifyPluginAsync = async (fastify): Promise => { -// fastify.post('/api/chat/broadcast', { -// schema: { -// body: { -// type: 'object', -// required: ['nextGame'], -// properties: { -// nextGame: { type: 'string' } -// } -// } -// } -// }, async (req, reply) => { - -// // Body only contains nextGame now -// const gameLink: Promise = Promise.resolve(req.body as string ); - -// // Broadcast nextGame -// if (gameLink) -// broadcastNextGame(fastify, gameLink); - -// return reply.send({ status: 'ok' }); -// }); +// fastify.post<{ Body: ChatReq }>( +// '/api/chat/broadcast', +// { +// schema: { +// body: ChatReq, +// hide: true, +// }, +// config: { requireAuth: false }, +// }, +// async function(req, res) { +// // broadcast(this, { command: '', destination: '', user: 'CMwaLeSever!!', text: req.body.message, SenderWindowID: 'server' }); +// void res; +// }, +// ); // }; // export default route; +const route: FastifyPluginAsync = async (fastify): Promise => { + fastify.post('/api/chat/broadcast', { + schema: { + body: { + type: 'object', + required: ['nextGame'], + properties: { + nextGame: { type: 'string' } + } + } + } +}, async (req, reply) => { + const gameLink: Promise = Promise.resolve(req.body as string ); + if (gameLink) + broadcastNextGame(fastify, gameLink); + + return reply.send({ status: 'ok' }); +}); +}; +export default route; +