51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
|
import DHTOnlineBase from "./dhtOnlineBase.js";
|
||
|
import DHTFlood from "@lumeweb/dht-flood";
|
||
|
|
||
|
const DISCONNECT_SMOOTH = 500;
|
||
|
|
||
|
export default class DHTOnline extends DHTOnlineBase {
|
||
|
private flood: DHTFlood;
|
||
|
private swarm: any;
|
||
|
|
||
|
constructor(
|
||
|
swarm: any,
|
||
|
{ id = swarm.keyPair.publicKey, data = {}, ...opts } = {}
|
||
|
) {
|
||
|
super(id, opts);
|
||
|
this.flood = new DHTFlood({ id, swarm, ...opts });
|
||
|
this.swarm = swarm;
|
||
|
|
||
|
this.flood.on("peer-open", (peer) => this.handlePeerAdd(peer));
|
||
|
this.flood.on("peer-remove", (peer) => this.handlePeerRemove(peer));
|
||
|
this.flood.on("message", (message, id) => this.onGetBroadcast(message, id));
|
||
|
|
||
|
this.swarm.on("connection", (peer: any) =>
|
||
|
this.flood.send(peer, Buffer.from("hello"), 0)
|
||
|
);
|
||
|
|
||
|
this.setData(data);
|
||
|
|
||
|
[...this.swarm.peers.values()].forEach(this.handlePeerAdd.bind(this));
|
||
|
}
|
||
|
|
||
|
handlePeerAdd(peer: any) {
|
||
|
const id = peer.remotePublicKey;
|
||
|
this.onAddPeer(id);
|
||
|
}
|
||
|
|
||
|
handlePeerRemove(peer: any) {
|
||
|
const id = peer.remotePublicKey;
|
||
|
// Wait for a bit and check if we're still disconnected before removing the peer
|
||
|
setTimeout(() => {
|
||
|
if (this.swarm._allConnections.has(id)) {
|
||
|
return;
|
||
|
}
|
||
|
this.onRemovePeer(id);
|
||
|
}, DISCONNECT_SMOOTH);
|
||
|
}
|
||
|
|
||
|
broadcast(message: any, ttl?: number) {
|
||
|
this.flood.broadcast(message, ttl);
|
||
|
}
|
||
|
}
|