testing EventEmitter

This commit is contained in:
Raven Scott 2024-06-08 15:06:24 -04:00
parent 20aa777270
commit 9e6c803347

173
app.js
View File

@ -1,3 +1,4 @@
import { EventEmitter } from 'events';
import Hyperswarm from 'hyperswarm'; import Hyperswarm from 'hyperswarm';
import crypto from 'hypercore-crypto'; import crypto from 'hypercore-crypto';
import b4a from 'b4a'; import b4a from 'b4a';
@ -12,16 +13,20 @@ const drive = new Hyperdrive(store);
await drive.ready(); await drive.ready();
let swarm; class ChatHandler extends EventEmitter {
let userName = 'Anonymous'; constructor() {
let userAvatar = ''; super();
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; this.userName = 'Anonymous';
let peerCount = 0; this.userAvatar = '';
let currentRoom = null; this.registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
this.peerCount = 0;
this.currentRoom = null;
this.swarm = new Hyperswarm();
async function initialize() { this.initialize();
swarm = new Hyperswarm(); }
async initialize() {
const servePort = 1337; const servePort = 1337;
const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive }); const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive });
await serve.ready(); await serve.ready();
@ -36,7 +41,7 @@ async function initialize() {
const removeRoomBtn = document.querySelector('#remove-room-btn'); const removeRoomBtn = document.querySelector('#remove-room-btn');
if (registerForm) { if (registerForm) {
registerForm.addEventListener('submit', registerUser); registerForm.addEventListener('submit', (e) => this.registerUser(e));
} }
if (selectAvatarButton) { if (selectAvatarButton) {
selectAvatarButton.addEventListener('click', () => { selectAvatarButton.addEventListener('click', () => {
@ -44,19 +49,19 @@ async function initialize() {
}); });
} }
if (createChatRoomButton) { if (createChatRoomButton) {
createChatRoomButton.addEventListener('click', createChatRoom); createChatRoomButton.addEventListener('click', () => this.createChatRoom());
} }
if (joinChatRoomButton) { if (joinChatRoomButton) {
joinChatRoomButton.addEventListener('click', joinChatRoom); joinChatRoomButton.addEventListener('click', (e) => this.joinChatRoom(e));
} }
if (messageForm) { if (messageForm) {
messageForm.addEventListener('submit', sendMessage); messageForm.addEventListener('submit', (e) => this.sendMessage(e));
} }
if (toggleSetupBtn) { if (toggleSetupBtn) {
toggleSetupBtn.addEventListener('click', toggleSetupView); toggleSetupBtn.addEventListener('click', () => this.toggleSetupView());
} }
if (removeRoomBtn) { if (removeRoomBtn) {
removeRoomBtn.addEventListener('click', leaveRoom); removeRoomBtn.addEventListener('click', () => this.leaveRoom());
} }
const registerDiv = document.querySelector('#register'); const registerDiv = document.querySelector('#register');
@ -64,52 +69,43 @@ async function initialize() {
registerDiv.classList.remove('hidden'); registerDiv.classList.remove('hidden');
} }
swarm.on('connection', async (connection, info) => { this.swarm.on('connection', async (connection, info) => {
peerCount++; this.peerCount++;
updatePeerCount(); this.updatePeerCount();
const iconBuffer = await drive.get(`/icons/${userName}.png`); const iconBuffer = await drive.get(`/icons/${this.userName}.png`);
if (iconBuffer) { if (iconBuffer) {
const iconMessage = JSON.stringify({ const iconMessage = JSON.stringify({
type: 'icon', type: 'icon',
username: userName, username: this.userName,
avatar: iconBuffer.toString('base64'), avatar: iconBuffer.toString('base64'),
}); });
connection.write(iconMessage); connection.write(iconMessage);
} }
connection.on('data', async (data) => { connection.on('data', (data) => this.emit('onMessage', data, connection));
const messageObj = JSON.parse(data.toString());
if (messageObj.type === 'icon') {
const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
await drive.put(`/icons/${username}.png`, avatarBuffer);
updateIcon(username, avatarBuffer);
} else {
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
});
connection.on('close', () => { connection.on('close', () => {
peerCount--; this.peerCount--;
updatePeerCount(); this.updatePeerCount();
}); });
}); });
swarm.on('error', (err) => { this.swarm.on('error', (err) => {
console.error('Swarm error:', err); console.error('Swarm error:', err);
}); });
swarm.on('close', () => { this.swarm.on('close', () => {
console.log('Swarm closed'); console.log('Swarm closed');
}); });
this.on('onMessage', async (data, connection) => this.handleMessage(data, connection));
} }
function registerUser(e) { async registerUser(e) {
e.preventDefault(); e.preventDefault();
const regUsername = document.querySelector('#reg-username').value; const regUsername = document.querySelector('#reg-username').value;
if (registeredUsers[regUsername]) { if (this.registeredUsers[regUsername]) {
alert('Username already taken. Please choose another.'); alert('Username already taken. Please choose another.');
return; return;
} }
@ -120,18 +116,18 @@ function registerUser(e) {
reader.onload = (event) => { reader.onload = (event) => {
const buffer = new Uint8Array(event.target.result); const buffer = new Uint8Array(event.target.result);
drive.put(`/icons/${regUsername}.png`, buffer); drive.put(`/icons/${regUsername}.png`, buffer);
userAvatar = URL.createObjectURL(new Blob([buffer])); this.userAvatar = URL.createObjectURL(new Blob([buffer]));
registeredUsers[regUsername] = userAvatar; this.registeredUsers[regUsername] = this.userAvatar;
localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers)); localStorage.setItem('registeredUsers', JSON.stringify(this.registeredUsers));
continueRegistration(regUsername); this.continueRegistration(regUsername);
}; };
reader.readAsArrayBuffer(avatarFile); reader.readAsArrayBuffer(avatarFile);
} else { } else {
continueRegistration(regUsername); this.continueRegistration(regUsername);
} }
} }
async function continueRegistration(regUsername) { async continueRegistration(regUsername) {
const loadingDiv = document.querySelector('#loading'); const loadingDiv = document.querySelector('#loading');
const setupDiv = document.querySelector('#setup'); const setupDiv = document.querySelector('#setup');
@ -140,39 +136,39 @@ async function continueRegistration(regUsername) {
return; return;
} }
userName = regUsername; this.userName = regUsername;
setupDiv.classList.remove('hidden'); setupDiv.classList.remove('hidden');
document.querySelector('#register').classList.add('hidden'); document.querySelector('#register').classList.add('hidden');
loadingDiv.classList.add('hidden'); loadingDiv.classList.add('hidden');
const randomTopic = crypto.randomBytes(32); const randomTopic = crypto.randomBytes(32);
document.querySelector('#chat-room-topic').innerText = truncateHash(b4a.toString(randomTopic, 'hex')); document.querySelector('#chat-room-topic').innerText = this.truncateHash(b4a.toString(randomTopic, 'hex'));
} }
async function createChatRoom() { async createChatRoom() {
const topicBuffer = crypto.randomBytes(32); const topicBuffer = crypto.randomBytes(32);
const topic = b4a.toString(topicBuffer, 'hex'); const topic = b4a.toString(topicBuffer, 'hex');
addRoomToList(topic); this.addRoomToList(topic);
joinSwarm(topicBuffer); this.joinSwarm(topicBuffer);
} }
async function joinChatRoom(e) { async joinChatRoom(e) {
e.preventDefault(); e.preventDefault();
const topicStr = document.querySelector('#join-chat-room-topic').value; const topicStr = document.querySelector('#join-chat-room-topic').value;
const topicBuffer = b4a.from(topicStr, 'hex'); const topicBuffer = b4a.from(topicStr, 'hex');
addRoomToList(topicStr); this.addRoomToList(topicStr);
joinSwarm(topicBuffer); this.joinSwarm(topicBuffer);
} }
async function joinSwarm(topicBuffer) { async joinSwarm(topicBuffer) {
if (currentRoom) { if (this.currentRoom) {
currentRoom.destroy(); this.currentRoom.destroy();
} }
document.querySelector('#setup').classList.add('hidden'); document.querySelector('#setup').classList.add('hidden');
document.querySelector('#loading').classList.remove('hidden'); document.querySelector('#loading').classList.remove('hidden');
const discovery = swarm.join(topicBuffer, { client: true, server: true }); const discovery = this.swarm.join(topicBuffer, { client: true, server: true });
await discovery.flushed(); await discovery.flushed();
const topic = b4a.toString(topicBuffer, 'hex'); const topic = b4a.toString(topicBuffer, 'hex');
@ -180,65 +176,77 @@ async function joinSwarm(topicBuffer) {
document.querySelector('#loading').classList.add('hidden'); document.querySelector('#loading').classList.add('hidden');
document.querySelector('#chat').classList.remove('hidden'); document.querySelector('#chat').classList.remove('hidden');
currentRoom = discovery; this.currentRoom = discovery;
clearMessages(); this.clearMessages();
} }
function addRoomToList(topic) { 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 = truncateHash(topic); roomItem.textContent = this.truncateHash(topic);
roomItem.dataset.topic = topic; roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic)); roomItem.addEventListener('click', () => this.switchRoom(topic));
roomList.appendChild(roomItem); roomList.appendChild(roomItem);
} }
function switchRoom(topic) { switchRoom(topic) {
const topicBuffer = b4a.from(topic, 'hex'); const topicBuffer = b4a.from(topic, 'hex');
joinSwarm(topicBuffer); this.joinSwarm(topicBuffer);
} }
function leaveRoom() { leaveRoom() {
if (currentRoom) { if (this.currentRoom) {
const topic = b4a.toString(currentRoom.topic, 'hex'); const topic = b4a.toString(this.currentRoom.topic, 'hex');
const roomItem = document.querySelector(`li[data-topic="${topic}"]`); const roomItem = document.querySelector(`li[data-topic="${topic}"]`);
if (roomItem) { if (roomItem) {
roomItem.remove(); roomItem.remove();
} }
currentRoom.destroy(); this.currentRoom.destroy();
currentRoom = null; this.currentRoom = null;
} }
document.querySelector('#chat').classList.add('hidden'); document.querySelector('#chat').classList.add('hidden');
document.querySelector('#setup').classList.remove('hidden'); document.querySelector('#setup').classList.remove('hidden');
} }
function sendMessage(e) { 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 = '';
onMessageAdded(userName, message, userAvatar); this.onMessageAdded(this.userName, message, this.userAvatar);
const messageObj = JSON.stringify({ const messageObj = JSON.stringify({
type: 'message', type: 'message',
name: userName, name: this.userName,
message, message,
avatar: userAvatar, avatar: this.userAvatar,
timestamp: Date.now(), timestamp: Date.now(),
}); });
const peers = [...swarm.connections]; const peers = [...this.swarm.connections];
for (const peer of peers) { for (const peer of peers) {
peer.write(messageObj); peer.write(messageObj);
} }
} }
function scrollToBottom() { async handleMessage(data, connection) {
const messageObj = JSON.parse(data.toString());
if (messageObj.type === 'icon') {
const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
await drive.put(`/icons/${username}.png`, avatarBuffer);
this.updateIcon(username, avatarBuffer);
} else {
this.onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
}
scrollToBottom() {
var container = document.getElementById("messages-container"); var container = document.getElementById("messages-container");
container.scrollTop = container.scrollHeight; container.scrollTop = container.scrollHeight;
} }
function onMessageAdded(from, message, avatar) { onMessageAdded(from, message, avatar) {
const $div = document.createElement('div'); const $div = document.createElement('div');
$div.classList.add('message'); $div.classList.add('message');
@ -265,30 +273,35 @@ function onMessageAdded(from, message, avatar) {
$div.appendChild($content); $div.appendChild($content);
document.querySelector('#messages').appendChild($div); document.querySelector('#messages').appendChild($div);
scrollToBottom(); this.scrollToBottom();
} }
function truncateHash(hash) { truncateHash(hash) {
return `${hash.slice(0, 6)}...${hash.slice(-6)}`; return `${hash.slice(0, 6)}...${hash.slice(-6)}`;
} }
async function updateIcon(username, avatarBuffer) { async updateIcon(username, avatarBuffer) {
const userIcon = document.querySelector(`img[src*="${username}.png"]`); const userIcon = document.querySelector(`img[src*="${username}.png"]`);
if (userIcon) { if (userIcon) {
userIcon.src = URL.createObjectURL(new Blob([avatarBuffer])); userIcon.src = URL.createObjectURL(new Blob([avatarBuffer]));
} }
} }
function clearMessages() { 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);
} }
} }
function toggleSetupView() { toggleSetupView() {
const setupDiv = document.querySelector('#setup'); const setupDiv = document.querySelector('#setup');
setupDiv.classList.toggle('hidden'); setupDiv.classList.toggle('hidden');
} }
initialize(); updatePeerCount() {
// Implement this method based on your needs to update the peer count in the UI
}
}
new ChatHandler();