Compare commits

..

No commits in common. "9bcf6b8b43c2610d9c957c524334340f35b7c702" and "b2276837787cb40d5fd2ddbf32b84f569ad9af14" have entirely different histories.

66
app.js
View File

@ -5,7 +5,6 @@ import ServeDrive from 'serve-drive';
import Hyperdrive from 'hyperdrive'; import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore'; import Corestore from 'corestore';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import fs from "fs";
const storagePath = `./storage/storage_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; const storagePath = `./storage/storage_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
const store = new Corestore(storagePath); const store = new Corestore(storagePath);
@ -14,6 +13,8 @@ const drive = new Hyperdrive(store);
await drive.ready(); await drive.ready();
let swarm; let swarm;
let userName = 'Anonymous';
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;
@ -22,13 +23,6 @@ const eventEmitter = new EventEmitter();
// Define servePort at the top level // Define servePort at the top level
let servePort; let servePort;
// Object to store all the information we want to save
let config = {
userName: '',
userAvatar: '',
rooms: []
};
// Function to get a random port between 1337 and 2223 // Function to get a random port between 1337 and 2223
function getRandomPort() { function getRandomPort() {
return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152;
@ -88,24 +82,15 @@ async function initialize() {
const filePath = `/files/${file.name}`; const filePath = `/files/${file.name}`;
await drive.put(filePath, buffer); await drive.put(filePath, buffer);
const fileUrl = `http://localhost:${servePort}${filePath}`; const fileUrl = `http://localhost:${servePort}${filePath}`;
sendFileMessage(config.userName, fileUrl, file.type, config.userAvatar); sendFileMessage(userName, fileUrl, file.type, userAvatar);
}; };
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(file);
} }
}); });
} }
const configExists = fs.existsSync("./config.json");
if (configExists) {
config = JSON.parse(fs.readFileSync("./config.json", 'utf8'));
console.log("Read config from file:", config)
config.rooms.forEach(room => {
addRoomToListWithoutWritingToConfig(room);
});
}
const registerDiv = document.querySelector('#register'); const registerDiv = document.querySelector('#register');
if (registerDiv && !configExists) { if (registerDiv) {
registerDiv.classList.remove('hidden'); registerDiv.classList.remove('hidden');
} }
@ -128,11 +113,11 @@ async function initialize() {
console.log('Peer connected, current peer count:', peerCount); console.log('Peer connected, current peer count:', peerCount);
// Send the current user's icon to the new peer // Send the current user's icon to the new peer
const iconBuffer = await drive.get(`/icons/${config.userName}.png`); const iconBuffer = await drive.get(`/icons/${userName}.png`);
if (iconBuffer) { if (iconBuffer) {
const iconMessage = JSON.stringify({ const iconMessage = JSON.stringify({
type: 'icon', type: 'icon',
username: config.userName, username: userName,
avatar: iconBuffer.toString('base64'), avatar: iconBuffer.toString('base64'),
}); });
connection.write(iconMessage); connection.write(iconMessage);
@ -174,8 +159,8 @@ function registerUser(e) {
reader.onload = async (event) => { reader.onload = async (event) => {
const buffer = new Uint8Array(event.target.result); const buffer = new Uint8Array(event.target.result);
await drive.put(`/icons/${regUsername}.png`, buffer); await drive.put(`/icons/${regUsername}.png`, buffer);
config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL
registeredUsers[regUsername] = config.userAvatar; registeredUsers[regUsername] = userAvatar;
localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers)); localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
continueRegistration(regUsername); continueRegistration(regUsername);
}; };
@ -194,15 +179,13 @@ async function continueRegistration(regUsername) {
return; return;
} }
config.userName = regUsername; 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 = truncateHash(b4a.toString(randomTopic, 'hex'));
writeConfigToFile("./config.json");
} }
async function createChatRoom() { async function createChatRoom() {
@ -247,18 +230,6 @@ function addRoomToList(topic) {
roomItem.dataset.topic = topic; roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic)); roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem); roomList.appendChild(roomItem);
config.rooms.push(topic);
writeConfigToFile("./config.json");
}
function addRoomToListWithoutWritingToConfig(topic) {
const roomList = document.querySelector('#room-list');
const roomItem = document.createElement('li');
roomItem.textContent = truncateHash(topic);
roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem);
} }
function switchRoom(topic) { function switchRoom(topic) {
@ -278,9 +249,6 @@ function leaveRoom() {
} }
document.querySelector('#chat').classList.add('hidden'); document.querySelector('#chat').classList.add('hidden');
document.querySelector('#setup').classList.remove('hidden'); document.querySelector('#setup').classList.remove('hidden');
config.rooms = config.rooms.filter(e => e !== currentRoom.topic);
writeConfigToFile("./config.json");
} }
function sendMessage(e) { function sendMessage(e) {
@ -288,13 +256,13 @@ function sendMessage(e) {
const message = document.querySelector('#message').value; const message = document.querySelector('#message').value;
document.querySelector('#message').value = ''; document.querySelector('#message').value = '';
onMessageAdded(config.userName, message, config.userAvatar); onMessageAdded(userName, message, userAvatar);
const messageObj = JSON.stringify({ const messageObj = JSON.stringify({
type: 'message', type: 'message',
name: config.userName, name: userName,
message, message,
avatar: config.userAvatar, avatar: userAvatar,
timestamp: Date.now(), timestamp: Date.now(),
}); });
@ -413,9 +381,6 @@ async function updateIcon(username, avatarBuffer) {
const avatarBlob = new Blob([avatarBuffer], { type: 'image/png' }); const avatarBlob = new Blob([avatarBuffer], { type: 'image/png' });
const avatarUrl = URL.createObjectURL(avatarBlob); const avatarUrl = URL.createObjectURL(avatarBlob);
userIcon.src = avatarUrl; userIcon.src = avatarUrl;
config.userAvatar = avatarUrl;
writeConfigToFile("./config.json");
} }
} }
@ -431,11 +396,4 @@ function toggleSetupView() {
setupDiv.classList.toggle('hidden'); setupDiv.classList.toggle('hidden');
} }
function writeConfigToFile(filePath) {
fs.writeFile(filePath, JSON.stringify(config), (err) => {
if (err) return console.error(err);
console.log("File has been created");
});
}
initialize(); initialize();