Compare commits

...

17 Commits

Author SHA1 Message Date
9bcf6b8b43 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!
2024-06-09 07:11:48 +00:00
MrMasrozYTLIVE
0077989253 It acutally works just fine now yay 2024-06-09 10:08:29 +03:00
MrMasrozYTLIVE
f3b4755821 Very strange stuff tbh 2024-06-09 10:03:23 +03:00
MrMasrozYTLIVE
f6f804ab39 It actually works now but i want to get it to work properly 2024-06-09 10:01:01 +03:00
MrMasrozYTLIVE
f5f8d0ce19 And I honestly have no idea why it doesnt want to work 2024-06-09 10:00:01 +03:00
MrMasrozYTLIVE
13e4020920 It just doesnt want to put proper data to the config for some strange reason 2024-06-09 09:58:35 +03:00
MrMasrozYTLIVE
4a881ed721 Its actually not the reason... 2024-06-09 09:57:11 +03:00
MrMasrozYTLIVE
2befd34039 Ohh reading is async, thats why it didnt work 2024-06-09 09:56:12 +03:00
MrMasrozYTLIVE
b577ff3207 It doesnt want to use config for some reason. Time to debug stuff 2024-06-09 09:54:30 +03:00
MrMasrozYTLIVE
8ca1cc2b8f I just forgot to read from the file LOL 2024-06-09 09:53:11 +03:00
MrMasrozYTLIVE
a3fbe7434a Hmm will it work this way? 2024-06-09 09:50:05 +03:00
MrMasrozYTLIVE
a9f50e892b Oopsie checking if config exists didnt work (It is done by checking if username is not empty lol) 2024-06-09 09:46:42 +03:00
MrMasrozYTLIVE
1271c48571 Mostly finished loading. User avatar stuff is left to do 😭 2024-06-09 09:44:52 +03:00
MrMasrozYTLIVE
d33d31debf Got rid of userName and userAvatar in exchange of config.userName and config.userAvatar 2024-06-09 09:32:33 +03:00
MrMasrozYTLIVE
89ebe02743 Merge branch 'main' of https://git.ssh.surf/snxraven/LinkUp-P2P-Chat 2024-06-09 09:29:39 +03:00
MrMasrozYTLIVE
c2e1242d8b Merge branch 'main' of https://git.ssh.surf/snxraven/LinkUp-P2P-Chat
This is automatic merge of FileUploading and Config commits.
2024-06-09 09:24:04 +03:00
MrMasrozYTLIVE
3947e78aef Started working on saving the user data on actions like registration, joining and leaving rooms. Lacks of loading on start up. 2024-06-09 09:23:45 +03:00

66
app.js
View File

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