From b1ea06018bffeef05ab4fee938a78f899ace01e4 Mon Sep 17 00:00:00 2001 From: Raven Scott Date: Thu, 13 Jun 2024 21:05:10 -0400 Subject: [PATCH] Using swarm.connections.size --- app.js | 286 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 149 insertions(+), 137 deletions(-) diff --git a/app.js b/app.js index d90279f..bf83784 100644 --- a/app.js +++ b/app.js @@ -14,7 +14,6 @@ const drive = new Hyperdrive(store); await drive.ready(); let swarm; -let peerCount = 0; let activeRooms = []; const eventEmitter = new EventEmitter(); @@ -46,151 +45,28 @@ async function initialize() { await serve.ready(); console.log('Listening on http://localhost:' + serve.address().port); - const registerForm = document.querySelector('#register-form'); - const selectAvatarButton = document.querySelector('#select-avatar'); - const createChatRoomButton = document.querySelector('#create-chat-room'); - const joinChatRoomButton = document.querySelector('#join-chat-room'); - const messageForm = document.querySelector('#message-form'); - const toggleSetupBtn = document.querySelector('#toggle-setup-btn'); - const removeRoomBtn = document.querySelector('#remove-room-btn'); - const attachFileButton = document.getElementById('attach-file'); - const fileInput = document.getElementById('file-input'); - const talkButton = document.getElementById('talk-btn'); - - if (registerForm) { - registerForm.addEventListener('submit', registerUser); - } - if (selectAvatarButton) { - selectAvatarButton.addEventListener('click', () => { - document.querySelector('#avatar-file').click(); - }); - } - if (createChatRoomButton) { - createChatRoomButton.addEventListener('click', createChatRoom); - } - if (joinChatRoomButton) { - joinChatRoomButton.addEventListener('click', joinChatRoom); - } - if (messageForm) { - messageForm.addEventListener('submit', sendMessage); - } - if (toggleSetupBtn) { - toggleSetupBtn.addEventListener('click', toggleSetupView); - } - if (removeRoomBtn) { - removeRoomBtn.addEventListener('click', () => { - const topic = document.querySelector('#chat-room-topic').innerText; - leaveRoom(topic); - }); - } - if (attachFileButton) { - attachFileButton.addEventListener('click', () => fileInput.click()); - } - if (fileInput) { - fileInput.addEventListener('change', handleFileInput); - } - if (talkButton) { - setupTalkButton(); - } + // Event listeners setup + setupEventListeners(); const configExists = fs.existsSync("./config.json"); if (configExists) { - config = JSON.parse(fs.readFileSync("./config.json", 'utf8')); - console.log("Read config from file:", config); - // Update port in URLs - config.userAvatar = updatePortInUrl(config.userAvatar); - config.rooms.forEach(room => { - room.alias = room.alias || truncateHash(room.topic); - }); - for (let user in config.registeredUsers) { - config.registeredUsers[user] = updatePortInUrl(config.registeredUsers[user]); - } - - renderRoomList(); // Render the room list with aliases - - // Connect to all rooms on startup - for (const room of config.rooms) { - const topicBuffer = b4a.from(room.topic, 'hex'); - await joinSwarm(topicBuffer); - } + loadConfigFromFile(); + renderRoomList(); + await connectToAllRooms(); } - const registerDiv = document.querySelector('#register'); - if (registerDiv && !configExists) { - registerDiv.classList.remove('hidden'); + if (!configExists) { + document.querySelector('#register').classList.remove('hidden'); } eventEmitter.on('onMessage', async (messageObj) => { - console.log('Received message:', messageObj); // Debugging log - - if (messageObj.type === 'icon') { - const username = messageObj.username; - if (messageObj.avatar) { - const avatarBuffer = b4a.from(messageObj.avatar, 'base64'); - await drive.put(`/icons/${username}.png`, avatarBuffer); - updateIcon(username, avatarBuffer); - } else { - console.error('Received icon message with missing avatar data:', messageObj); - } - } else if (messageObj.type === 'file') { - if (messageObj.file && messageObj.fileName) { - const fileBuffer = b4a.from(messageObj.file, 'base64'); - await drive.put(`/files/${messageObj.fileName}`, fileBuffer); - const fileUrl = `http://localhost:${servePort}/files/${messageObj.fileName}`; - addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic); - } else { - console.error('Received file message with missing file data or fileName:', messageObj); - } - } else if (messageObj.type === 'message') { - onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar, messageObj.topic); - } else if (messageObj.type === 'audio') { - const audioBuffer = b4a.from(messageObj.audio, 'base64'); - const filePath = `/audio/${Date.now()}.webm`; - await drive.put(filePath, audioBuffer); - const audioUrl = `http://localhost:${servePort}${filePath}`; - addAudioMessage(messageObj.name, audioUrl, messageObj.avatar, messageObj.topic); - } else { - console.error('Received unknown message type:', messageObj); - } + handleIncomingMessage(messageObj); }); - swarm.on('connection', async (connection, info) => { - peerCount++; - updatePeerCount(); - console.log('Peer connected, current peer count:', peerCount); + swarm.on('connection', handleConnection); + swarm.on('error', (err) => console.error('Swarm error:', err)); + swarm.on('close', () => console.log('Swarm closed')); - // 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.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) => { - console.error('Swarm error:', err); - }); - - swarm.on('close', () => { - console.log('Swarm closed'); - }); - - // Initialize highlight.js once the DOM is fully loaded document.addEventListener("DOMContentLoaded", (event) => { hljs.highlightAll(); }); @@ -199,6 +75,119 @@ async function initialize() { } } +function setupEventListeners() { + const registerForm = document.querySelector('#register-form'); + const selectAvatarButton = document.querySelector('#select-avatar'); + const createChatRoomButton = document.querySelector('#create-chat-room'); + const joinChatRoomButton = document.querySelector('#join-chat-room'); + const messageForm = document.querySelector('#message-form'); + const toggleSetupBtn = document.querySelector('#toggle-setup-btn'); + const removeRoomBtn = document.querySelector('#remove-room-btn'); + const attachFileButton = document.getElementById('attach-file'); + const fileInput = document.getElementById('file-input'); + const talkButton = document.getElementById('talk-btn'); + + if (registerForm) { + registerForm.addEventListener('submit', registerUser); + } + if (selectAvatarButton) { + selectAvatarButton.addEventListener('click', () => { + document.querySelector('#avatar-file').click(); + }); + } + if (createChatRoomButton) { + createChatRoomButton.addEventListener('click', createChatRoom); + } + if (joinChatRoomButton) { + joinChatRoomButton.addEventListener('click', joinChatRoom); + } + if (messageForm) { + messageForm.addEventListener('submit', sendMessage); + } + if (toggleSetupBtn) { + toggleSetupBtn.addEventListener('click', toggleSetupView); + } + if (removeRoomBtn) { + removeRoomBtn.addEventListener('click', () => { + const topic = document.querySelector('#chat-room-topic').innerText; + leaveRoom(topic); + }); + } + if (attachFileButton) { + attachFileButton.addEventListener('click', () => fileInput.click()); + } + if (fileInput) { + fileInput.addEventListener('change', handleFileInput); + } + if (talkButton) { + setupTalkButton(); + } +} + +function handleIncomingMessage(messageObj) { + console.log('Received message:', messageObj); // Debugging log + + if (messageObj.type === 'icon') { + const username = messageObj.username; + if (messageObj.avatar) { + const avatarBuffer = b4a.from(messageObj.avatar, 'base64'); + drive.put(`/icons/${username}.png`, avatarBuffer).then(() => { + updateIcon(username, avatarBuffer); + }); + } else { + console.error('Received icon message with missing avatar data:', messageObj); + } + } else if (messageObj.type === 'file') { + if (messageObj.file && messageObj.fileName) { + const fileBuffer = b4a.from(messageObj.file, 'base64'); + drive.put(`/files/${messageObj.fileName}`, fileBuffer).then(() => { + const fileUrl = `http://localhost:${servePort}/files/${messageObj.fileName}`; + addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic); + }); + } else { + console.error('Received file message with missing file data or fileName:', messageObj); + } + } else if (messageObj.type === 'message') { + onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar, messageObj.topic); + } else if (messageObj.type === 'audio') { + const audioBuffer = b4a.from(messageObj.audio, 'base64'); + const filePath = `/audio/${Date.now()}.webm`; + drive.put(filePath, audioBuffer).then(() => { + const audioUrl = `http://localhost:${servePort}${filePath}`; + addAudioMessage(messageObj.name, audioUrl, messageObj.avatar, messageObj.topic); + }); + } else { + console.error('Received unknown message type:', messageObj); + } +} + +function handleConnection(connection, info) { + updatePeerCount(); + console.log('Peer connected, current peer count:', swarm.connections.size); + + // Send the current user's icon to the new peer + drive.get(`/icons/${config.userName}.png`).then(iconBuffer => { + if (iconBuffer) { + const iconMessage = JSON.stringify({ + type: 'icon', + username: config.userName, + avatar: b4a.toString(iconBuffer, 'base64'), + }); + connection.write(iconMessage); + } + }); + + connection.on('data', (data) => { + const messageObj = JSON.parse(data.toString()); + eventEmitter.emit('onMessage', messageObj); + }); + + connection.on('close', () => { + updatePeerCount(); + console.log('Peer disconnected, current peer count:', swarm.connections.size); + }); +} + function setupTalkButton() { const talkButton = document.getElementById('talk-btn'); if (!talkButton) return; @@ -334,6 +323,7 @@ async function joinSwarm(topicBuffer) { console.log('Joined room:', topic); // Debugging log renderMessagesForRoom(topic); + updatePeerCount(); } catch (error) { console.error('Error joining swarm for topic:', topic, error); } @@ -429,6 +419,7 @@ function switchRoom(topic) { clearMessages(); renderMessagesForRoom(topic); + updatePeerCount(); // Show chat UI elements document.querySelector('#chat').classList.remove('hidden'); @@ -571,7 +562,7 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) { function updatePeerCount() { const peerCountElement = document.querySelector('#peers-count'); if (peerCountElement) { - peerCountElement.textContent = peerCount; // Display the actual peer count + peerCountElement.textContent = swarm.connections.size; // Display the actual peer count } } @@ -756,7 +747,28 @@ function addMessageToStore(topic, messageObj) { messagesStore[topic].push(messageObj); } +function loadConfigFromFile() { + config = JSON.parse(fs.readFileSync("./config.json", 'utf8')); + console.log("Read config from file:", config); + // Update port in URLs + config.userAvatar = updatePortInUrl(config.userAvatar); + config.rooms.forEach(room => { + room.alias = room.alias || truncateHash(room.topic); + }); + for (let user in config.registeredUsers) { + config.registeredUsers[user] = updatePortInUrl(config.registeredUsers[user]); + } +} + +async function connectToAllRooms() { + // Connect to all rooms on startup + for (const room of config.rooms) { + const topicBuffer = b4a.from(room.topic, 'hex'); + await joinSwarm(topicBuffer); + } +} + // Call this function when loading the rooms initially renderRoomList(); -initialize(); \ No newline at end of file +initialize();