This commit is contained in:
Raven Scott 2024-06-03 19:42:30 -04:00
parent c58671dc7d
commit 6e171c5ffa

116
app.js
View File

@ -1,25 +1,29 @@
// Import required modules
import Hyperswarm from 'hyperswarm';
import crypto from 'hypercore-crypto';
import b4a from 'b4a';
import ServeDrive from 'serve-drive';
import Localdrive from 'localdrive';
// Create instances for local drive and Hyperswarm
const drive = new Localdrive('./storage');
let swarm;
let userName = 'Anonymous';
let userAvatar = '';
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
let peerCount = 0;
// Initialize the application
async function initialize() {
swarm = new Hyperswarm();
// Ensure the local drive is ready
await drive.ready();
// Set up ServeDrive
const servePort = 1337;
const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive });
await serve.ready();
console.log('Listening on http://localhost:' + serve.address().port);
// Set up event listeners for UI elements
const registerForm = document.querySelector('#register-form');
const selectAvatarButton = document.querySelector('#select-avatar');
const createChatRoomButton = document.querySelector('#create-chat-room');
@ -44,6 +48,43 @@ async function initialize() {
messageForm.addEventListener('submit', sendMessage);
}
// Listen for connections from peers
swarm.on('connection', (connection, info) => {
peerCount++;
updatePeerCount();
// Handle data received from peers
connection.on('data', async (data) => {
const messageObj = JSON.parse(data.toString());
if (messageObj.type === 'avatarRequest') {
// Respond to avatar request by sending the requested avatar
const avatarBuffer = await getAvatar(messageObj.username);
if (avatarBuffer) {
connection.write(avatarBuffer);
}
} else {
// Handle other types of messages
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
});
// Handle disconnection of peers
connection.on('close', () => {
peerCount--;
updatePeerCount();
});
});
// Error and close event handlers for the swarm
swarm.on('error', (err) => {
console.error('Swarm error:', err);
});
swarm.on('close', () => {
console.log('Swarm closed.');
});
// Perform any additional setup tasks
const savedUser = localStorage.getItem('currentUser');
if (savedUser) {
const user = JSON.parse(savedUser);
@ -59,29 +100,56 @@ async function initialize() {
registerDiv.classList.remove('hidden');
}
}
swarm.on('connection', (connection, info) => {
peerCount++;
updatePeerCount();
connection.on('data', (data) => {
const messageObj = JSON.parse(data.toString());
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
});
connection.on('close', () => {
peerCount--;
updatePeerCount();
});
});
swarm.on('error', (err) => {
console.error('Swarm error:', err);
});
swarm.on('close', () => {
console.log('Swarm closed.');
});
}
// Function to get the avatar for a given username
async function getAvatar(username) {
try {
// Check if the avatar exists locally
const avatarPath = `./storage/icons/${username}.png`;
const avatarBuffer = await drive.get(avatarPath);
return avatarBuffer;
} catch (error) {
console.error('Error getting avatar:', error);
return null;
}
}
// Function to update the count of connected peers in the UI
function updatePeerCount() {
const peersCountElement = document.querySelector('#peers-count');
if (peersCountElement) {
peersCountElement.textContent = peerCount;
}
}
// Function to handle incoming messages from peers
function onMessageAdded(from, message, avatar) {
const $div = document.createElement('div');
$div.classList.add('message');
const $img = document.createElement('img');
$img.src = avatar || 'https://via.placeholder.com/40';
$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;
const $text = document.createElement('div');
$text.textContent = message;
$content.appendChild($header);
$content.appendChild($text);
$div.appendChild($content);
document.querySelector('#messages').appendChild($div);
}
function updatePeerCount() {
const peersCountElement = document.querySelector('#peers-count');
if (peersCountElement) {