diff --git a/app.js b/app.js index 40b0888..f771de0 100644 --- a/app.js +++ b/app.js @@ -14,6 +14,7 @@ const drive = new Hyperdrive(store); await drive.ready(); let swarm; +let peerCount = 0; let activeRooms = []; const eventEmitter = new EventEmitter(); @@ -31,12 +32,6 @@ let config = { // Store messages for each room let messagesStore = {}; -// Store peer counts for each room -let peerCounts = {}; - -// Map to store discovery instances and their associated topics -const discoveryTopicsMap = new Map(); - // Function to get a random port between 49152 and 65535 function getRandomPort() { return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; @@ -130,7 +125,6 @@ async function initialize() { if (messageObj.type === 'icon') { const username = messageObj.username; - const topic = messageObj.topic; if (messageObj.avatar) { const avatarBuffer = b4a.from(messageObj.avatar, 'base64'); await drive.put(`/icons/${username}.png`, avatarBuffer); @@ -138,7 +132,6 @@ async function initialize() { } else { console.error('Received icon message with missing avatar data:', messageObj); } - // updatePeerCount(topic); } else if (messageObj.type === 'file') { if (messageObj.file && messageObj.fileName) { const fileBuffer = b4a.from(messageObj.file, 'base64'); @@ -162,61 +155,31 @@ async function initialize() { }); swarm.on('connection', async (connection, info) => { - try { - connection.on('data', (data) => { - const messageObj = JSON.parse(data.toString()); - if (messageObj.type === 'icon' && messageObj.topic) { - connection.topic = messageObj.topic; - if (!peerCounts[messageObj.topic]) { - peerCounts[messageObj.topic] = 0; - } - peerCounts[messageObj.topic]++; - updateHeaderPeerCount(messageObj.topic); - } - eventEmitter.emit('onMessage', messageObj); + peerCount++; + updatePeerCount(); + console.log('Peer connected, current peer count:', peerCount); + + // Send the current user's icon to the new peer + const iconBuffer = await drive.get(`/icons/${config.userName}.png`); + if (iconBuffer) { + const iconMessage = JSON.stringify({ + type: 'icon', + username: config.userName, + avatar: b4a.toString(iconBuffer, 'base64'), }); - - connection.on('close', () => { - const topic = connection.topic; - if (topic && peerCounts[topic]) { - peerCounts[topic]--; - updateHeaderPeerCount(topic); - console.log('Peer disconnected, current peer count:', peerCounts[topic]); - } - }); - - // Sending current user's topic to the new peer - const currentTopic = document.querySelector('#chat-room-topic').innerText; - connection.topic = currentTopic; - - if (!peerCounts[currentTopic]) { - peerCounts[currentTopic] = 0; - } - peerCounts[currentTopic]++; - updateHeaderPeerCount(currentTopic); - console.log('Peer connected, current peer count:', peerCounts[currentTopic]); - - // Send the current user's icon to the new peer - const iconBuffer = await drive.get(`/icons/${config.userName}.png`); - if (iconBuffer) { - const iconMessage = JSON.stringify({ - type: 'icon', - username: config.userName, - avatar: b4a.toString(iconBuffer, 'base64'), - topic: currentTopic - }); - connection.write(iconMessage); - } else { - const iconMessage = JSON.stringify({ - type: 'icon', - username: config.userName, - topic: currentTopic - }); - connection.write(iconMessage); - } - } catch (error) { - console.error('Error handling connection:', error); + connection.write(iconMessage); } + + connection.on('data', (data) => { + const messageObj = JSON.parse(data.toString()); + eventEmitter.emit('onMessage', messageObj); + }); + + connection.on('close', () => { + peerCount--; + updatePeerCount(); + console.log('Peer disconnected, current peer count:', peerCount); + }); }); swarm.on('error', (err) => { @@ -367,10 +330,6 @@ async function joinSwarm(topicBuffer) { await discovery.flushed(); activeRooms.push({ topic, discovery }); - peerCounts[topic] = 0; // Initialize peer count for the new room - - // Store the topic in the map - discoveryTopicsMap.set(discovery, topic); console.log('Joined room:', topic); // Debugging log @@ -384,13 +343,9 @@ async function joinSwarm(topicBuffer) { function addRoomToList(topic) { const roomList = document.querySelector('#room-list'); const roomItem = document.createElement('li'); + roomItem.textContent = truncateHash(topic); roomItem.dataset.topic = topic; - const roomName = document.createElement('span'); - roomName.textContent = truncateHash(topic); - - roomItem.appendChild(roomName); - roomItem.addEventListener('dblclick', () => enterEditMode(roomItem)); roomItem.addEventListener('click', () => switchRoom(topic)); roomList.appendChild(roomItem); @@ -478,9 +433,6 @@ function switchRoom(topic) { // Show chat UI elements document.querySelector('#chat').classList.remove('hidden'); document.querySelector('#setup').classList.add('hidden'); - - // Update the peer count in the header - updateHeaderPeerCount(topic); } function leaveRoom(topic) { @@ -489,7 +441,6 @@ function leaveRoom(topic) { const room = activeRooms[roomIndex]; room.discovery.destroy(); activeRooms.splice(roomIndex, 1); - discoveryTopicsMap.delete(room.discovery); } const roomItem = document.querySelector(`li[data-topic="${topic}"]`); @@ -617,11 +568,10 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) { } } -function updateHeaderPeerCount(topic) { +function updatePeerCount() { const peerCountElement = document.querySelector('#peers-count'); if (peerCountElement) { - const peerCount = peerCounts[topic] || 0; - peerCountElement.textContent = peerCount; + peerCountElement.textContent = peerCount; // Display the actual peer count } } @@ -632,13 +582,12 @@ function scrollToBottom() { function onMessageAdded(from, message, avatar, topic) { console.log('Adding message:', { from, message, avatar, topic }); // Debugging log - const messageObj = { from, message, avatar }; - + // Add the message to the store addMessageToStore(topic, messageObj); @@ -663,24 +612,19 @@ function onMessageAdded(from, message, avatar, topic) { const $text = document.createElement('div'); $text.classList.add('message-text'); - if (typeof message === 'string') { - const md = window.markdownit({ - highlight: function (str, lang) { - if (lang && hljs.getLanguage(lang)) { - try { - return hljs.highlight(str, { language: lang }).value; - } catch (__) {} - } - return ''; // use external default escaping + const md = window.markdownit({ + highlight: function (str, lang) { + if (lang && hljs.getLanguage(lang)) { + try { + return hljs.highlight(str, { language: lang }).value; + } catch (__) {} } - }); + return ''; // use external default escaping + } + }); - const markdownContent = md.render(message); - $text.innerHTML = markdownContent; - } else { - console.error('Message content is not a string:', message); - $text.textContent = 'Invalid message content.'; - } + const markdownContent = md.render(message); + $text.innerHTML = markdownContent; $content.appendChild($header); $content.appendChild($text); @@ -800,6 +744,7 @@ function renderMessagesForRoom(topic) { onMessageAdded(message.from, message.message, message.avatar, topic); }); } + function getMessagesForRoom(topic) { return messagesStore[topic] || []; }