LinkUp-P2P-Chat/chatBot/includes/client.js

64 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-06-03 19:23:14 -04:00
import Hyperswarm from 'hyperswarm';
import EventEmitter from 'node:events'
2024-06-03 19:23:14 -04:00
class Client extends EventEmitter {
constructor(botName) {
super();
if(!botName) return console.error("BotName is not defined!");
2024-06-03 19:23:14 -04:00
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())));
2024-06-08 16:29:51 -04:00
peer.on('error', e => {
this.emit('onError', e);
2024-06-08 16:29:51 -04:00
console.error(`Connection error: ${e}`)
});
2024-06-03 19:23:14 -04:00
});
this.swarm.on('update', () => {
console.log(`Peers count: ${this.swarm.connections.size}`);
if(this.swarm.connections.size > 0) {
let arr = [];
[...this.swarm.peers].forEach(peer => arr.push([peer.topics]));
console.log(arr);
process.exit(-1);
}
2024-06-03 19:23:14 -04:00
});
}
joinChatRoom(chatRoomID) {
this.discovery = this.swarm.join(Buffer.from(chatRoomID, 'hex'), {client: true, server: true});
2024-06-03 19:23:14 -04:00
this.discovery.flushed().then(() => {
console.log(`Bot ${this.botName} joined the chat room.`);
this.emit('onBotJoinRoom');
2024-06-03 19:23:14 -04:00
});
}
sendMessage(roomPeers, message) {
2024-06-03 19:23:14 -04:00
console.log('Bot name:', this.botName);
const timestamp = Date.now(); // Generate timestamp
2024-06-10 10:28:18 -04:00
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
2024-06-03 19:23:14 -04:00
for (const peer of peers) peer.write(data);
}
destroy() {
this.swarm.destroy();
console.log(`Bot ${this.botName} disconnected.`);
}
}
export default Client;