From b50bd0bbabfba6f8bd8dc8b9625ef9bd0ed9e78e Mon Sep 17 00:00:00 2001 From: Raven Scott Date: Thu, 13 Jun 2024 20:02:01 -0400 Subject: [PATCH] Room Counts done better --- app.js | 116 ++++++++++++++++++++++++------------------------- chatBot/bot.js | 29 +++++++------ 2 files changed, 74 insertions(+), 71 deletions(-) diff --git a/app.js b/app.js index 7d33ed3..40b0888 100644 --- a/app.js +++ b/app.js @@ -130,6 +130,7 @@ 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); @@ -137,6 +138,7 @@ 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'); @@ -161,20 +163,38 @@ async function initialize() { swarm.on('connection', async (connection, info) => { try { - const discovery = [...discoveryTopicsMap.entries()].find(([key, value]) => key.id === info.id); - const topic = discovery ? discovery[1] : null; + 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); + }); - if (!topic) { - console.error('No topic found in connection info:', info); - return; - } + connection.on('close', () => { + const topic = connection.topic; + if (topic && peerCounts[topic]) { + peerCounts[topic]--; + updateHeaderPeerCount(topic); + console.log('Peer disconnected, current peer count:', peerCounts[topic]); + } + }); - if (!peerCounts[topic]) { - peerCounts[topic] = 0; + // 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[topic]++; - updatePeerCount(topic); - console.log('Peer connected, current peer count:', peerCounts[topic]); + 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`); @@ -183,21 +203,17 @@ async function initialize() { type: 'icon', username: config.userName, avatar: b4a.toString(iconBuffer, 'base64'), - topic + topic: currentTopic + }); + connection.write(iconMessage); + } else { + const iconMessage = JSON.stringify({ + type: 'icon', + username: config.userName, + topic: currentTopic }); connection.write(iconMessage); } - - connection.on('data', (data) => { - const messageObj = JSON.parse(data.toString()); - eventEmitter.emit('onMessage', messageObj); - }); - - connection.on('close', () => { - peerCounts[topic]--; - updatePeerCount(topic); - console.log('Peer disconnected, current peer count:', peerCounts[topic]); - }); } catch (error) { console.error('Error handling connection:', error); } @@ -601,27 +617,6 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) { } } -function updatePeerCount(topic) { - let peerCountElement = document.querySelector(`#peers-count-${topic}`); - if (!peerCountElement) { - const roomItem = document.querySelector(`#room-list li[data-topic="${topic}"]`); - if (roomItem) { - peerCountElement = document.createElement('span'); - peerCountElement.id = `peers-count-${topic}`; - // roomItem.appendChild(peerCountElement); - } - } - if (peerCountElement) { - peerCountElement.textContent = ` (${peerCounts[topic]})`; // Display the peer count for the specific topic - } - - // Update the header peer count if the current room matches the topic - const currentTopic = document.querySelector('#chat-room-topic').innerText; - if (currentTopic === topic) { - updateHeaderPeerCount(topic); - } -} - function updateHeaderPeerCount(topic) { const peerCountElement = document.querySelector('#peers-count'); if (peerCountElement) { @@ -637,12 +632,13 @@ 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); @@ -667,19 +663,24 @@ function onMessageAdded(from, message, avatar, topic) { const $text = document.createElement('div'); $text.classList.add('message-text'); - const md = window.markdownit({ - highlight: function (str, lang) { - if (lang && hljs.getLanguage(lang)) { - try { - return hljs.highlight(str, { language: lang }).value; - } catch (__) {} + 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 } - return ''; // use external default escaping - } - }); + }); - const markdownContent = md.render(message); - $text.innerHTML = markdownContent; + const markdownContent = md.render(message); + $text.innerHTML = markdownContent; + } else { + console.error('Message content is not a string:', message); + $text.textContent = 'Invalid message content.'; + } $content.appendChild($header); $content.appendChild($text); @@ -799,7 +800,6 @@ function renderMessagesForRoom(topic) { onMessageAdded(message.from, message.message, message.avatar, topic); }); } - function getMessagesForRoom(topic) { return messagesStore[topic] || []; } @@ -814,4 +814,4 @@ function addMessageToStore(topic, messageObj) { // Call this function when loading the rooms initially renderRoomList(); -initialize(); \ No newline at end of file +initialize(); diff --git a/chatBot/bot.js b/chatBot/bot.js index fc952a6..3e4b961 100644 --- a/chatBot/bot.js +++ b/chatBot/bot.js @@ -5,6 +5,7 @@ import 'dotenv/config'; // Create a new instance of the chatBot class with a valid botName const botName = process.env.BOT_NAME; // Replace 'MyBot' with the desired bot name +const linkupRoomId = process.env.LINKUP_ROOM_ID; // Use the environment variable for room ID // Load commands from the 'commands' directory const commandsDir = path.join(new URL('./commands/', import.meta.url).pathname); @@ -41,29 +42,31 @@ loadCommands().then(commands => { bot.on('onMessage', (peer, message) => { console.log(message); - console.log(`Message received from ${message.name}@${message.topic} at ${new Date(message.timestamp).toLocaleTimeString()}: ${message.message}`); + console.log(`Message received from ${message.peerName}@${message.topic} at ${new Date(message.timestamp).toLocaleTimeString()}: ${message.message}`); - // Check if the message starts with a command prefix - if (message.message.startsWith('!')) { - // Extract the command and arguments - const [command, ...args] = message.message.slice(1).split(' '); + // Handle all messages as potential AI commands + const userMessage = message.message; - // Find the corresponding command handler - const commandHandler = commands[command.toLowerCase()]; + // Find the corresponding command handler (assuming the AI command handler is in 'commands/ai.js') + const commandHandler = commands['ai']; - // If the command exists, execute its handler - if (commandHandler && typeof commandHandler.handler === 'function') { - commandHandler.handler(bot, args, message); - } + // If the command exists, execute its handler + if (commandHandler && typeof commandHandler.handler === 'function') { + commandHandler.handler(bot, [userMessage], message); } }); bot.on('onBotJoinRoom', () => { console.log("Bot is ready!"); - bot.sendTextMessage(process.env.ON_READY_MESSAGE); + // Include topic in the message sent when the bot joins the room + bot.sendTextMessage({ + text: process.env.ON_READY_MESSAGE, + topic: linkupRoomId + }); }); - bot.joinChatRoom(process.env.LINKUP_ROOM_ID); + // Ensure the bot joins the chat room with the topic information + bot.joinChatRoom(linkupRoomId); }).catch(error => { console.error('Error loading commands:', error); });