diff --git a/index.js b/index.js index f5b57d6..83a113f 100644 --- a/index.js +++ b/index.js @@ -19,40 +19,6 @@ app.use(express.static(clientPath)); const server = http.createServer(app); -// User data -const users = []; -// Incoming user connection -app.get('/connect', (req, res) => { - // Generate id, save user - const id = crypto.randomUUID(); - users.push({ - socket: req.socket, - date: new Date(), - chats: {}, - name: "", - id - }); - // Log connection, send back id - if (consoleLogging) - console.log(`User with ID '${id}' connected.`); - res.status(200).json({ id }); -}); - -// User has disconnected -app.post('/disconnect', (req, res) => { - const { id } = req.body; - for (let i = 0; i < users.length; i++) - if (users[i].id === id) { - // If id is valid, delete all user data - if (consoleLogging) - console.log(`User with ID '${id}' disconnected.`); - users.splice(i, 1); - break; - } - // Confirm disconnect - res.status(200).send(); -}); - // Check if string is already in array function isStringUnique(arr, str) { let match = true; @@ -64,57 +30,86 @@ function isStringUnique(arr, str) { return match; } +// Generate the partial ID after username +function generatePartialID() { + return Math.floor(Math.random()*10000).toString().padStart(4, '0'); +} + + +// User data +const users = []; +// Incoming user connection +app.post('/connect', (req, res) => { + // Generate id, save user + const { name } = req.body; + let id = generatePartialID(); + const name_id = users.map(u => `${u.name}#${u.id}`); + while (!isStringUnique(name_id, `${name}#${id}`)) + id = generatePartialID(); + users.push({ + socket: req.socket, + date: new Date(), + chats: {}, + name, + id + }); + // Log connection, send back id + if (consoleLogging) + console.log(`User with ID '${name}#${id}' connected.`); + res.status(200).json({ id }); +}); + +// User has disconnected +app.post('/disconnect', (req, res) => { + const { name, id } = req.body; + for (let i = 0; i < users.length; i++) + if (users[i].name === name && users[i].id === id) { + // If id is valid, delete all user data + if (consoleLogging) + console.log(`User with ID '${name}#${id}' disconnected.`); + users.splice(i, 1); + break; + } + // Confirm disconnect + res.status(200).send(); +}); + // User wants to change name app.post('/nickname', (req, res) => { - const { id, name } = req.body; + const { oldName, name, id } = req.body; // Check if name is taken, if not, append id until unique - const usernames = users.map(u => u.name); - let currentChar = 0, newname = name; - while (!isStringUnique(usernames, newname)) { - if (newname === name) - newname += '_'; - newname += id.charAt(currentChar++); - } + const name_id = users.map(u => `${u.name}#${u.id}`); + let currentID = id; + while (!isStringUnique(name_id, `${name}#${currentID}`)) + currentID = generatePartialID(); // Change username for (const u of users) - if (u.id === id) { + if (u.name === oldName && u.id === id) { if (consoleLogging) - console.log(`(Re-)named user with ID '${id}'.`); - u.name = newname; + console.log(`(Re-)named user with ID '${oldName}#${id}'.`); + u.name = name; + u.id = currentID; break; } // Confirm renaming - res.status(200).json({ name: newname }); + res.status(200).json({ id: currentID }); }); // User is pulling messages app.post('/getChat', (req, res) => { - const { id } = req.body - - // Get users' name - let name = ""; - for (const u of users) - if (u.id === id) { - name = u.name; - break; - } - - // If no name was found, user cannot send or receive messages - if (name === "") { - res.status(401).send(); - return; - } + const { name, id } = req.body; // Go through users' chats, retrieve messages, save by username let chats = {}; + const fullName = `${name}#${id}`; for (const u of users) - if (name in u.chats) { - const len = u.chats[name].length; + if (fullName in u.chats) { + const len = u.chats[fullName].length; if (len > 0) - chats[u.name] = u.chats[name].splice(0, len); + chats[`${u.name}#${u.id}`] = u.chats[fullName].splice(0, len); } // No chat messages were found @@ -125,7 +120,7 @@ app.post('/getChat', (req, res) => { // Log if messages were delivered if (consoleLogging) - console.log(`Delivered messages to user with ID '${id}'.`); + console.log(`Delivered messages to user with ID '${fullName}'.`); // Send back data res.status(200).json(chats); @@ -133,27 +128,20 @@ app.post('/getChat', (req, res) => { // User sent new message app.post('/message', (req, res) => { - const { id, message, name } = req.body; + const { name, id, recipient, message } = req.body; // Search for senders' name, save message - let ownName; for (const u of users) - if (u.id === id) { - ownName = u.name; - if (!u.chats[name]) - u.chats[name] = []; - u.chats[name].push(message); + if (u.name === name && u.id === id) { + if (!u.chats[recipient]) + u.chats[recipient] = []; + u.chats[recipient].push(message); break; } // Log message for debugging - let user = `User '${ownName}'`; - if (!ownName) - user = ownName = "Anonymous" - if (consoleLogging) { - const idStr = (!ownName) ? ` ID: ${id}.` : ''; - console.log(`${user} sent message '${message}'.${idStr}`); - } + if (consoleLogging) + console.log(`User '${name}#${id}' sent message '${message}'.`); // Confirm process res.status(200).send(); @@ -162,25 +150,14 @@ app.post('/message', (req, res) => { // User requesting all names app.get('/getNames', (req, res) => { if (consoleLogging) - console.log('User requested all names.'); + console.log('Some user requested all names.'); - let names = [{name: "Anonymous", id: "0"}]; - for (const u of users) { - if (u.name === "") { - names[0].id = (parseInt(names[0].id) + 1).toString(); - continue; - } - names.push({ - id: u.id, - name: u.name - }); - } - if (names[0].id === "0") - names.splice(0, 1); - else - names[0].id = `${names[0].id} time(/-s)`; - - res.status(200).json(names); + res.status(200).json(users.map(u => { + return { + name: u.name, + id: u.id + }; + })); }); // Internal server error