import Hyperswarm from 'hyperswarm'; import EventEmitter from 'node:events' import b4a from "b4a"; class Client extends EventEmitter { constructor(botName) { super(); if (!botName) return console.error("BotName is not defined!"); this.botName = botName; this.swarm = new Hyperswarm(); this.setupSwarm(); } setupSwarm() { this.swarm.on('connection', (peer) => { peer.on('data', message => { const messageObj = JSON.parse(message.toString()); if (messageObj.type === "message") this.emit('onMessage', peer, messageObj); if (messageObj.type === "icon") this.emit('onIcon', peer, messageObj); if (messageObj.type === "file") this.emit('onFile', peer, messageObj); }); peer.on('error', e => { this.emit('onError', e); console.error(`Connection error: ${e}`) }); }); this.swarm.on('update', () => { console.log(`Connections count: ${this.swarm.connections.size} / Peers count: ${this.swarm.peers.size}`); this.swarm.peers.forEach((peerInfo, peerId) => { // Please do not try to understand what is going on here. I have no idea anyway. But it surprisingly works const peer = [peerId]; const peerTopics = [peerInfo.topics] .filter(topics => topics) .map(topics => topics.map(topic => b4a.toString(topic, 'hex'))); }); }); } joinChatRoom(chatRoomID) { this.discovery = this.swarm.join(Buffer.from(chatRoomID, 'hex'), { client: true, server: true }); this.discovery.flushed().then(() => { console.log(`Bot ${this.botName} joined the chat room.`); this.emit('onBotJoinRoom'); }); } sendMessage(roomPeers, message) { console.log('Bot name:', this.botName); const timestamp = Date.now(); // Generate timestamp const messageObj = { type: 'message', // Add type field name: this.botName, message, timestamp }; const data = JSON.stringify(messageObj); const peers = [...this.swarm.connections].filter(peer => roomPeers.includes(peer.remotePublicKey.toString('hex'))); // We remove all the peers that aren't included in a room for (const peer of peers) peer.write(data); } sendMessageToAll(message) { console.log('Bot name:', this.botName); const timestamp = Date.now(); // Generate timestamp const messageObj = { type: 'message', // Add type field name: this.botName, message, timestamp }; const data = JSON.stringify(messageObj); const peers = [...this.swarm.connections]; for (const peer of peers) peer.write(data); } destroy() { this.swarm.destroy(); console.log(`Bot ${this.botName} disconnected.`); } } export default Client;