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

View File

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

View File

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

View File

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

View File

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