LinkUp-P2P-Chat/chatBot/includes/client.js
2024-06-10 20:57:32 +03:00

64 lines
2.2 KiB
JavaScript

import Hyperswarm from 'hyperswarm';
import EventEmitter from 'node:events'
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 => this.emit('onMessage', peer, JSON.parse(message.toString())));
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((peer, peerInfo) => {
console.log([peer]);
console.log([peerInfo.topics]);
console.log(`Peer ${[peer]} is in topic(s) ${[peerInfo.topics].filter(topic => topic).map(topic => topic.toString('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 peers = [...this.swarm.connections].filter(peer => roomPeers.includes(peer.remotePublicKey.toString('hex'))); // We remove all the peers that arent included in a room
const data = JSON.stringify({name: this.botName, message, timestamp}); // Include timestamp
for (const peer of peers) peer.write(data);
}
sendMessageToAll(message) {
console.log('Bot name:', this.botName);
const timestamp = Date.now(); // Generate timestamp
const peers = [...this.swarm.connections]
const data = JSON.stringify({name: this.botName, message, timestamp}); // Include timestamp
for (const peer of peers) peer.write(data);
}
destroy() {
this.swarm.destroy();
console.log(`Bot ${this.botName} disconnected.`);
}
}
export default Client;