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();
|
await drive.ready();
|
||||||
|
|
||||||
let swarm;
|
let swarm;
|
||||||
let peerCount = 0;
|
|
||||||
let activeRooms = [];
|
let activeRooms = [];
|
||||||
const eventEmitter = new EventEmitter();
|
const eventEmitter = new EventEmitter();
|
||||||
|
|
||||||
@ -46,6 +45,37 @@ async function initialize() {
|
|||||||
await serve.ready();
|
await serve.ready();
|
||||||
console.log('Listening on http://localhost:' + serve.address().port);
|
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 registerForm = document.querySelector('#register-form');
|
||||||
const selectAvatarButton = document.querySelector('#select-avatar');
|
const selectAvatarButton = document.querySelector('#select-avatar');
|
||||||
const createChatRoomButton = document.querySelector('#create-chat-room');
|
const createChatRoomButton = document.querySelector('#create-chat-room');
|
||||||
@ -92,52 +122,28 @@ async function initialize() {
|
|||||||
if (talkButton) {
|
if (talkButton) {
|
||||||
setupTalkButton();
|
setupTalkButton();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const configExists = fs.existsSync("./config.json");
|
function handleIncomingMessage(messageObj) {
|
||||||
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) => {
|
|
||||||
console.log('Received message:', messageObj); // Debugging log
|
console.log('Received message:', messageObj); // Debugging log
|
||||||
|
|
||||||
if (messageObj.type === 'icon') {
|
if (messageObj.type === 'icon') {
|
||||||
const username = messageObj.username;
|
const username = messageObj.username;
|
||||||
if (messageObj.avatar) {
|
if (messageObj.avatar) {
|
||||||
const avatarBuffer = b4a.from(messageObj.avatar, 'base64');
|
const avatarBuffer = b4a.from(messageObj.avatar, 'base64');
|
||||||
await drive.put(`/icons/${username}.png`, avatarBuffer);
|
drive.put(`/icons/${username}.png`, avatarBuffer).then(() => {
|
||||||
updateIcon(username, avatarBuffer);
|
updateIcon(username, avatarBuffer);
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error('Received icon message with missing avatar data:', messageObj);
|
console.error('Received icon message with missing avatar data:', messageObj);
|
||||||
}
|
}
|
||||||
} else if (messageObj.type === 'file') {
|
} else if (messageObj.type === 'file') {
|
||||||
if (messageObj.file && messageObj.fileName) {
|
if (messageObj.file && messageObj.fileName) {
|
||||||
const fileBuffer = b4a.from(messageObj.file, 'base64');
|
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}`;
|
const fileUrl = `http://localhost:${servePort}/files/${messageObj.fileName}`;
|
||||||
addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic);
|
addFileMessage(messageObj.name, messageObj.fileName, updatePortInUrl(fileUrl), messageObj.fileType, updatePortInUrl(messageObj.avatar), messageObj.topic);
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error('Received file message with missing file data or fileName:', messageObj);
|
console.error('Received file message with missing file data or fileName:', messageObj);
|
||||||
}
|
}
|
||||||
@ -146,21 +152,21 @@ async function initialize() {
|
|||||||
} else if (messageObj.type === 'audio') {
|
} else if (messageObj.type === 'audio') {
|
||||||
const audioBuffer = b4a.from(messageObj.audio, 'base64');
|
const audioBuffer = b4a.from(messageObj.audio, 'base64');
|
||||||
const filePath = `/audio/${Date.now()}.webm`;
|
const filePath = `/audio/${Date.now()}.webm`;
|
||||||
await drive.put(filePath, audioBuffer);
|
drive.put(filePath, audioBuffer).then(() => {
|
||||||
const audioUrl = `http://localhost:${servePort}${filePath}`;
|
const audioUrl = `http://localhost:${servePort}${filePath}`;
|
||||||
addAudioMessage(messageObj.name, audioUrl, messageObj.avatar, messageObj.topic);
|
addAudioMessage(messageObj.name, audioUrl, messageObj.avatar, messageObj.topic);
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error('Received unknown message type:', messageObj);
|
console.error('Received unknown message type:', messageObj);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
swarm.on('connection', async (connection, info) => {
|
function handleConnection(connection, info) {
|
||||||
peerCount++;
|
|
||||||
updatePeerCount();
|
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
|
// 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) {
|
if (iconBuffer) {
|
||||||
const iconMessage = JSON.stringify({
|
const iconMessage = JSON.stringify({
|
||||||
type: 'icon',
|
type: 'icon',
|
||||||
@ -169,6 +175,7 @@ async function initialize() {
|
|||||||
});
|
});
|
||||||
connection.write(iconMessage);
|
connection.write(iconMessage);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
connection.on('data', (data) => {
|
connection.on('data', (data) => {
|
||||||
const messageObj = JSON.parse(data.toString());
|
const messageObj = JSON.parse(data.toString());
|
||||||
@ -176,27 +183,9 @@ async function initialize() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
connection.on('close', () => {
|
connection.on('close', () => {
|
||||||
peerCount--;
|
|
||||||
updatePeerCount();
|
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() {
|
function setupTalkButton() {
|
||||||
@ -334,6 +323,7 @@ async function joinSwarm(topicBuffer) {
|
|||||||
console.log('Joined room:', topic); // Debugging log
|
console.log('Joined room:', topic); // Debugging log
|
||||||
|
|
||||||
renderMessagesForRoom(topic);
|
renderMessagesForRoom(topic);
|
||||||
|
updatePeerCount();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error joining swarm for topic:', topic, error);
|
console.error('Error joining swarm for topic:', topic, error);
|
||||||
}
|
}
|
||||||
@ -429,6 +419,7 @@ function switchRoom(topic) {
|
|||||||
|
|
||||||
clearMessages();
|
clearMessages();
|
||||||
renderMessagesForRoom(topic);
|
renderMessagesForRoom(topic);
|
||||||
|
updatePeerCount();
|
||||||
|
|
||||||
// Show chat UI elements
|
// Show chat UI elements
|
||||||
document.querySelector('#chat').classList.remove('hidden');
|
document.querySelector('#chat').classList.remove('hidden');
|
||||||
@ -571,7 +562,7 @@ function addFileMessage(from, fileName, fileUrl, fileType, avatar, topic) {
|
|||||||
function updatePeerCount() {
|
function updatePeerCount() {
|
||||||
const peerCountElement = document.querySelector('#peers-count');
|
const peerCountElement = document.querySelector('#peers-count');
|
||||||
if (peerCountElement) {
|
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);
|
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
|
// Call this function when loading the rooms initially
|
||||||
renderRoomList();
|
renderRoomList();
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user