more/better comments, splitting up functions and fixing chat output

This commit is contained in:
Baipyrus 2023-01-19 12:57:44 +01:00
parent 0ffc9c16a2
commit 3832413c23

View File

@ -1,11 +1,16 @@
// Global logging toggles
const fileLogging = false; const fileLogging = false;
const consoleLogging = true; const consoleLogging = true;
// Imports
const fs = require('fs'); const fs = require('fs');
const http = require('http'); const http = require('http');
const crypto = require('crypto'); const crypto = require('crypto');
const express = require('express'); const express = require('express');
// Global server setup
const app = express(); const app = express();
const clientPath = __dirname+'/../html'; const clientPath = __dirname+'/../html';
console.log('Serving static from ' + clientPath); console.log('Serving static from ' + clientPath);
@ -13,8 +18,12 @@ app.use(express.json());
app.use(express.static(clientPath)); app.use(express.static(clientPath));
const server = http.createServer(app); const server = http.createServer(app);
// User data
const users = []; const users = [];
// Incoming user connection
app.get('/connect', (req, res) => { app.get('/connect', (req, res) => {
// Generate id, save user
const id = crypto.randomUUID(); const id = crypto.randomUUID();
users.push({ users.push({
socket: req.socket, socket: req.socket,
@ -23,26 +32,32 @@ app.get('/connect', (req, res) => {
name: "", name: "",
id id
}); });
// Log connection, send back id
if (consoleLogging) if (consoleLogging)
console.log(`User with ID '${id}' connected.`); console.log(`User with ID '${id}' connected.`);
res.status(200).json({ id }); res.status(200).json({ id });
}); });
// User has disconnected
app.post('/disconnect', (req, res) => { app.post('/disconnect', (req, res) => {
const { id } = req.body; const { id } = req.body;
for (let i = 0; i < users.length; i++) for (let i = 0; i < users.length; i++)
if (users[i].id === id) { if (users[i].id === id) {
// If id is valid, delete all user data
if (consoleLogging) if (consoleLogging)
console.log(`User with ID '${id}' disconnected.`); console.log(`User with ID '${id}' disconnected.`);
users.splice(i, 1); users.splice(i, 1);
break; break;
} }
// Confirm disconnect
res.status(200).send(); res.status(200).send();
}); });
// User wants to change name
app.post('/nickname', (req, res) => { app.post('/nickname', (req, res) => {
const { id, name } = req.body; const { id, name } = req.body;
// Check if name is taken
let success = true; let success = true;
for (const u of users) for (const u of users)
if (u.name === name) { if (u.name === name) {
@ -51,6 +66,7 @@ app.post('/nickname', (req, res) => {
} }
if (success) { if (success) {
// Change name if not taken
for (const u of users) for (const u of users)
if (u.id === id) { if (u.id === id) {
if (consoleLogging) if (consoleLogging)
@ -60,12 +76,15 @@ app.post('/nickname', (req, res) => {
} }
} }
// Confirm renaming
res.status(200).json({ success }); res.status(200).json({ success });
}); });
// User is pulling messages
app.post('/getChat', (req, res) => { app.post('/getChat', (req, res) => {
const { id } = req.body const { id } = req.body
// Get users' name
let name = ""; let name = "";
for (const u of users) for (const u of users)
if (u.id === id) { if (u.id === id) {
@ -73,11 +92,13 @@ app.post('/getChat', (req, res) => {
break; break;
} }
// If no name was found, user cannot send or receive messages
if (name === "") { if (name === "") {
res.status(401).send(); res.status(401).send();
return; return;
} }
// Go through users' chats, retrieve messages, save by username
let chats = {}; let chats = {};
for (const u of users) for (const u of users)
if (name in u.chats) { if (name in u.chats) {
@ -86,19 +107,25 @@ app.post('/getChat', (req, res) => {
chats[u.name] = u.chats[name].splice(0, len); chats[u.name] = u.chats[name].splice(0, len);
} }
// No chat messages were found
if (Object.keys(chats).length === 0) { if (Object.keys(chats).length === 0) {
res.status(204).send(); res.status(204).send();
return; return;
} }
// Log if messages were delivered
if (consoleLogging) if (consoleLogging)
console.log(`Delivered messages to user with ID '${id}'.`); console.log(`Delivered messages to user with ID '${id}'.`);
// Send back data
res.status(200).json(chats); res.status(200).json(chats);
}); });
// User sent new message
app.post('/message', (req, res) => { app.post('/message', (req, res) => {
const { id, message, name } = req.body; const { id, message, name } = req.body;
// Search for senders' name, save message
let ownName; let ownName;
for (const u of users) for (const u of users)
if (u.id === id) { if (u.id === id) {
@ -109,6 +136,7 @@ app.post('/message', (req, res) => {
break; break;
} }
// Log message for debugging
let user = `User '${ownName}'`; let user = `User '${ownName}'`;
if (!ownName) if (!ownName)
user = ownName = "Anonymous" user = ownName = "Anonymous"
@ -117,17 +145,21 @@ app.post('/message', (req, res) => {
console.log(`${user} sent message '${message}'.${idStr}`); console.log(`${user} sent message '${message}'.${idStr}`);
} }
// Confirm process
res.status(200).send(); res.status(200).send();
}); });
// Internal server error
server.on('error', err => { server.on('error', err => {
console.error('Internal server error', err); console.error('Internal server error', err);
}); });
// Server has closed
server.on('close', () => { server.on('close', () => {
console.log("Shutting down ..."); console.log('Shutting down server ...');
}); });
// Listen on port 3000 for webserver connection
server.listen(3000, () => { server.listen(3000, () => {
console.log('Server running on port 3000'); console.log('Server running on port 3000');
}); });