changed from uuid + username to username + '#' + id

This commit is contained in:
Baipyrus 2023-01-20 08:13:36 +01:00
parent 27ff59e174
commit 0d9eabe32e

171
index.js
View File

@ -19,40 +19,6 @@ app.use(express.static(clientPath));
const server = http.createServer(app); 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 // Check if string is already in array
function isStringUnique(arr, str) { function isStringUnique(arr, str) {
let match = true; let match = true;
@ -64,57 +30,86 @@ function isStringUnique(arr, str) {
return match; 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 // User wants to change name
app.post('/nickname', (req, res) => { 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 // Check if name is taken, if not, append id until unique
const usernames = users.map(u => u.name); const name_id = users.map(u => `${u.name}#${u.id}`);
let currentChar = 0, newname = name; let currentID = id;
while (!isStringUnique(usernames, newname)) { while (!isStringUnique(name_id, `${name}#${currentID}`))
if (newname === name) currentID = generatePartialID();
newname += '_';
newname += id.charAt(currentChar++);
}
// Change username // Change username
for (const u of users) for (const u of users)
if (u.id === id) { if (u.name === oldName && u.id === id) {
if (consoleLogging) if (consoleLogging)
console.log(`(Re-)named user with ID '${id}'.`); console.log(`(Re-)named user with ID '${oldName}#${id}'.`);
u.name = newname; u.name = name;
u.id = currentID;
break; break;
} }
// Confirm renaming // Confirm renaming
res.status(200).json({ name: newname }); res.status(200).json({ id: currentID });
}); });
// User is pulling messages // User is pulling messages
app.post('/getChat', (req, res) => { app.post('/getChat', (req, res) => {
const { id } = req.body const { name, 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;
}
// Go through users' chats, retrieve messages, save by username // Go through users' chats, retrieve messages, save by username
let chats = {}; let chats = {};
const fullName = `${name}#${id}`;
for (const u of users) for (const u of users)
if (name in u.chats) { if (fullName in u.chats) {
const len = u.chats[name].length; const len = u.chats[fullName].length;
if (len > 0) 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 // No chat messages were found
@ -125,7 +120,7 @@ app.post('/getChat', (req, res) => {
// Log if messages were delivered // 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 '${fullName}'.`);
// Send back data // Send back data
res.status(200).json(chats); res.status(200).json(chats);
@ -133,27 +128,20 @@ app.post('/getChat', (req, res) => {
// User sent new message // User sent new message
app.post('/message', (req, res) => { app.post('/message', (req, res) => {
const { id, message, name } = req.body; const { name, id, recipient, message } = req.body;
// Search for senders' name, save message // Search for senders' name, save message
let ownName;
for (const u of users) for (const u of users)
if (u.id === id) { if (u.name === name && u.id === id) {
ownName = u.name; if (!u.chats[recipient])
if (!u.chats[name]) u.chats[recipient] = [];
u.chats[name] = []; u.chats[recipient].push(message);
u.chats[name].push(message);
break; break;
} }
// Log message for debugging // Log message for debugging
let user = `User '${ownName}'`; if (consoleLogging)
if (!ownName) console.log(`User '${name}#${id}' sent message '${message}'.`);
user = ownName = "Anonymous"
if (consoleLogging) {
const idStr = (!ownName) ? ` ID: ${id}.` : '';
console.log(`${user} sent message '${message}'.${idStr}`);
}
// Confirm process // Confirm process
res.status(200).send(); res.status(200).send();
@ -162,25 +150,14 @@ app.post('/message', (req, res) => {
// User requesting all names // User requesting all names
app.get('/getNames', (req, res) => { app.get('/getNames', (req, res) => {
if (consoleLogging) if (consoleLogging)
console.log('User requested all names.'); console.log('Some user requested all names.');
let names = [{name: "Anonymous", id: "0"}]; res.status(200).json(users.map(u => {
for (const u of users) { return {
if (u.name === "") { name: u.name,
names[0].id = (parseInt(names[0].id) + 1).toString(); id: u.id
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);
}); });
// Internal server error // Internal server error