This commit is contained in:
Raven Scott 2024-06-08 16:13:20 -04:00
parent d0310247c5
commit c15b298268

23
app.js
View File

@ -6,6 +6,7 @@ import Localdrive from 'localdrive';
import fs from 'fs'; import fs from 'fs';
import Hyperdrive from 'hyperdrive'; import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore'; import Corestore from 'corestore';
import { EventEmitter } from 'events';
const store = new Corestore('./storage'); const store = new Corestore('./storage');
const drive = new Hyperdrive(store); const drive = new Hyperdrive(store);
@ -18,6 +19,7 @@ let userAvatar = '';
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
let peerCount = 0; let peerCount = 0;
let currentRoom = null; let currentRoom = null;
const eventEmitter = new EventEmitter();
async function initialize() { async function initialize() {
swarm = new Hyperswarm(); swarm = new Hyperswarm();
@ -64,6 +66,16 @@ async function initialize() {
registerDiv.classList.remove('hidden'); registerDiv.classList.remove('hidden');
} }
eventEmitter.on('onMessage', (messageObj) => {
if (messageObj.type === 'icon') {
const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
updateIcon(username, avatarBuffer);
} else {
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
});
swarm.on('connection', async (connection, info) => { swarm.on('connection', async (connection, info) => {
peerCount++; peerCount++;
updatePeerCount(); updatePeerCount();
@ -80,16 +92,9 @@ async function initialize() {
connection.write(iconMessage); connection.write(iconMessage);
} }
connection.on('data', async (data) => { connection.on('data', (data) => {
const messageObj = JSON.parse(data.toString()); const messageObj = JSON.parse(data.toString());
if (messageObj.type === 'icon') { eventEmitter.emit('onMessage', messageObj);
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', () => {