Added Date.now ClientChat that stores user, socket id and date
This commit is contained in:
parent
ea5f997fe0
commit
f2a5285479
8 changed files with 107 additions and 48 deletions
|
|
@ -12,6 +12,33 @@ document.addEventListener('ft:pageChange', () => {
|
||||||
__socket = undefined;
|
__socket = undefined;
|
||||||
console.log("Page changed");
|
console.log("Page changed");
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
document.addEventListener("visibilitychange", async () => {
|
||||||
|
|
||||||
|
// When user leaves tab
|
||||||
|
if (document.visibilityState === "hidden") {
|
||||||
|
console.log("User LEFT this tab");
|
||||||
|
|
||||||
|
// if (__socket) {
|
||||||
|
// __socket.close();
|
||||||
|
// __socket = undefined;
|
||||||
|
// }
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// When user returns to tab → soft reload using imported HTML file
|
||||||
|
if (document.visibilityState === "visible") {
|
||||||
|
// location.reload();
|
||||||
|
//console.log(location.replace(location.href));
|
||||||
|
|
||||||
|
|
||||||
|
console.log('Chat Visible')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
function getSocket(): Socket {
|
function getSocket(): Socket {
|
||||||
if (__socket === undefined)
|
if (__socket === undefined)
|
||||||
__socket = io("wss://localhost:8888", {
|
__socket = io("wss://localhost:8888", {
|
||||||
|
|
@ -23,6 +50,10 @@ function getSocket(): Socket {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async function isLoggedIn() {
|
||||||
|
return getUser() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
||||||
|
|
@ -43,6 +74,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
};
|
};
|
||||||
socket.emit('message', JSON.stringify(message));
|
socket.emit('message', JSON.stringify(message));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for messages from the server "MsgObjectServer"
|
// Listen for messages from the server "MsgObjectServer"
|
||||||
socket.on("MsgObjectServer", (data: any) => {
|
socket.on("MsgObjectServer", (data: any) => {
|
||||||
console.log("Message Obj Recieved:", data.message);
|
console.log("Message Obj Recieved:", data.message);
|
||||||
|
|
@ -109,6 +141,11 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
console.log(`Added new message: ${text}`)
|
console.log(`Added new message: ${text}`)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
socket.on("welcome", (data) => {
|
||||||
|
addMessage(`${data.msg}`);
|
||||||
|
});
|
||||||
|
|
||||||
// Send button
|
// Send button
|
||||||
sendButton?.addEventListener("click", () => {
|
sendButton?.addEventListener("click", () => {
|
||||||
if (sendtextbox && sendtextbox.value.trim()) {
|
if (sendtextbox && sendtextbox.value.trim()) {
|
||||||
|
|
@ -141,9 +178,13 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
|
|
||||||
// Help Text button
|
// Help Text button
|
||||||
bconnected?.addEventListener("click", async () => {
|
bconnected?.addEventListener("click", async () => {
|
||||||
|
|
||||||
|
const loggedIn = await isLoggedIn();
|
||||||
|
|
||||||
|
if (loggedIn?.name === undefined) return ;
|
||||||
if (chatWindow) {
|
if (chatWindow) {
|
||||||
addMessage('@list - lists all connected users in the chat');
|
addMessage('@list - lists all connected users in the chat');
|
||||||
await socket.emit('list');
|
socket.emit('list');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
socket.on('listObj', (list: string) => {
|
socket.on('listObj', (list: string) => {
|
||||||
|
|
@ -152,6 +193,9 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Enter key to send message
|
// Enter key to send message
|
||||||
sendtextbox!.addEventListener('keydown', (event) => {
|
sendtextbox!.addEventListener('keydown', (event) => {
|
||||||
if (event.key === 'Enter') {
|
if (event.key === 'Enter') {
|
||||||
|
|
|
||||||
|
|
@ -196,6 +196,7 @@ export async function handleRoute() {
|
||||||
return navigateTo(`/login?returnTo=${encodeURIComponent(window.location.pathname)}`)
|
return navigateTo(`/login?returnTo=${encodeURIComponent(window.location.pathname)}`)
|
||||||
const app = document.getElementById('app')!;
|
const app = document.getElementById('app')!;
|
||||||
document.dispatchEvent(new CustomEvent('ft:pageChange' as any, {} as any) as any);
|
document.dispatchEvent(new CustomEvent('ft:pageChange' as any, {} as any) as any);
|
||||||
|
document.dispatchEvent(new CustomEvent('ft:tabChange' as any, {} as any) as any);
|
||||||
let ret = await executeRouteHandler(route_handler, window.location.pathname, args)
|
let ret = await executeRouteHandler(route_handler, window.location.pathname, args)
|
||||||
app.innerHTML = ret.html;
|
app.innerHTML = ret.html;
|
||||||
if (ret.postInsert) {
|
if (ret.postInsert) {
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@
|
||||||
"fastify-plugin": "^5.1.0",
|
"fastify-plugin": "^5.1.0",
|
||||||
"joi": "^18.0.2",
|
"joi": "^18.0.2",
|
||||||
"otp": "^1.1.2",
|
"otp": "^1.1.2",
|
||||||
"typebox": "^1.0.55",
|
"typebox": "^1.0.56",
|
||||||
"uuidv7": "^1.0.2"
|
"uuidv7": "^1.0.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@
|
||||||
"fastify": "^5.6.2",
|
"fastify": "^5.6.2",
|
||||||
"fastify-cli": "^7.4.1",
|
"fastify-cli": "^7.4.1",
|
||||||
"fastify-plugin": "^5.1.0",
|
"fastify-plugin": "^5.1.0",
|
||||||
"typebox": "^1.0.55"
|
"typebox": "^1.0.56"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.19.1",
|
"@types/node": "^22.19.1",
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,12 @@ declare const __SERVICE_NAME: string;
|
||||||
|
|
||||||
// Global map of clients
|
// Global map of clients
|
||||||
// key = socket, value = clientname
|
// key = socket, value = clientname
|
||||||
const clientChat = new Map<string, string>();
|
interface ClientInfo {
|
||||||
|
user: string;
|
||||||
|
lastSeen: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clientChat = new Map<string, ClientInfo>();
|
||||||
|
|
||||||
// @ts-expect-error: import.meta.glob is a vite thing. Typescript doesn't know this...
|
// @ts-expect-error: import.meta.glob is a vite thing. Typescript doesn't know this...
|
||||||
const plugins = import.meta.glob('./plugins/**/*.ts', { eager: true });
|
const plugins = import.meta.glob('./plugins/**/*.ts', { eager: true });
|
||||||
|
|
@ -79,13 +84,13 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
// <- only log/count unique usernames
|
// <- only log/count unique usernames
|
||||||
|
|
||||||
for (const [socketId, username] of clientChat) {
|
for (const [socketId, username,] of clientChat) {
|
||||||
// Basic sanity checks
|
// Basic sanity checks
|
||||||
if (typeof socketId !== 'string' || socketId.length === 0) {
|
if (typeof socketId !== 'string' || socketId.length === 0) {
|
||||||
clientChat.delete(socketId);
|
clientChat.delete(socketId);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (typeof username !== 'string' || username.length === 0) {
|
if (typeof username.user !== 'string' || username.user.length === 0) {
|
||||||
clientChat.delete(socketId);
|
clientChat.delete(socketId);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -102,17 +107,17 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip duplicates (DO NOT delete them — just don't count)
|
// Skip duplicates (DO NOT delete them — just don't count)
|
||||||
if (seen.has(username)) {
|
if (seen.has(username.user)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// socket exists and is connected
|
// socket exists and is connected
|
||||||
seen.add(username);
|
seen.add(username.user);
|
||||||
count++;
|
count++;
|
||||||
// console.log(color.green,"count: ", count);
|
// console.log(color.green,"count: ", count);
|
||||||
console.log(color.yellow, 'Client:', color.reset, username);
|
console.log(color.yellow, 'Client:', color.reset, username.user);
|
||||||
|
|
||||||
const targetSocketId = target;
|
const targetSocketId = target;
|
||||||
io.to(targetSocketId!).emit('listObj', username);
|
io.to(targetSocketId!).emit('listObj', username.user);
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
color.yellow,
|
color.yellow,
|
||||||
|
|
@ -147,8 +152,8 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
for (const s of sockets) {
|
for (const s of sockets) {
|
||||||
if (s.id !== sender) {
|
if (s.id !== sender) {
|
||||||
// Send REAL JSON object
|
// Send REAL JSON object
|
||||||
const clientName = clientChat.get(s.id) || null;
|
const clientName = clientChat.get(s.id)?.user;
|
||||||
if (clientName !== null) {
|
if (clientName !== undefined) {
|
||||||
s.emit('MsgObjectServer', { message: data });
|
s.emit('MsgObjectServer', { message: data });
|
||||||
}
|
}
|
||||||
console.log(' Target window socket ID:', s.id);
|
console.log(' Target window socket ID:', s.id);
|
||||||
|
|
@ -159,7 +164,11 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fastify.io.on('connection', (socket: Socket) => {
|
fastify.io.on('connection', (socket: Socket) => {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
socket.on('message', (message: string) => {
|
socket.on('message', (message: string) => {
|
||||||
console.info(
|
console.info(
|
||||||
color.blue,
|
color.blue,
|
||||||
|
|
@ -175,7 +184,7 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
);
|
);
|
||||||
|
|
||||||
const obj: ClientMessage = JSON.parse(message) as ClientMessage;
|
const obj: ClientMessage = JSON.parse(message) as ClientMessage;
|
||||||
clientChat.set(socket.id, obj.user);
|
clientChat.set(socket.id, { user: obj.user, lastSeen: Date.now() });
|
||||||
console.log(
|
console.log(
|
||||||
color.green,
|
color.green,
|
||||||
'Message from client',
|
'Message from client',
|
||||||
|
|
@ -192,6 +201,11 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
socket.emit("welcome", {
|
||||||
|
msg: `Welcome to the chat!`,
|
||||||
|
id: socket.id
|
||||||
|
});
|
||||||
|
|
||||||
socket.on('testend', (sock_id_cl: string) => {
|
socket.on('testend', (sock_id_cl: string) => {
|
||||||
console.log('testend received from client socket id:', sock_id_cl);
|
console.log('testend received from client socket id:', sock_id_cl);
|
||||||
});
|
});
|
||||||
|
|
@ -205,15 +219,15 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
const clientName = clientChat.get(socket.id) || null;
|
const clientName = clientChat.get(socket.id) || null;
|
||||||
console.log(
|
console.log(
|
||||||
color.green,
|
color.green,
|
||||||
`Client disconnecting: ${clientName} (${socket.id}) reason:`,
|
`Client disconnecting: ${clientName?.user} (${socket.id}) reason:`,
|
||||||
reason,
|
reason,
|
||||||
);
|
);
|
||||||
if (reason === 'transport error') return;
|
if (reason === 'transport error') return;
|
||||||
|
|
||||||
if (clientName !== null) {
|
if (clientName?.user !== null) {
|
||||||
const obj = {
|
const obj = {
|
||||||
type: 'chat',
|
type: 'chat',
|
||||||
user: clientName,
|
user: clientName!.user,
|
||||||
token: '',
|
token: '',
|
||||||
text: 'LEFT the chat',
|
text: 'LEFT the chat',
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
|
|
|
||||||
18
src/pnpm-lock.yaml
generated
18
src/pnpm-lock.yaml
generated
|
|
@ -88,8 +88,8 @@ importers:
|
||||||
specifier: ^1.1.2
|
specifier: ^1.1.2
|
||||||
version: 1.1.2
|
version: 1.1.2
|
||||||
typebox:
|
typebox:
|
||||||
specifier: ^1.0.55
|
specifier: ^1.0.56
|
||||||
version: 1.0.55
|
version: 1.0.56
|
||||||
uuidv7:
|
uuidv7:
|
||||||
specifier: ^1.0.2
|
specifier: ^1.0.2
|
||||||
version: 1.0.2
|
version: 1.0.2
|
||||||
|
|
@ -131,8 +131,8 @@ importers:
|
||||||
specifier: ^5.1.0
|
specifier: ^5.1.0
|
||||||
version: 5.1.0
|
version: 5.1.0
|
||||||
typebox:
|
typebox:
|
||||||
specifier: ^1.0.55
|
specifier: ^1.0.56
|
||||||
version: 1.0.55
|
version: 1.0.56
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^22.19.1
|
specifier: ^22.19.1
|
||||||
|
|
@ -266,8 +266,8 @@ importers:
|
||||||
specifier: ^5.1.0
|
specifier: ^5.1.0
|
||||||
version: 5.1.0
|
version: 5.1.0
|
||||||
typebox:
|
typebox:
|
||||||
specifier: ^1.0.55
|
specifier: ^1.0.56
|
||||||
version: 1.0.55
|
version: 1.0.56
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^22.19.1
|
specifier: ^22.19.1
|
||||||
|
|
@ -3025,8 +3025,8 @@ packages:
|
||||||
resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}
|
resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
|
|
||||||
typebox@1.0.55:
|
typebox@1.0.56:
|
||||||
resolution: {integrity: sha512-TP02wN0B6tDZngprrGVu/Z9s/QUyVEmR7VIg1yEOtsqyDdXXEoQPSfWdkD2PsA2lGLxu6GgwOTtGZVS9CAoERg==}
|
resolution: {integrity: sha512-KMd1DJnIRqLUzAicpFmGqgmt+/IePCEmT/Jtywyyyn0hK6+dupQnxm7OAIn/cL/vu22jKi1XvDjDhrpatZ46kA==}
|
||||||
|
|
||||||
typescript-eslint@8.48.0:
|
typescript-eslint@8.48.0:
|
||||||
resolution: {integrity: sha512-fcKOvQD9GUn3Xw63EgiDqhvWJ5jsyZUaekl3KVpGsDJnN46WJTe3jWxtQP9lMZm1LJNkFLlTaWAxK2vUQR+cqw==}
|
resolution: {integrity: sha512-fcKOvQD9GUn3Xw63EgiDqhvWJ5jsyZUaekl3KVpGsDJnN46WJTe3jWxtQP9lMZm1LJNkFLlTaWAxK2vUQR+cqw==}
|
||||||
|
|
@ -6156,7 +6156,7 @@ snapshots:
|
||||||
media-typer: 0.3.0
|
media-typer: 0.3.0
|
||||||
mime-types: 2.1.35
|
mime-types: 2.1.35
|
||||||
|
|
||||||
typebox@1.0.55: {}
|
typebox@1.0.56: {}
|
||||||
|
|
||||||
typescript-eslint@8.48.0(eslint@9.39.1)(typescript@5.9.3):
|
typescript-eslint@8.48.0(eslint@9.39.1)(typescript@5.9.3):
|
||||||
dependencies:
|
dependencies:
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@
|
||||||
"fastify": "^5.6.2",
|
"fastify": "^5.6.2",
|
||||||
"fastify-cli": "^7.4.1",
|
"fastify-cli": "^7.4.1",
|
||||||
"fastify-plugin": "^5.1.0",
|
"fastify-plugin": "^5.1.0",
|
||||||
"typebox": "^1.0.55"
|
"typebox": "^1.0.56"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.19.1",
|
"@types/node": "^22.19.1",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue