This commit is contained in:
Raven Scott 2024-06-08 15:16:28 -04:00
parent 9e6c803347
commit 310f1bd14d

220
app.js
View File

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