Using swarm.connections.size
This commit is contained in:
parent
116b23d70f
commit
b1ea06018b
126
app.js
126
app.js
@ -14,7 +14,6 @@ const drive = new Hyperdrive(store);
|
||||
await drive.ready();
|
||||
|
||||
let swarm;
|
||||
let peerCount = 0;
|
||||
let activeRooms = [];
|
||||
const eventEmitter = new EventEmitter();
|
||||
|
||||
@ -46,6 +45,37 @@ async function initialize() {
|
||||
await serve.ready();
|
||||
console.log('Listening on http://localhost:' + serve.address().port);
|
||||
|
||||
// Event listeners setup
|
||||
setupEventListeners();
|
||||
|
||||
const configExists = fs.existsSync("./config.json");
|
||||
if (configExists) {
|
||||
loadConfigFromFile();
|
||||
renderRoomList();
|
||||
await connectToAllRooms();
|
||||
}
|
||||
|
||||
if (!configExists) {
|
||||
document.querySelector('#register').classList.remove('hidden');
|
||||
}
|
||||
|
||||
eventEmitter.on('onMessage', async (messageObj) => {
|
||||
handleIncomingMessage(messageObj);
|
||||
});
|
||||
|
||||
swarm.on('connection', handleConnection);
|
||||
swarm.on('error', (err) => console.error('Swarm error:', err));
|
||||
swarm.on('close', () => console.log('Swarm closed'));
|
||||
|
||||
document.addEventListener("DOMContentLoaded", (event) => {
|
||||
hljs.highlightAll();
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error during initialization:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
const registerForm = document.querySelector('#register-form');
|
||||
const selectAvatarButton = document.querySelector('#select-avatar');
|
||||
const createChatRoomButton = document.querySelector('#create-chat-room');
|
||||
@ -92,52 +122,28 @@ async function initialize() {
|
||||
if (talkButton) {
|
||||
setupTalkButton();
|
||||
}
|
||||
}
|
||||
|
||||
const configExists = fs.existsSync("./config.json");
|
||||
if (configExists) {
|
||||
config = JSON.parse(fs.readFileSync("./config.json", 'utf8'));
|
||||
console.log("Read config from file:", config);
|
||||
// Update port in URLs
|
||||
config.userAvatar = updatePortInUrl(config.userAvatar);
|
||||
config.rooms.forEach(room => {
|
||||
room.alias = room.alias || truncateHash(room.topic);
|
||||
});
|
||||
for (let user in config.registeredUsers) {
|
||||
config.registeredUsers[user] = updatePortInUrl(config.registeredUsers[user]);
|
||||
}
|
||||
|
||||
renderRoomList(); // Render the room list with aliases
|
||||
|
||||
// Connect to all rooms on startup
|
||||
for (const room of config.rooms) {
|
||||
const topicBuffer = b4a.from(room.topic, 'hex');
|
||||
await joinSwarm(topicBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
const registerDiv = document.querySelector('#register');
|
||||
if (registerDiv && !configExists) {
|
||||
registerDiv.classList.remove('hidden');
|
||||
}
|
||||
|
||||
eventEmitter.on('onMessage', async (messageObj) => {
|
||||
function handleIncomingMessage(messageObj) {
|
||||
console.log('Received message:', messageObj); // Debugging log
|
||||
|
||||
if (messageObj.type === 'icon') {
|
||||
const username = messageObj.username;
|
||||
if (messageObj.avatar) {
|
||||
const avatarBuffer = b4a.from(messageObj.avatar, 'base64');
|
||||
await drive.put(`/icons/${username}.png`, avatarBuffer);
|
||||
drive.put(`/icons/${username}.png`, avatarBuffer).then(() => {
|
||||
updateIcon(username, avatarBuffer);
|
||||
});
|
||||
} else {
|
||||
console.error('Received icon message with missing avatar data:', messageObj);
|
||||
}
|
||||
} else if (messageObj.type === 'file') {
|
||||
if (messageObj.file && messageObj.fileName) {
|
||||
const fileBuffer = b4a.from(messageObj.file, 'base64');
|
||||
await drive.put(`/files/${messageObj.fileName}`, fileBuffer);
|
||||
drive.put(`/files/${messageObj.fileName}`, fileBuffer).then(() => {
|
||||
const fileUrl = `http://localhost:${servePort}/files/${messageObj.fileName}`;
|
||||
addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic);
|
||||
});
|
||||
} else {
|
||||
console.error('Received file message with missing file data or fileName:', messageObj);
|
||||
}
|
||||
@ -146,21 +152,21 @@ async function initialize() {
|
||||
} else if (messageObj.type === 'audio') {
|
||||
const audioBuffer = b4a.from(messageObj.audio, 'base64');
|
||||
const filePath = `/audio/${Date.now()}.webm`;
|
||||
await drive.put(filePath, audioBuffer);
|
||||
drive.put(filePath, audioBuffer).then(() => {
|
||||
const audioUrl = `http://localhost:${servePort}${filePath}`;
|
||||
addAudioMessage(messageObj.name, audioUrl, messageObj.avatar, messageObj.topic);
|
||||
});
|
||||
} else {
|
||||
console.error('Received unknown message type:', messageObj);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
swarm.on('connection', async (connection, info) => {
|
||||
peerCount++;
|
||||
function handleConnection(connection, info) {
|
||||
updatePeerCount();
|
||||
console.log('Peer connected, current peer count:', peerCount);
|
||||
console.log('Peer connected, current peer count:', swarm.connections.size);
|
||||
|
||||
// Send the current user's icon to the new peer
|
||||
const iconBuffer = await drive.get(`/icons/${config.userName}.png`);
|
||||
drive.get(`/icons/${config.userName}.png`).then(iconBuffer => {
|
||||
if (iconBuffer) {
|
||||
const iconMessage = JSON.stringify({
|
||||
type: 'icon',
|
||||
@ -169,6 +175,7 @@ async function initialize() {
|
||||
});
|
||||
connection.write(iconMessage);
|
||||
}
|
||||
});
|
||||
|
||||
connection.on('data', (data) => {
|
||||
const messageObj = JSON.parse(data.toString());
|
||||
@ -176,27 +183,9 @@ async function initialize() {
|
||||
});
|
||||
|
||||
connection.on('close', () => {
|
||||
peerCount--;
|
||||
updatePeerCount();
|
||||
console.log('Peer disconnected, current peer count:', peerCount);
|
||||
console.log('Peer disconnected, current peer count:', swarm.connections.size);
|
||||
});
|
||||
});
|
||||
|
||||
swarm.on('error', (err) => {
|
||||
console.error('Swarm error:', err);
|
||||
});
|
||||
|
||||
swarm.on('close', () => {
|
||||
console.log('Swarm closed');
|
||||
});
|
||||
|
||||
// Initialize highlight.js once the DOM is fully loaded
|
||||
document.addEventListener("DOMContentLoaded", (event) => {
|
||||
hljs.highlightAll();
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error during initialization:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function setupTalkButton() {
|
||||
@ -334,6 +323,7 @@ async function joinSwarm(topicBuffer) {
|
||||
console.log('Joined room:', topic); // Debugging log
|
||||
|
||||
renderMessagesForRoom(topic);
|
||||
updatePeerCount();
|
||||
} catch (error) {
|
||||
console.error('Error joining swarm for topic:', topic, error);
|
||||
}
|
||||
@ -429,6 +419,7 @@ function switchRoom(topic) {
|
||||
|
||||
clearMessages();
|
||||
renderMessagesForRoom(topic);
|
||||
updatePeerCount();
|
||||
|
||||
// Show chat UI elements
|
||||
document.querySelector('#chat').classList.remove('hidden');
|
||||
@ -571,7 +562,7 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
|
||||
function updatePeerCount() {
|
||||
const peerCountElement = document.querySelector('#peers-count');
|
||||
if (peerCountElement) {
|
||||
peerCountElement.textContent = peerCount; // Display the actual peer count
|
||||
peerCountElement.textContent = swarm.connections.size; // Display the actual peer count
|
||||
}
|
||||
}
|
||||
|
||||
@ -756,6 +747,27 @@ function addMessageToStore(topic, messageObj) {
|
||||
messagesStore[topic].push(messageObj);
|
||||
}
|
||||
|
||||
function loadConfigFromFile() {
|
||||
config = JSON.parse(fs.readFileSync("./config.json", 'utf8'));
|
||||
console.log("Read config from file:", config);
|
||||
// Update port in URLs
|
||||
config.userAvatar = updatePortInUrl(config.userAvatar);
|
||||
config.rooms.forEach(room => {
|
||||
room.alias = room.alias || truncateHash(room.topic);
|
||||
});
|
||||
for (let user in config.registeredUsers) {
|
||||
config.registeredUsers[user] = updatePortInUrl(config.registeredUsers[user]);
|
||||
}
|
||||
}
|
||||
|
||||
async function connectToAllRooms() {
|
||||
// Connect to all rooms on startup
|
||||
for (const room of config.rooms) {
|
||||
const topicBuffer = b4a.from(room.topic, 'hex');
|
||||
await joinSwarm(topicBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Call this function when loading the rooms initially
|
||||
renderRoomList();
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user