Compare commits

..

No commits in common. "d3792b4bd0dd583b4cc23a1a2763fce0c0788e6d" and "f69b22c810633161451c8e348e4249f2f53f75af" have entirely different histories.

11 changed files with 216 additions and 643 deletions

1
.gitignore vendored
View File

@ -7,4 +7,3 @@ chatBot/.env
chatBot/commands/ai.js chatBot/commands/ai.js
config.json config.json
.idea .idea
AIBot

View File

@ -1,12 +0,0 @@
`LinkUp` is currently in` active development` and `not fully launched`.
To launch the App in Dev Mode:
`git clone https://git.ssh.surf/snxraven/LinkUp-P2P-Chat.git`
`cd LinkUp-P2P-Chat`
`npm i; npm i pear -g;`
Lastly - run the app:
`pear dev -s /tmp/tmp_pear`

573
app.js
View File

@ -6,22 +6,16 @@ import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore'; import Corestore from 'corestore';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import fs from "fs"; import fs from "fs";
import handleCommand from './commands.js';
const agentAvatarPath = './assets/agent.png';
let agentAvatar = '';
const storagePath = `./storage/`; const storagePath = `./storage/`;
const store = new Corestore(storagePath); const store = new Corestore(storagePath);
const drive = new Hyperdrive(store); const drive = new Hyperdrive(store);
await drive.ready(); await drive.ready();
// Load the agent avatar once when the app starts let swarm;
if (fs.existsSync(agentAvatarPath)) { let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
const avatarBuffer = fs.readFileSync(agentAvatarPath); let peerCount = 0;
agentAvatar = `data:image/png;base64,${b4a.toString(avatarBuffer, 'base64')}`;
}
let activeRooms = []; let activeRooms = [];
const eventEmitter = new EventEmitter(); const eventEmitter = new EventEmitter();
@ -32,8 +26,7 @@ let servePort;
let config = { let config = {
userName: '', userName: '',
userAvatar: '', userAvatar: '',
rooms: [], rooms: []
registeredUsers: {}
}; };
// Store messages for each room // Store messages for each room
@ -44,81 +37,14 @@ function getRandomPort() {
return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152;
} }
function currentTopic() {
return document.querySelector('#chat-room-topic').innerText;
}
function getCurrentPeerCount() {
const topic = currentTopic();
const room = activeRooms.find(room => room.topic === topic);
return room ? room.swarm.connections.size : 0;
}
function updatePeerCount() {
const peerCountElement = document.querySelector('#peers-count');
if (peerCountElement) {
peerCountElement.textContent = getCurrentPeerCount(); // Display the actual peer count
}
}
async function joinRoom(topicStr) {
const topicBuffer = b4a.from(topicStr, 'hex');
addRoomToList(topicStr);
await joinSwarm(topicBuffer);
}
async function createRoom(alias) {
const topicBuffer = crypto.randomBytes(32);
const topic = b4a.toString(topicBuffer, 'hex');
addRoomToList(topic, alias);
await joinSwarm(topicBuffer);
}
async function listFiles() {
const files = [];
for await (const entry of drive.readdir('/files')) {
files.push(entry);
}
return files;
}
async function deleteFile(filename) {
await drive.del(`/files/${filename}`);
}
async function initialize() { async function initialize() {
try { 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);
// Event listeners setup servePort = getRandomPort();
setupEventListeners(); const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive });
await serve.ready();
console.log('Listening on http://localhost:' + serve.address().port);
const configExists = fs.existsSync("./config.json");
if (configExists) {
loadConfigFromFile();
renderRoomList();
await connectToAllRooms();
}
if (!configExists) {
document.querySelector('#register').classList.remove('hidden');
}
eventEmitter.on('onMessage', async (messageObj) => {
handleIncomingMessage(messageObj);
});
document.addEventListener("DOMContentLoaded", (event) => {
hljs.highlightAll();
});
} catch (error) {
console.error('Error during initialization:', error);
}
}
function setupEventListeners() {
const registerForm = document.querySelector('#register-form'); const registerForm = document.querySelector('#register-form');
const selectAvatarButton = document.querySelector('#select-avatar'); const selectAvatarButton = document.querySelector('#select-avatar');
const createChatRoomButton = document.querySelector('#create-chat-room'); const createChatRoomButton = document.querySelector('#create-chat-room');
@ -128,7 +54,6 @@ function setupEventListeners() {
const removeRoomBtn = document.querySelector('#remove-room-btn'); const removeRoomBtn = document.querySelector('#remove-room-btn');
const attachFileButton = document.getElementById('attach-file'); const attachFileButton = document.getElementById('attach-file');
const fileInput = document.getElementById('file-input'); const fileInput = document.getElementById('file-input');
const talkButton = document.getElementById('talk-btn');
if (registerForm) { if (registerForm) {
registerForm.addEventListener('submit', registerUser); registerForm.addEventListener('submit', registerUser);
@ -152,7 +77,7 @@ function setupEventListeners() {
} }
if (removeRoomBtn) { if (removeRoomBtn) {
removeRoomBtn.addEventListener('click', () => { removeRoomBtn.addEventListener('click', () => {
const topic = currentTopic(); const topic = document.querySelector('#chat-room-topic').innerText;
leaveRoom(topic); leaveRoom(topic);
}); });
} }
@ -162,155 +87,101 @@ function setupEventListeners() {
if (fileInput) { if (fileInput) {
fileInput.addEventListener('change', handleFileInput); fileInput.addEventListener('change', handleFileInput);
} }
if (talkButton) {
setupTalkButton();
}
}
function handleIncomingMessage(messageObj) { const configExists = fs.existsSync("./config.json");
console.log('Received message:', messageObj); // Debugging log if (configExists) {
config = JSON.parse(fs.readFileSync("./config.json", 'utf8'));
if (messageObj.type === 'icon') { console.log("Read config from file:", config);
const username = messageObj.username; // Update port in URLs
if (messageObj.avatar) { config.userAvatar = updatePortInUrl(config.userAvatar);
const avatarBuffer = b4a.from(messageObj.avatar, 'base64'); config.rooms.forEach(room => {
drive.put(`/icons/${username}.png`, avatarBuffer); room.alias = room.alias || truncateHash(room.topic);
updateIcon(username, avatarBuffer); });
} else { for (let user in registeredUsers) {
console.error('Received icon message with missing avatar data:', messageObj); registeredUsers[user] = updatePortInUrl(registeredUsers[user]);
} }
} else if (messageObj.type === 'file') {
if (messageObj.file && messageObj.fileName) { renderRoomList(); // Render the room list with aliases
const fileBuffer = b4a.from(messageObj.file, 'base64');
drive.put(`/files/${messageObj.fileName}`, fileBuffer).then(() => { // Connect to all rooms on startup
for (const room of config.rooms) {
const topicBuffer = b4a.from(room.topic, 'hex');
await joinSwarm(topicBuffer);
}
}
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}`; const fileUrl = `http://localhost:${servePort}/files/${messageObj.fileName}`;
addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic); addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic);
}); } else {
} else { console.error('Received file message with missing file data or fileName:', messageObj);
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, messageObj.timestamp);
} 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);
}
}
async function handleConnection(connection, info) {
console.log('New connection', info);
// Sending the icon immediately upon connection
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'),
});
console.log('Sending icon to new peer:', iconMessage);
connection.write(iconMessage);
} else {
console.error('Icon not found for user:', config.userName);
}
connection.on('data', (data) => {
const messageObj = JSON.parse(data.toString());
eventEmitter.emit('onMessage', messageObj);
});
connection.on('close', () => {
console.log('Connection closed', info);
updatePeerCount();
});
connection.on('error', (error) => {
console.error('Connection error', error);
if (error.code === 'ETIMEDOUT') {
retryConnection(info.topicBuffer);
}
});
updatePeerCount();
}
function retryConnection(topicBuffer) {
const topic = b4a.toString(topicBuffer, 'hex');
const room = activeRooms.find(room => room.topic === topic);
if (room) {
console.log('Retrying connection to room:', topic);
room.swarm.leave(topicBuffer);
joinSwarm(topicBuffer).catch((error) => {
console.error('Failed to rejoin room after timeout:', error);
});
}
}
function setupTalkButton() {
const talkButton = document.getElementById('talk-btn');
if (!talkButton) return;
let mediaRecorder;
let audioChunks = [];
talkButton.addEventListener('mousedown', async () => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.addEventListener('dataavailable', event => {
audioChunks.push(event.data);
});
mediaRecorder.addEventListener('stop', async () => {
const audioBlob = new Blob(audioChunks);
audioChunks = [];
const arrayBuffer = await audioBlob.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
const topic = currentTopic();
const filePath = `/audio/${Date.now()}.webm`;
await drive.put(filePath, buffer);
const audioUrl = `http://localhost:${servePort}${filePath}`;
const audioMessage = {
type: 'audio',
name: config.userName,
audio: b4a.toString(buffer, 'base64'),
audioType: audioBlob.type,
avatar: updatePortInUrl(config.userAvatar),
topic: topic
};
console.log('Sending audio message:', audioMessage); // Debugging log
const peers = [...activeRooms.find(room => room.topic === topic).swarm.connections];
for (const peer of peers) {
peer.write(JSON.stringify(audioMessage));
} }
} else if (messageObj.type === 'message') {
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar, messageObj.topic);
} else {
console.error('Received unknown message type:', messageObj);
}
});
addAudioMessage(config.userName, audioUrl, config.userAvatar, topic); 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);
}); });
}); });
talkButton.addEventListener('mouseup', () => { swarm.on('error', (err) => {
if (mediaRecorder) { console.error('Swarm error:', err);
mediaRecorder.stop();
}
}); });
talkButton.addEventListener('mouseleave', () => { swarm.on('close', () => {
if (mediaRecorder && mediaRecorder.state === 'recording') { console.log('Swarm closed');
mediaRecorder.stop(); });
}
// Initialize highlight.js once the DOM is fully loaded
document.addEventListener("DOMContentLoaded", (event) => {
hljs.highlightAll();
}); });
} }
@ -318,7 +189,7 @@ function registerUser(e) {
e.preventDefault(); e.preventDefault();
const regUsername = document.querySelector('#reg-username').value; const regUsername = document.querySelector('#reg-username').value;
if (config.registeredUsers[regUsername]) { if (registeredUsers[regUsername]) {
alert('Username already taken. Please choose another.'); alert('Username already taken. Please choose another.');
return; return;
} }
@ -330,8 +201,8 @@ function registerUser(e) {
const buffer = new Uint8Array(event.target.result); const buffer = new Uint8Array(event.target.result);
await drive.put(`/icons/${regUsername}.png`, buffer); await drive.put(`/icons/${regUsername}.png`, buffer);
config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL
config.registeredUsers[regUsername] = `http://localhost:${servePort}/icons/${regUsername}.png`; // Use placeholder URL registeredUsers[regUsername] = `http://localhost:${servePort}/icons/${regUsername}.png`; // Use placeholder URL
writeConfigToFile("./config.json"); localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
continueRegistration(regUsername); continueRegistration(regUsername);
}; };
reader.readAsArrayBuffer(avatarFile); reader.readAsArrayBuffer(avatarFile);
@ -369,15 +240,7 @@ async function createChatRoom() {
async function joinChatRoom(e) { async function joinChatRoom(e) {
e.preventDefault(); e.preventDefault();
const topicStr = document.querySelector('#join-chat-room-topic').value.trim(); const topicStr = document.querySelector('#join-chat-room-topic').value;
// Validate the topic string
const isValidTopic = /^[0-9a-fA-F]{64}$/.test(topicStr);
if (!isValidTopic) {
alert('Invalid topic format. Please enter a 64-character hexadecimal string.');
return;
}
const topicBuffer = b4a.from(topicStr, 'hex'); const topicBuffer = b4a.from(topicStr, 'hex');
addRoomToList(topicStr); addRoomToList(topicStr);
await joinSwarm(topicBuffer); await joinSwarm(topicBuffer);
@ -386,38 +249,28 @@ async function joinChatRoom(e) {
async function joinSwarm(topicBuffer) { async function joinSwarm(topicBuffer) {
const topic = b4a.toString(topicBuffer, 'hex'); const topic = b4a.toString(topicBuffer, 'hex');
if (!activeRooms.some(room => room.topic === topic)) { if (!activeRooms.some(room => room.topic === topic)) {
try { const discovery = swarm.join(topicBuffer, { client: true, server: true });
const swarm = new Hyperswarm(); await discovery.flushed();
const discovery = swarm.join(topicBuffer, { client: true, server: true });
await discovery.flushed();
swarm.on('connection', (connection, info) => { activeRooms.push({ topic, discovery });
handleConnection(connection, info);
});
activeRooms.push({ topic, swarm, discovery }); console.log('Joined room:', topic); // Debugging log
console.log('Joined room:', topic); // Debugging log renderMessagesForRoom(topic);
renderMessagesForRoom(topic);
updatePeerCount();
} catch (error) {
console.error('Error joining swarm for topic:', topic, error);
}
} }
} }
function addRoomToList(topic, alias) { function addRoomToList(topic) {
const roomList = document.querySelector('#room-list'); const roomList = document.querySelector('#room-list');
const roomItem = document.createElement('li'); const roomItem = document.createElement('li');
roomItem.textContent = alias || truncateHash(topic); roomItem.textContent = truncateHash(topic);
roomItem.dataset.topic = topic; roomItem.dataset.topic = topic;
roomItem.addEventListener('dblclick', () => enterEditMode(roomItem)); roomItem.addEventListener('dblclick', () => enterEditMode(roomItem));
roomItem.addEventListener('click', () => switchRoom(topic)); roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem); roomList.appendChild(roomItem);
config.rooms.push({ topic, alias: alias || truncateHash(topic) }); config.rooms.push({ topic, alias: truncateHash(topic) });
writeConfigToFile("./config.json"); writeConfigToFile("./config.json");
} }
@ -462,7 +315,8 @@ function exitEditMode(roomItem, input, topic) {
} }
// Check if the edited room is the current room in view // Check if the edited room is the current room in view
if (currentTopic() === topic) { const currentTopic = document.querySelector('#chat-room-topic').innerText;
if (currentTopic === topic) {
const chatRoomName = document.querySelector('#chat-room-name'); const chatRoomName = document.querySelector('#chat-room-name');
if (chatRoomName) { if (chatRoomName) {
chatRoomName.innerText = newAlias; chatRoomName.innerText = newAlias;
@ -495,7 +349,6 @@ function switchRoom(topic) {
clearMessages(); clearMessages();
renderMessagesForRoom(topic); renderMessagesForRoom(topic);
updatePeerCount();
// Show chat UI elements // Show chat UI elements
document.querySelector('#chat').classList.remove('hidden'); document.querySelector('#chat').classList.remove('hidden');
@ -506,7 +359,7 @@ function leaveRoom(topic) {
const roomIndex = activeRooms.findIndex(room => room.topic === topic); const roomIndex = activeRooms.findIndex(room => room.topic === topic);
if (roomIndex !== -1) { if (roomIndex !== -1) {
const room = activeRooms[roomIndex]; const room = activeRooms[roomIndex];
room.swarm.destroy(); room.discovery.destroy();
activeRooms.splice(roomIndex, 1); activeRooms.splice(roomIndex, 1);
} }
@ -526,34 +379,16 @@ function leaveRoom(topic) {
} }
} }
function sendMessage(e) {
async function sendMessage(e) {
e.preventDefault(); e.preventDefault();
const message = document.querySelector('#message').value; const message = document.querySelector('#message').value;
document.querySelector('#message').value = ''; document.querySelector('#message').value = '';
const topic = currentTopic(); const topic = document.querySelector('#chat-room-topic').innerText;
const timestamp = Date.now();
if (message.startsWith('~')) {
// Handle command
await handleCommand(message, {
eventEmitter,
currentTopic,
clearMessages,
addMessage: (from, message, avatar, topic) => onMessageAdded(from, message, avatar, topic, timestamp),
joinRoom,
leaveRoom,
createRoom,
listFiles,
deleteFile
});
return;
}
console.log('Sending message:', message); // Debugging log console.log('Sending message:', message); // Debugging log
onMessageAdded(config.userName, message, config.userAvatar, topic, timestamp); onMessageAdded(config.userName, message, config.userAvatar, topic);
const messageObj = JSON.stringify({ const messageObj = JSON.stringify({
type: 'message', type: 'message',
@ -561,10 +396,10 @@ async function sendMessage(e) {
message, message,
avatar: config.userAvatar, avatar: config.userAvatar,
topic: topic, topic: topic,
timestamp: timestamp timestamp: Date.now()
}); });
const peers = [...activeRooms.find(room => room.topic === topic).swarm.connections]; const peers = [...swarm.connections];
for (const peer of peers) { for (const peer of peers) {
peer.write(messageObj); peer.write(messageObj);
} }
@ -580,7 +415,7 @@ async function handleFileInput(event) {
await drive.put(filePath, buffer); await drive.put(filePath, buffer);
const fileUrl = `http://localhost:${servePort}${filePath}`; const fileUrl = `http://localhost:${servePort}${filePath}`;
const topic = currentTopic(); const topic = document.querySelector('#chat-room-topic').innerText;
const fileMessage = { const fileMessage = {
type: 'file', type: 'file',
@ -594,7 +429,7 @@ async function handleFileInput(event) {
console.log('Sending file message:', fileMessage); // Debugging log console.log('Sending file message:', fileMessage); // Debugging log
const peers = [...activeRooms.find(room => room.topic === topic).swarm.connections]; const peers = [...swarm.connections];
for (const peer of peers) { for (const peer of peers) {
peer.write(JSON.stringify(fileMessage)); peer.write(JSON.stringify(fileMessage));
} }
@ -605,13 +440,34 @@ async function handleFileInput(event) {
} }
} }
function sendFileMessage(name, fileUrl, fileType, avatar) {
const fileName = fileUrl.split('/').pop();
const messageObj = JSON.stringify({
type: 'file',
name,
fileName,
fileUrl,
fileType,
avatar,
topic: document.querySelector('#chat-room-topic').innerText,
timestamp: Date.now(),
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(messageObj);
}
addFileMessage(name, fileName, fileUrl, fileType, avatar, document.querySelector('#chat-room-topic').innerText);
}
function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) { function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
console.log('Adding file message:', { from, fileName, fileUrl, fileType, avatar, topic }); // Debugging log console.log('Adding file message:', { from, fileName, fileUrl, fileType, avatar, topic }); // Debugging log
const $div = document.createElement('div'); const $div = document.createElement('div');
$div.classList.add('message'); $div.classList.add('message');
const $img = document.createElement('img'); const $img = document.createElement('img');
$img.src = updatePortInUrl(avatar) || 'https://via.placeholder.com/40'; $img.src = avatar || 'https://via.placeholder.com/40';
$img.classList.add('avatar'); $img.classList.add('avatar');
$div.appendChild($img); $div.appendChild($img);
@ -625,7 +481,7 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
if (fileType.startsWith('image/')) { if (fileType.startsWith('image/')) {
const $image = document.createElement('img'); const $image = document.createElement('img');
$image.src = updatePortInUrl(fileUrl); $image.src = fileUrl;
$image.alt = fileName; $image.alt = fileName;
$image.classList.add('attached-image'); $image.classList.add('attached-image');
$content.appendChild($image); $content.appendChild($image);
@ -644,11 +500,19 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
$div.appendChild($content); $div.appendChild($content);
// Only render the message if it's for the current room // Only render the message if it's for the current room
if (currentTopic() === topic) { const currentTopic = document.querySelector('#chat-room-topic').innerText;
if (currentTopic === topic) {
document.querySelector('#messages').appendChild($div); document.querySelector('#messages').appendChild($div);
scrollToBottom(); scrollToBottom();
} else { } else {
console.log(`Message for topic ${topic} not rendered because current topic is ${currentTopic()}`); // Debugging log console.log(`Message for topic ${topic} not rendered because current topic is ${currentTopic}`); // Debugging log
}
}
function updatePeerCount() {
const peerCountElement = document.querySelector('#peers-count');
if (peerCountElement) {
peerCountElement.textContent = peerCount; // Display the actual peer count
} }
} }
@ -657,20 +521,20 @@ function scrollToBottom() {
container.scrollTop = container.scrollHeight; container.scrollTop = container.scrollHeight;
} }
function onMessageAdded(from, message, avatar, topic, timestamp) { function onMessageAdded(from, message, avatar, topic) {
console.log('Adding message:', { from, message, avatar, topic }); // Debugging log console.log('Adding message:', { from, message, avatar, topic }); // Debugging log
const messageObj = { const messageObj = {
from, from,
message, message,
avatar, avatar
timestamp: timestamp || Date.now()
}; };
// Add the message to the store // Add the message to the store
addMessageToStore(topic, messageObj); addMessageToStore(topic, messageObj);
// Only render messages for the current room // Only render messages for the current room
if (currentTopic() === topic) { const currentTopic = document.querySelector('#chat-room-topic').innerText;
if (currentTopic === topic) {
const $div = document.createElement('div'); const $div = document.createElement('div');
$div.classList.add('message'); $div.classList.add('message');
@ -689,34 +553,6 @@ function onMessageAdded(from, message, avatar, topic, timestamp) {
const $text = document.createElement('div'); const $text = document.createElement('div');
$text.classList.add('message-text'); $text.classList.add('message-text');
if (message.includes('Available files:')) {
const files = message.split('\n').slice(1); // Skip the "Available files:" line
const fileList = document.createElement('ul');
files.forEach(file => {
file = file.replace("- ", "")
const listItem = document.createElement('li');
const fileButton = document.createElement('button');
fileButton.textContent = file.trim();
fileButton.onclick = () => downloadFile(file.trim());
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.onclick = () => {
console.log("file to delete: ", file);
deleteFile(file);
listItem.remove();
};
listItem.appendChild(fileButton);
listItem.appendChild(deleteButton);
fileList.appendChild(listItem);
});
$text.appendChild(fileList);
} else {
const md = window.markdownit({ const md = window.markdownit({
highlight: function (str, lang) { highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) { if (lang && hljs.getLanguage(lang)) {
@ -727,9 +563,9 @@ function onMessageAdded(from, message, avatar, topic, timestamp) {
return ''; // use external default escaping return ''; // use external default escaping
} }
}); });
const markdownContent = md.render(message); const markdownContent = md.render(message);
$text.innerHTML = markdownContent; $text.innerHTML = markdownContent;
}
$content.appendChild($header); $content.appendChild($header);
$content.appendChild($text); $content.appendChild($text);
@ -738,54 +574,7 @@ function onMessageAdded(from, message, avatar, topic, timestamp) {
document.querySelector('#messages').appendChild($div); document.querySelector('#messages').appendChild($div);
scrollToBottom(); scrollToBottom();
} else { } else {
console.log(`Message for topic ${topic} not rendered because current topic is ${currentTopic()}`); // Debugging log console.log(`Message for topic ${topic} not rendered because current topic is ${currentTopic}`); // Debugging log
}
}
function downloadFile(filename) {
const fileUrl = `http://localhost:${servePort}/files/${filename}`;
const a = document.createElement('a');
a.href = fileUrl;
a.download = filename;
a.click();
}
function addAudioMessage(from, audioUrl, avatar, topic) {
console.log('Adding audio message:', { from, audioUrl, avatar, topic }); // Debugging log
const $div = document.createElement('div');
$div.classList.add('message');
const $img = document.createElement('img');
$img.src = updatePortInUrl(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);
const $audio = document.createElement('audio');
$audio.controls = true;
if (from !== config.userName) {
$audio.autoplay = true; // Add autoplay attribute for peers only
}
$audio.src = updatePortInUrl(audioUrl);
$audio.classList.add('attached-audio');
$content.appendChild($audio);
$div.appendChild($content);
// Only render the message if it's for the current room
if (currentTopic() === topic) {
document.querySelector('#messages').appendChild($div);
scrollToBottom();
} else {
console.log(`Message for topic ${topic} not rendered because current topic is ${currentTopic()}`); // Debugging log
} }
} }
@ -805,26 +594,11 @@ async function updateIcon(username, avatarBuffer) {
} }
} }
function clearMessagesCMD() {
const messagesContainer = document.querySelector('#messages');
while (messagesContainer.firstChild) {
messagesContainer.removeChild(messagesContainer.firstChild);
}
// Clear the messages from the store for the current room
const topic = currentTopic();
messagesStore[topic] = [];
}
function clearMessages() { function clearMessages() {
const messagesContainer = document.querySelector('#messages'); const messagesContainer = document.querySelector('#messages');
while (messagesContainer.firstChild) { while (messagesContainer.firstChild) {
messagesContainer.removeChild(messagesContainer.firstChild); messagesContainer.removeChild(messagesContainer.firstChild);
} }
// Clear the messages from the store for the current room
// const topic = currentTopic();
// messagesStore[topic] = [];
} }
function toggleSetupView() { function toggleSetupView() {
@ -869,7 +643,7 @@ function renderMessagesForRoom(topic) {
// Fetch and render messages for the selected room // Fetch and render messages for the selected room
const messages = getMessagesForRoom(topic); const messages = getMessagesForRoom(topic);
messages.forEach(message => { messages.forEach(message => {
onMessageAdded(message.from, message.message, message.avatar, topic, message.timestamp); onMessageAdded(message.from, message.message, message.avatar, topic);
}); });
} }
@ -881,40 +655,7 @@ function addMessageToStore(topic, messageObj) {
if (!messagesStore[topic]) { if (!messagesStore[topic]) {
messagesStore[topic] = []; messagesStore[topic] = [];
} }
messagesStore[topic].push(messageObj);
// Check for duplicates using a combination of message content and timestamp
const isDuplicate = messagesStore[topic].some(msg =>
msg.from === messageObj.from &&
msg.message === messageObj.message &&
msg.timestamp === messageObj.timestamp
);
if (!isDuplicate) {
messagesStore[topic].push(messageObj);
} else {
console.log('Duplicate message detected:', messageObj); // Debugging log
}
}
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 // Call this function when loading the rooms initially

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

View File

@ -64,6 +64,7 @@ loadCommands().then(commands => {
}); });
bot.joinChatRoom(process.env.LINKUP_ROOM_ID); bot.joinChatRoom(process.env.LINKUP_ROOM_ID);
bot.joinChatRoom(process.env.LINKUP_ROOM_ID2);
}).catch(error => { }).catch(error => {
console.error('Error loading commands:', error); console.error('Error loading commands:', error);
}); });

View File

@ -7,7 +7,7 @@ import FileMessage from "./FileMessage.js";
class Client extends EventEmitter { class Client extends EventEmitter {
constructor(botName) { constructor(botName) {
super(); super();
if (!botName) return console.error("Bot Name is not defined!"); if(!botName) return console.error("Bot Name is not defined!");
this.botName = botName; this.botName = botName;
this.swarm = new Hyperswarm(); this.swarm = new Hyperswarm();
this.joinedRooms = new Set(); // Track the rooms the bot has joined this.joinedRooms = new Set(); // Track the rooms the bot has joined
@ -48,10 +48,6 @@ class Client extends EventEmitter {
} }
joinChatRoom(chatRoomID) { joinChatRoom(chatRoomID) {
if (!chatRoomID || typeof chatRoomID !== 'string') {
return console.error("Invalid chat room ID!");
}
this.joinedRooms.add(chatRoomID); // Add the room to the list of joined rooms this.joinedRooms.add(chatRoomID); // Add the room to the list of joined rooms
this.currentTopic = chatRoomID; // Store the current topic this.currentTopic = chatRoomID; // Store the current topic
this.discovery = this.swarm.join(Buffer.from(chatRoomID, 'hex'), { client: true, server: true }); this.discovery = this.swarm.join(Buffer.from(chatRoomID, 'hex'), { client: true, server: true });

View File

@ -1,5 +1,5 @@
class FileMessage { class FileMessage {
constructor(peerName, fileName, fileUrl, fileType, peerAvatar, topic, timestamp) { public FileMessage(peerName, fileName, fileUrl, fileType, peerAvatar, topic, timestamp) {
this.peerName = peerName; this.peerName = peerName;
this.fileName = fileName; this.fileName = fileName;
this.fileUrl = fileUrl; this.fileUrl = fileUrl;
@ -9,7 +9,7 @@ class FileMessage {
this.timestamp = timestamp; this.timestamp = timestamp;
} }
toJsonString() { public toJsonString() {
return JSON.stringify({ return JSON.stringify({
type: 'file', type: 'file',
name: this.peerName, name: this.peerName,

View File

@ -1,5 +1,5 @@
class TextMessage { class TextMessage {
constructor(peerName, peerAvatar, topic, message, timestamp) { public TextMessage(peerName, peerAvatar, topic, message, timestamp) {
this.peerName = peerName; this.peerName = peerName;
this.peerAvatar = peerAvatar; this.peerAvatar = peerAvatar;
this.topic = topic; this.topic = topic;
@ -7,7 +7,7 @@ class TextMessage {
this.timestamp = timestamp; this.timestamp = timestamp;
} }
toJsonString() { public toJsonString() {
return JSON.stringify({ return JSON.stringify({
type: 'message', type: 'message',
name: this.peerName, name: this.peerName,
@ -18,7 +18,7 @@ class TextMessage {
}); });
} }
static new(bot, message) { public static new(bot, message) {
return new TextMessage(bot.botName, "", bot.currentTopic, message, Date.now()); return new TextMessage(bot.botName, "", bot.currentTopic, message, Date.now());
} }
} }

View File

@ -1,56 +0,0 @@
// commands.js
import b4a from 'b4a';
import fs from 'fs';
const agentAvatarPath = './assets/agent.png';
let agentAvatar = '';
// Load the agent avatar once when the module is imported
if (fs.existsSync(agentAvatarPath)) {
const avatarBuffer = fs.readFileSync(agentAvatarPath);
agentAvatar = `data:image/png;base64,${b4a.toString(avatarBuffer, 'base64')}`;
}
export default async function handleCommand(command, context) {
const { eventEmitter, currentTopic, clearMessages, addMessage, joinRoom, leaveRoom, createRoom, listFiles } = context;
const args = command.trim().split(' ');
const cmd = args[0].toLowerCase();
const restArgs = args.slice(1).join(' ');
switch (cmd) {
case '~clear':
clearMessages();
break;
case '~ping':
addMessage('LinkUp', 'pong', agentAvatar, currentTopic());
break;
case '~help':
addMessage('LinkUp', 'Available commands:\n- ~clear\n- ~ping\n- ~help\n- ~join [topic]\n- ~leave\n- ~create [alias]\n- ~list-files', agentAvatar, currentTopic());
break;
case '~join':
if (restArgs) {
await joinRoom(restArgs);
} else {
addMessage('LinkUp', 'Usage: ~join [topic]', agentAvatar, currentTopic());
}
break;
case '~leave':
leaveRoom(currentTopic());
break;
case '~create':
if (restArgs) {
await createRoom(restArgs);
} else {
addMessage('LinkUp', 'Usage: ~create [alias]', agentAvatar, currentTopic());
}
break;
case '~list-files':
const files = await listFiles();
const fileList = files.length > 0 ? files.map(file => `- ${file}`).join('\n') : 'No files available';
addMessage('LinkUp', `Available files:\n${fileList}`, agentAvatar, currentTopic());
break;
default:
console.log('Unknown command:', command);
}
}

View File

@ -62,7 +62,6 @@
<textarea id="message" rows="4"></textarea> <textarea id="message" rows="4"></textarea>
<input type="file" id="file-input" style="display:none;"> <input type="file" id="file-input" style="display:none;">
<button type="button" id="attach-file">Attach File</button> <button type="button" id="attach-file">Attach File</button>
<button type="button" id="talk-btn">Talk</button> <!-- New Talk button -->
<input type="submit" value="Send" /> <input type="submit" value="Send" />
</form> </form>
<button id="remove-room-btn">Leave Room</button> <button id="remove-room-btn">Leave Room</button>
@ -91,7 +90,7 @@
if (chatRoomTopic) { if (chatRoomTopic) {
const topic = chatRoomTopic.innerText; const topic = chatRoomTopic.innerText;
navigator.clipboard.writeText(topic).then(() => { navigator.clipboard.writeText(topic).then(() => {
console.log('Topic copied to clipboard:', topic); alert('Topic copied to clipboard!');
}).catch(err => { }).catch(err => {
console.error('Failed to copy topic:', err); console.error('Failed to copy topic:', err);
}); });

189
style.css
View File

@ -17,28 +17,23 @@ body {
padding: 3px 7px; padding: 3px 7px;
font-size: 14px; font-size: 14px;
font-weight: bold; font-weight: bold;
color: #ffffff; color: #fff;
background-color: #464343; background-color: #7289da;
border: none; border: none;
border-radius: 3px; border-radius: 3px;
text-decoration: none; text-decoration: none;
cursor: pointer; cursor: pointer;
transition: background-color 0.3s ease, transform 0.3s ease; }
}
.mini-button:hover { .mini-button:hover {
background-color: #181717; background-color: #0056b3;
transform: scale(1.05); }
}
.bold { .bold {
font-weight: bold; font-weight: bold;
} }
pear-ctrl[data-platform="darwin"] { pear-ctrl[data-platform="darwin"] { float: right; margin-top: 4px; }
float: right;
margin-top: 4px;
}
pear-ctrl { pear-ctrl {
margin-top: 9px; margin-top: 9px;
@ -55,7 +50,7 @@ pear-ctrl:after {
left: 0; left: 0;
top: 0; top: 0;
width: 100%; width: 100%;
background-color: #1f1f1f; background-color: #B0D94413;
filter: drop-shadow(2px 10px 6px #888); filter: drop-shadow(2px 10px 6px #888);
} }
@ -63,6 +58,7 @@ main {
display: flex; display: flex;
flex: 1; flex: 1;
overflow: hidden; overflow: hidden;
/* Ensure no overflow in main */
} }
#sidebar { #sidebar {
@ -111,21 +107,27 @@ main {
#messages-container { #messages-container {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
/* Allow vertical scrolling */
overflow-x: hidden; overflow-x: hidden;
/* Hide horizontal scrolling */
width: 100%; width: 100%;
} }
#messages-container::-webkit-scrollbar { #messages-container::-webkit-scrollbar {
width: 8px; width: 8px;
/* Set the width of the scrollbar */
} }
#messages-container::-webkit-scrollbar-thumb { #messages-container::-webkit-scrollbar-thumb {
background-color: #464343; background-color: #b0d944;
/* Set the color of the scrollbar thumb */
border-radius: 10px; border-radius: 10px;
/* Round the corners of the scrollbar thumb */
} }
#messages-container::-webkit-scrollbar-track { #messages-container::-webkit-scrollbar-track {
background: #2e2e2e; background: #2e2e2e;
/* Set the color of the scrollbar track */
} }
#message-form { #message-form {
@ -140,15 +142,19 @@ main {
margin-right: 0.5rem; margin-right: 0.5rem;
padding-right: 0.5rem; padding-right: 0.5rem;
height: 1.5rem; height: 1.5rem;
/* Initial single line height */
overflow-y: hidden; overflow-y: hidden;
/* Hide scrollbar */
} }
#message:focus { #message:focus {
height: auto; height: auto;
/* Allow the textarea to grow dynamically when focused */
} }
#message:empty { #message:empty {
height: 1.5rem; height: 1.5rem;
/* Ensure single line height when empty */
} }
#sidebar button { #sidebar button {
@ -156,17 +162,15 @@ main {
padding: 10px; padding: 10px;
margin-bottom: 10px; margin-bottom: 10px;
cursor: pointer; cursor: pointer;
background-color: #3e3c3c; background-color: #7289da;
border: none; border: none;
color: white; color: white;
font-size: 14px; font-size: 14px;
border-radius: 5px; border-radius: 5px;
transition: background-color 0.3s ease, transform 0.3s ease;
} }
#sidebar button:hover { #sidebar button:hover {
background-color: #191919; background-color: #5b6eae;
transform: scale(1.05);
} }
#remove-room-btn { #remove-room-btn {
@ -177,12 +181,10 @@ main {
color: white; color: white;
cursor: pointer; cursor: pointer;
border-radius: 5px; border-radius: 5px;
transition: background-color 0.3s ease, transform 0.3s ease;
} }
#remove-room-btn:hover { #remove-room-btn:hover {
background-color: #c03535; background-color: #c03535;
transform: scale(1.05);
} }
.hidden { .hidden {
@ -219,69 +221,53 @@ header {
padding: 0.5rem; padding: 0.5rem;
border-radius: 4px; border-radius: 4px;
cursor: pointer; cursor: pointer;
transition: background-color 0.3s ease, transform 0.3s ease; transition: background-color 0.3s ease;
} }
.window-controls button:hover { .window-controls button:hover {
background-color: #3e3e3e; background-color: #3e3e3e;
transform: scale(1.05);
} }
/* Button and input styles */ /* Button and input styles */
button, button,
input, input,
textarea { textarea {
border: 1px solid #464343; border: 1px solid #b0d944;
background-color: #333; background-color: #333;
color: #e0e0e0; color: #b0d944;
padding: 0.5rem; padding: 0.5rem;
/* Reduced padding */
font-family: 'Roboto Mono', monospace; font-family: 'Roboto Mono', monospace;
font-size: 1rem; font-size: 1rem;
line-height: 1.25rem; line-height: 1.25rem;
/* Adjusted line height */
border-radius: 4px; border-radius: 4px;
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, transform 0.3s ease; transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
resize: none; resize: none;
/* Prevent resizing */
overflow-y: hidden; overflow-y: hidden;
} /* Hide scrollbar */
button:hover,
input[type="submit"]:hover {
background-color: #191919;
transform: scale(1.05);
} }
textarea { textarea {
height: auto; height: auto;
/* Allow the textarea to grow dynamically */
} }
textarea:focus { textarea:focus {
outline: none; outline: none;
/* Remove focus outline */
} }
textarea::placeholder { textarea::placeholder {
color: #a0a0a0; color: #a0a0a0;
} }
#attach-file, #attach-file, #message-form input[type="submit"] {
#message-form input[type="submit"] { padding: 0.5rem 1rem; /* Add padding to buttons */
padding: 0.5rem 1rem; margin-left: 0.5rem; /* Add margin between buttons */
margin-left: 0.5rem;
} }
#talk-btn {
padding: 0.5rem 1rem;
margin-left: 0.5rem;
font-size: 14px;
border-radius: 5px;
cursor: pointer;
}
#talk-btn:active {
color: #fff;
background-color: #f04747;
}
/* Main container styles */ /* Main container styles */
main { main {
display: flex; display: flex;
@ -311,7 +297,7 @@ main {
#or { #or {
margin: 1.5rem 0; margin: 1.5rem 0;
color: #e0e0e0; color: #b0d944;
} }
#loading { #loading {
@ -355,12 +341,6 @@ main {
#join-chat-room-container button { #join-chat-room-container button {
margin-left: 0.5rem; margin-left: 0.5rem;
transition: background-color 0.3s ease, transform 0.3s ease;
}
#join-chat-room-container button:hover {
background-color: #191919;
transform: scale(1.05);
} }
#details { #details {
@ -372,21 +352,17 @@ main {
border-radius: 4px; border-radius: 4px;
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
/* Added to ensure box model includes padding */
} }
#details>div { #details>div {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
/* Allow peers count to stack */
} }
#submit-button { #submit-button {
margin-left: 1rem; margin-left: 1rem;
transition: background-color 0.3s ease, transform 0.3s ease;
}
#submit-button:hover {
background-color: #191919;
transform: scale(1.05);
} }
#messages { #messages {
@ -394,6 +370,7 @@ main {
min-height: 200px; min-height: 200px;
overflow-y: auto; overflow-y: auto;
padding: 0.5rem; padding: 0.5rem;
/* Reduced padding */
background-color: #262626; background-color: #262626;
border-radius: 4px; border-radius: 4px;
display: flex; display: flex;
@ -436,6 +413,7 @@ main {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
margin-bottom: 0.5rem; margin-bottom: 0.5rem;
/* Reduced margin */
} }
.message img.avatar { .message img.avatar {
@ -443,21 +421,24 @@ main {
height: 32px; height: 32px;
border-radius: 50%; border-radius: 50%;
margin-right: 0.5rem; margin-right: 0.5rem;
border: 2px solid #464343; border: 2px solid #b0d944;
} }
.message-content { .message-content {
max-width: 70%; max-width: 70%;
background-color: #2e2e2e; background-color: #2e2e2e;
padding: 0.5rem; padding: 0.5rem;
/* Reduced padding */
border-radius: 8px; border-radius: 8px;
/* Reduced border radius */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
} }
.message-header { .message-header {
font-weight: bold; font-weight: bold;
color: #e0e0e0; color: #b0d944;
font-size: 0.9rem; font-size: 0.9rem;
/* Reduced font size */
} }
.message-text { .message-text {
@ -469,82 +450,6 @@ main {
height: auto; height: auto;
margin-top: 0.5rem; margin-top: 0.5rem;
border-radius: 4px; border-radius: 4px;
/* Removed circular border */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
} }
/* Updated Room List Styles */
#room-list {
list-style: none;
padding: 0;
margin: 0;
}
#room-list li {
padding: 10px;
margin-bottom: 10px;
background-color: #3a3f44;
border-radius: 5px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
transition: background-color 0.3s ease;
}
#room-list li:hover {
background-color: #4a5258;
}
#room-list li span {
flex: 1;
}
#room-list li .edit-icon,
#room-list li .delete-icon {
margin-left: 10px;
color: #e0e0e0;
cursor: pointer;
transition: color 0.3s ease;
}
#room-list li .edit-icon:hover,
#room-list li .delete-icon:hover {
color: #a0a0a0;
}
/* Style for Edit Mode Input Box */
#room-list li input[type="text"] {
background-color: #2e2e2e;
border: 1px solid #464343;
border-radius: 5px;
color: #e0e0e0;
padding: 5px;
width: calc(100% - 40px);
margin-right: 10px;
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
#room-list li input[type="text"]:focus {
outline: none;
background-color: #3a3a3a;
}
/* Link styles */
a {
color: #e0e0e0; /* Base color for links matching the text color */
text-decoration: none; /* Remove underline */
transition: color 0.3s ease, text-decoration 0.3s ease;
}
a:hover {
color: #b0b0b0; /* Lighter color on hover */
text-decoration: underline; /* Underline on hover */
}
a:active {
color: #a0a0a0; /* Slightly darker color on active */
}
a:visited {
color: #b0b0b0; /* Different color for visited links */
}