Up to date fork #1

Merged
MiTask merged 33 commits from snxraven/LinkUp-P2P-Chat:main into main 2024-06-14 04:32:25 -04:00
Showing only changes of commit b1ea06018b - Show all commits

286
app.js
View File

@ -14,7 +14,6 @@ const drive = new Hyperdrive(store);
await drive.ready(); await drive.ready();
let swarm; let swarm;
let peerCount = 0;
let activeRooms = []; let activeRooms = [];
const eventEmitter = new EventEmitter(); const eventEmitter = new EventEmitter();
@ -46,151 +45,28 @@ async function initialize() {
await serve.ready(); await serve.ready();
console.log('Listening on http://localhost:' + serve.address().port); console.log('Listening on http://localhost:' + serve.address().port);
const registerForm = document.querySelector('#register-form'); // Event listeners setup
const selectAvatarButton = document.querySelector('#select-avatar'); setupEventListeners();
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();
}
const configExists = fs.existsSync("./config.json"); const configExists = fs.existsSync("./config.json");
if (configExists) { if (configExists) {
config = JSON.parse(fs.readFileSync("./config.json", 'utf8')); loadConfigFromFile();
console.log("Read config from file:", config); renderRoomList();
// Update port in URLs await connectToAllRooms();
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);
}
} }
const registerDiv = document.querySelector('#register'); if (!configExists) {
if (registerDiv && !configExists) { document.querySelector('#register').classList.remove('hidden');
registerDiv.classList.remove('hidden');
} }
eventEmitter.on('onMessage', async (messageObj) => { eventEmitter.on('onMessage', async (messageObj) => {
console.log('Received message:', messageObj); // Debugging log handleIncomingMessage(messageObj);
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);
}
}); });
swarm.on('connection', async (connection, info) => { swarm.on('connection', handleConnection);
peerCount++; swarm.on('error', (err) => console.error('Swarm error:', err));
updatePeerCount(); swarm.on('close', () => console.log('Swarm closed'));
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) => { document.addEventListener("DOMContentLoaded", (event) => {
hljs.highlightAll(); 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() { function setupTalkButton() {
const talkButton = document.getElementById('talk-btn'); const talkButton = document.getElementById('talk-btn');
if (!talkButton) return; if (!talkButton) return;
@ -334,6 +323,7 @@ async function joinSwarm(topicBuffer) {
console.log('Joined room:', topic); // Debugging log console.log('Joined room:', topic); // Debugging log
renderMessagesForRoom(topic); renderMessagesForRoom(topic);
updatePeerCount();
} catch (error) { } catch (error) {
console.error('Error joining swarm for topic:', topic, error); console.error('Error joining swarm for topic:', topic, error);
} }
@ -429,6 +419,7 @@ 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');
@ -571,7 +562,7 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
function updatePeerCount() { function updatePeerCount() {
const peerCountElement = document.querySelector('#peers-count'); const peerCountElement = document.querySelector('#peers-count');
if (peerCountElement) { 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); 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 // Call this function when loading the rooms initially
renderRoomList(); renderRoomList();
initialize(); initialize();