removed currentUsername from localstorage now its streamed from socket, some refactor like changed some socket.to(username) to io.to ( i have no idea whats de diffrence

This commit is contained in:
slawk0
2024-09-09 21:47:17 +02:00
parent ff68204eae
commit dc9aacc407
6 changed files with 37 additions and 32 deletions

View File

@@ -31,19 +31,17 @@ function initializeSocket(server) {
// open main socket connection // open main socket connection
io.on('connection', (socket) => { io.on('connection', (socket) => {
if (!socket.user) { if (!socket.user) {
console.log(socket.user);
console.log('User not authenticated');
socket.emit('socket error', 'User not authenticated') socket.emit('socket error', 'User not authenticated')
socket.disconnect(); socket.disconnect();
return; return;
} }
const username = socket.user.username; const username = socket.user.username;
// Join a room with the user's username // Join a room with the user's username
socket.join(username); socket.join(username);
io.to(username).emit('username', username);
// chat message event // chat message event
socket.on('chat message', async (msgData) => { socket.on('chat message', async (msgData) => {
const { content, recipient } = msgData; const { content, recipient } = msgData;
@@ -74,6 +72,7 @@ function initializeSocket(server) {
console.error('Error fetching inserted message:', err); console.error('Error fetching inserted message:', err);
} }
}); });
socket.on('get messages', async (recipient) => { socket.on('get messages', async (recipient) => {
const username = socket.user.username; const username = socket.user.username;
try { try {
@@ -88,11 +87,10 @@ function initializeSocket(server) {
if (result.rows.length > 0) { if (result.rows.length > 0) {
//const { username: sender, recipient: receiver, content: content, id: id } = result.rows; //const { username: sender, recipient: receiver, content: content, id: id } = result.rows;
// useless option io.to(username).emit('messages history', result.rows);
//console.log('Sending historical messages');
socket.emit('messages history', result.rows);
} else { } else {
io.emit('no messages'); io.to(username).emit('no messages');
} }
} catch (e) { } catch (e) {
console.error('Error retrieving messages:', e); console.error('Error retrieving messages:', e);

View File

@@ -3,20 +3,22 @@ const input = document.getElementById('input');
const recipientForm = document.getElementById('recipientForm'); const recipientForm = document.getElementById('recipientForm');
const recipientInput = document.getElementById('recipient'); const recipientInput = document.getElementById('recipient');
const messages = document.getElementById('messages'); const messages = document.getElementById('messages');
const error = document.getElementById('error'); const messageBox = document.getElementById('messageBox');
document.getElementById('input').placeholder = `Send message as: ${localStorage.getItem('username')}`;
let currentRecipient = null; let currentRecipient = null;
window.onload = () => { window.onload = () => {
document.getElementById('recipient').focus(); initializeRecipient();
if(!recipientInput.value){
recipientInput.focus();
}
} }
1
function initializeRecipient() { function initializeRecipient() {
const savedRecipient = localStorage.getItem('currentRecipient'); const savedRecipient = localStorage.getItem('currentRecipient');
if (savedRecipient) { if (savedRecipient) {
currentRecipient = savedRecipient; currentRecipient = savedRecipient;
recipientInput.value = savedRecipient; recipientInput.value = savedRecipient;
input.focus();
return currentRecipient; return currentRecipient;
} }
} }
@@ -54,28 +56,32 @@ async function initializeSocket() {
const initialRecipient = initializeRecipient(); const initialRecipient = initializeRecipient();
socket.emit('get messages', initialRecipient); socket.emit('get messages', initialRecipient);
}); });
let currentUsername = null;
socket.on('username', (username) => {
currentUsername = username;
document.getElementById('input').placeholder = `Send message as: ${username}`;
})
socket.on('chat message', (msg) => { socket.on('chat message', (msg) => {
console.log('Received message:', msg); console.log('Received message:', msg);
const { username, content, recipient } = msg; const { username, content, recipient } = msg;
console.log('Current recipient:', currentRecipient, 'Sender:', username, 'Recipient:', recipient); const item = document.createElement('li');
item.textContent = `${username}: ${content}`;
if (recipient === currentRecipient || username === currentRecipient) { messages.appendChild(item);
const item = document.createElement('li'); window.scrollTo(0, document.body.scrollHeight);
item.textContent = `${username}: ${content}`;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
}
}); });
// If not previous messages found on backend
socket.on('no messages', () => { socket.on('no messages', () => {
console.log('No previous messages found'); console.log('No previous messages found');
messages.innerHTML = '<p>No messages found</p>'; messages.innerHTML = '<p>No messages found</p>';
}); });
// Error messages from backend
socket.on('socket error', (msg) => { socket.on('socket error', (msg) => {
console.log('There was an error: ', msg) console.log('There was an error: ', msg)
error.innerHTML = msg; messageBox.innerHTML = msg;
messages.innerHTML = '<p>No messages found</p>';
}) })
recipientForm.addEventListener('submit', (e) => { recipientForm.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();

View File

@@ -13,11 +13,6 @@ function showPasswd() {
} }
} }
document.querySelector('form').addEventListener('submit', () => {
const username = document.getElementById('username').value;
localStorage.setItem('username', username);
})
document.getElementById('loginForm').addEventListener('submit', async (e) => { document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault() e.preventDefault()
const username = document.getElementById('username').value.trim(); const username = document.getElementById('username').value.trim();

View File

@@ -8,8 +8,11 @@
<title>Chat</title> <title>Chat</title>
<link rel="stylesheet" href="/static/stylesheet/chat.css"> <link rel="stylesheet" href="/static/stylesheet/chat.css">
</head> </head>
<body> <body>
<div>
<ul id="contacts"></ul>
</div>
<form id="recipientForm"> <form id="recipientForm">
<input id="recipient" autocomplete="off" placeholder="Enter recipient"/> <input id="recipient" autocomplete="off" placeholder="Enter recipient"/>
<button type="submit">Set recipient</button> <button type="submit">Set recipient</button>
@@ -20,7 +23,7 @@
<form id="form" action=""> <form id="form" action="">
<input id="input" autocomplete="off" placeholder="Enter message"/> <input id="input" autocomplete="off" placeholder="Enter message"/>
<p id="error"></p> <p id="messageBox"></p>
<button type="submit">Send</button> <button type="submit">Send</button>
<button type="button" id="settings" onclick="document.location.href='/settings';">Settings</button> <button type="button" id="settings" onclick="document.location.href='/settings';">Settings</button>
</form> </form>

View File

@@ -128,3 +128,7 @@ p {
font-size: 20px; font-size: 20px;
color: #e0e0e0; color: #e0e0e0;
} }
#messageBox {
color: red;
}

View File

@@ -247,15 +247,14 @@ async function loginUser(req, res) {
req.session.username = username; req.session.username = username;
res.status(200).json({ message: 'Successfully logged in' }); res.status(200).json({ message: 'Successfully logged in' });
} else { } else {
res.send('Incorrect Username or Password!');
return res.status(401).json({ message: 'Incorrect Username or Password!'}) return res.status(401).json({ message: 'Incorrect Username or Password!'})
} }
} catch (error) { } catch (error) {
console.error('Error executing query', error); console.error('Error executing query', error);
res.status(500).send('Error executing query'); res.status(500).json({ message: 'Internal server error' });
} }
} else { } else {
res.send('Please enter Username and Password!'); res.status(400).json({ message: 'Please enter Username and Password!' });
} }
res.end(); res.end();
} }