Merge pull request 'Working on Config system (Saving & Loading user data)' (#3) from MiTask/LinkUp-P2P-Chat:main into main

Reviewed-on: #3

Well done!
This commit is contained in:
snxraven 2024-06-09 07:11:48 +00:00
commit 9bcf6b8b43

66
app.js
View File

@ -5,6 +5,7 @@ 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);
@ -13,8 +14,6 @@ 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;
@ -23,6 +22,13 @@ 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;
@ -82,15 +88,24 @@ 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(userName, fileUrl, file.type, userAvatar); sendFileMessage(config.userName, fileUrl, file.type, config.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) { if (registerDiv && !configExists) {
registerDiv.classList.remove('hidden'); registerDiv.classList.remove('hidden');
} }
@ -113,11 +128,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/${userName}.png`); const iconBuffer = await drive.get(`/icons/${config.userName}.png`);
if (iconBuffer) { if (iconBuffer) {
const iconMessage = JSON.stringify({ const iconMessage = JSON.stringify({
type: 'icon', type: 'icon',
username: userName, username: config.userName,
avatar: iconBuffer.toString('base64'), avatar: iconBuffer.toString('base64'),
}); });
connection.write(iconMessage); connection.write(iconMessage);
@ -159,8 +174,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);
userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL
registeredUsers[regUsername] = userAvatar; registeredUsers[regUsername] = config.userAvatar;
localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers)); localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
continueRegistration(regUsername); continueRegistration(regUsername);
}; };
@ -179,13 +194,15 @@ async function continueRegistration(regUsername) {
return; return;
} }
userName = regUsername; config.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() {
@ -230,6 +247,18 @@ 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) {
@ -249,6 +278,9 @@ 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) {
@ -256,13 +288,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(userName, message, userAvatar); onMessageAdded(config.userName, message, config.userAvatar);
const messageObj = JSON.stringify({ const messageObj = JSON.stringify({
type: 'message', type: 'message',
name: userName, name: config.userName,
message, message,
avatar: userAvatar, avatar: config.userAvatar,
timestamp: Date.now(), timestamp: Date.now(),
}); });
@ -381,6 +413,9 @@ 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");
} }
} }
@ -396,4 +431,11 @@ 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();