import Hyperswarm from 'hyperswarm'; import crypto from 'hypercore-crypto'; import b4a from 'b4a'; import ServeDrive from 'serve-drive'; import Hyperdrive from 'hyperdrive'; import Corestore from 'corestore'; import { EventEmitter } from 'events'; import fs from "fs"; const storagePath = `./storage/`; const store = new Corestore(storagePath); const drive = new Hyperdrive(store); await drive.ready(); let swarm; let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; let peerCount = 0; let currentRoom = null; const eventEmitter = new EventEmitter(); // Define servePort at the top level let servePort; // Object to store all the information we want to save let config = { userName: '', userAvatar: '', rooms: [] }; // Function to get a random port between 1337 and 2223 function getRandomPort() { return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; } async function initialize() { swarm = new Hyperswarm(); servePort = getRandomPort(); const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive }); 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'); 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', leaveRoom); } if (attachFileButton) { attachFileButton.addEventListener('click', () => fileInput.click()); } if (fileInput) { fileInput.addEventListener('change', handleFileInput); } 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 registeredUsers) { registeredUsers[user] = updatePortInUrl(registeredUsers[user]); } renderRoomList(); // Render the room list with aliases } const registerDiv = document.querySelector('#register'); if (registerDiv && !configExists) { registerDiv.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)); } 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); } else { console.error('Received unknown message type:', messageObj); } }); swarm.on('connection', async (connection, info) => { 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.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(); }); } function registerUser(e) { e.preventDefault(); const regUsername = document.querySelector('#reg-username').value; if (registeredUsers[regUsername]) { alert('Username already taken. Please choose another.'); return; } const avatarFile = document.querySelector('#avatar-file').files[0]; if (avatarFile) { const reader = new FileReader(); reader.onload = async (event) => { const buffer = new Uint8Array(event.target.result); await drive.put(`/icons/${regUsername}.png`, buffer); config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL registeredUsers[regUsername] = `http://localhost:${servePort}/icons/${regUsername}.png`; // Use placeholder URL localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers)); continueRegistration(regUsername); }; reader.readAsArrayBuffer(avatarFile); } else { continueRegistration(regUsername); } } async function continueRegistration(regUsername) { const loadingDiv = document.querySelector('#loading'); const setupDiv = document.querySelector('#setup'); if (!regUsername) { alert('Please enter a username.'); return; } config.userName = regUsername; setupDiv.classList.remove('hidden'); document.querySelector('#register').classList.add('hidden'); loadingDiv.classList.add('hidden'); const randomTopic = crypto.randomBytes(32); document.querySelector('#chat-room-topic').innerText = truncateHash(b4a.toString(randomTopic, 'hex')); writeConfigToFile("./config.json"); } async function createChatRoom() { const topicBuffer = crypto.randomBytes(32); const topic = b4a.toString(topicBuffer, 'hex'); addRoomToList(topic); joinSwarm(topicBuffer); } async function joinChatRoom(e) { e.preventDefault(); const topicStr = document.querySelector('#join-chat-room-topic').value; const topicBuffer = b4a.from(topicStr, 'hex'); addRoomToList(topicStr); joinSwarm(topicBuffer); } async function joinSwarm(topicBuffer) { if (currentRoom) { currentRoom.destroy(); } document.querySelector('#setup').classList.add('hidden'); document.querySelector('#loading').classList.remove('hidden'); const discovery = swarm.join(topicBuffer, { client: true, server: true }); await discovery.flushed(); const topic = b4a.toString(topicBuffer, 'hex'); document.querySelector('#chat-room-topic').innerText = topic; // Set full topic here document.querySelector('#loading').classList.add('hidden'); document.querySelector('#chat').classList.remove('hidden'); currentRoom = discovery; clearMessages(); } function addRoomToList(topic) { const roomList = document.querySelector('#room-list'); const roomItem = document.createElement('li'); roomItem.textContent = truncateHash(topic); roomItem.dataset.topic = topic; // Add double-click event listener for editing room name roomItem.addEventListener('dblclick', () => enterEditMode(roomItem)); roomItem.addEventListener('click', () => switchRoom(topic)); roomList.appendChild(roomItem); config.rooms.push({ topic, alias: truncateHash(topic) }); writeConfigToFile("./config.json"); } function addRoomToListWithoutWritingToConfig(topic) { const roomList = document.querySelector('#room-list'); const roomItem = document.createElement('li'); roomItem.textContent = truncateHash(topic); roomItem.dataset.topic = topic; // Add double-click event listener for editing room name roomItem.addEventListener('dblclick', () => enterEditMode(roomItem)); roomItem.addEventListener('click', () => switchRoom(topic)); roomList.appendChild(roomItem); } function enterEditMode(roomItem) { const originalText = roomItem.textContent; const topic = roomItem.dataset.topic; roomItem.innerHTML = ''; const input = document.createElement('input'); input.type = 'text'; input.value = originalText; input.style.maxWidth = '100%'; // Add this line to set the max width input.style.boxSizing = 'border-box'; // Add this line to ensure padding and border are included in the width roomItem.appendChild(input); input.focus(); input.addEventListener('blur', () => { exitEditMode(roomItem, input, topic); }); input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { exitEditMode(roomItem, input, topic); } else if (e.key === 'Escape') { roomItem.textContent = originalText; } }); } function exitEditMode(roomItem, input, topic) { const newAlias = input.value.trim(); if (newAlias) { roomItem.textContent = newAlias; // Update the config with the new alias const roomConfig = config.rooms.find(room => room.topic === topic); if (roomConfig) { roomConfig.alias = newAlias; writeConfigToFile("./config.json"); } } else { roomItem.textContent = truncateHash(topic); } } function switchRoom(topic) { const topicBuffer = b4a.from(topic, 'hex'); joinSwarm(topicBuffer); } function leaveRoom() { if (currentRoom) { const topic = b4a.toString(currentRoom.topic, 'hex'); const roomItem = document.querySelector(`li[data-topic="${topic}"]`); if (roomItem) { roomItem.remove(); } config.rooms = config.rooms.filter(e => e.topic !== topic); writeConfigToFile("./config.json"); currentRoom.destroy(); currentRoom = null; } document.querySelector('#chat').classList.add('hidden'); document.querySelector('#setup').classList.remove('hidden'); } function sendMessage(e) { e.preventDefault(); const message = document.querySelector('#message').value; document.querySelector('#message').value = ''; onMessageAdded(config.userName, message, config.userAvatar); let peersPublicKeys = []; peersPublicKeys.push([...swarm.connections].map(peer => peer.remotePublicKey.toString('hex'))); peersPublicKeys = peersPublicKeys.flat(1); peersPublicKeys.push(swarm.keyPair.publicKey.toString('hex')); const messageObj = JSON.stringify({ type: 'message', name: config.userName, message, avatar: config.userAvatar, topic: b4a.toString(currentRoom.topic, 'hex'), peers: peersPublicKeys, // Deprecated. To be deleted in future updates timestamp: Date.now(), readableTimestamp: new Date().toLocaleString(), // Added human-readable timestamp }); const peers = [...swarm.connections]; for (const peer of peers) { peer.write(messageObj); } } async function handleFileInput(event) { const file = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = async (event) => { const buffer = new Uint8Array(event.target.result); const filePath = `/files/${file.name}`; await drive.put(filePath, buffer); const fileUrl = `http://localhost:${servePort}${filePath}`; const fileMessage = { type: 'file', name: config.userName, fileName: file.name, file: b4a.toString(buffer, 'base64'), fileType: file.type, avatar: updatePortInUrl(config.userAvatar), }; console.log('Sending file message:', fileMessage); // Debugging log const peers = [...swarm.connections]; for (const peer of peers) { peer.write(JSON.stringify(fileMessage)); } addFileMessage(config.userName, file.name, fileUrl, file.type, config.userAvatar); }; reader.readAsArrayBuffer(file); } } function sendFileMessage(name, fileUrl, fileType, avatar) { const fileName = fileUrl.split('/').pop(); const messageObj = JSON.stringify({ type: 'file', name, fileName, fileUrl, fileType, avatar, topic: b4a.toString(currentRoom.topic, 'hex'), timestamp: Date.now(), }); const peers = [...swarm.connections]; for (const peer of peers) { peer.write(messageObj); } addFileMessage(name, fileName, fileUrl, fileType, avatar); } function addFileMessage(from, fileName, fileUrl, fileType, avatar) { const $div = document.createElement('div'); $div.classList.add('message'); const $img = document.createElement('img'); $img.src = avatar || 'https://via.placeholder.com/40'; $img.classList.add('avatar'); $div.appendChild($img); const $content = document.createElement('div'); $content.classList.add('message-content'); const $header = document.createElement('div'); $header.classList.add('message-header'); $header.textContent = from; $content.appendChild($header); if (fileType.startsWith('image/')) { const $image = document.createElement('img'); $image.src = fileUrl; $image.alt = fileName; $image.classList.add('attached-image'); $content.appendChild($image); } else { const $fileButton = document.createElement('button'); $fileButton.textContent = `Download File: ${fileName}`; $fileButton.onclick = function() { const $fileLink = document.createElement('a'); $fileLink.href = fileUrl; $fileLink.download = fileName; $fileLink.click(); }; $content.appendChild($fileButton); } $div.appendChild($content); document.querySelector('#messages').appendChild($div); scrollToBottom(); } function updatePeerCount() { const peerCountElement = document.querySelector('#peers-count'); if (peerCountElement) { peerCountElement.textContent = peerCount; // Display the actual peer count } } function scrollToBottom() { var container = document.getElementById("messages-container"); container.scrollTop = container.scrollHeight; } function onMessageAdded(from, message, avatar) { const $div = document.createElement('div'); $div.classList.add('message'); const $img = document.createElement('img'); $img.src = updatePortInUrl(avatar) || 'https://via.placeholder.com/40'; // Default to a placeholder image if avatar URL is not provided $img.classList.add('avatar'); $div.appendChild($img); const $content = document.createElement('div'); $content.classList.add('message-content'); const $header = document.createElement('div'); $header.classList.add('message-header'); $header.textContent = from; 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 (__) {} } return ''; // use external default escaping } }); const markdownContent = md.render(message); $text.innerHTML = markdownContent; $content.appendChild($header); $content.appendChild($text); $div.appendChild($content); document.querySelector('#messages').appendChild($div); scrollToBottom(); } function truncateHash(hash) { return `${hash.slice(0, 6)}...${hash.slice(-6)}`; } async function updateIcon(username, avatarBuffer) { const userIcon = document.querySelector(`img[src*="${username}.png"]`); if (userIcon) { const avatarBlob = new Blob([avatarBuffer], { type: 'image/png' }); const avatarUrl = URL.createObjectURL(avatarBlob); userIcon.src = updatePortInUrl(avatarUrl); config.userAvatar = avatarUrl; writeConfigToFile("./config.json"); } } function clearMessages() { const messagesContainer = document.querySelector('#messages'); while (messagesContainer.firstChild) { messagesContainer.removeChild(messagesContainer.firstChild); } } function toggleSetupView() { const setupDiv = document.querySelector('#setup'); setupDiv.classList.toggle('hidden'); } function writeConfigToFile(filePath) { fs.writeFile(filePath, JSON.stringify(config), (err) => { if (err) return console.error(err); console.log("File has been created"); }); } function updatePortInUrl(url) { if (!url) return url; const urlObject = new URL(url); urlObject.port = servePort; return urlObject.toString(); } function renderRoomList() { const roomList = document.querySelector('#room-list'); roomList.innerHTML = ''; config.rooms.forEach(room => { const roomItem = document.createElement('li'); roomItem.textContent = room.alias || truncateHash(room.topic); roomItem.dataset.topic = room.topic; roomItem.addEventListener('dblclick', () => enterEditMode(roomItem)); roomItem.addEventListener('click', () => switchRoom(room.topic)); roomList.appendChild(roomItem); }); } // Call this function when loading the rooms initially renderRoomList(); initialize();