2022-11-16 07:47:03 +00:00
|
|
|
"use strict";
|
|
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
|
|
};
|
|
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
|
const dhtOnlineBase_js_1 = __importDefault(require("./dhtOnlineBase.js"));
|
|
|
|
const dht_flood_1 = __importDefault(require("@lumeweb/dht-flood"));
|
|
|
|
const DISCONNECT_SMOOTH = 500;
|
|
|
|
class DHTOnline extends dhtOnlineBase_js_1.default {
|
|
|
|
flood;
|
|
|
|
swarm;
|
2022-11-16 17:12:52 +00:00
|
|
|
constructor(swarm, { id = swarm.keyPair.publicKey, data = {}, protocol = undefined, ...opts } = {}) {
|
2022-11-16 07:47:03 +00:00
|
|
|
super(id, opts);
|
2022-11-16 17:05:21 +00:00
|
|
|
this.flood = new dht_flood_1.default({ id, swarm, protocol, ...opts });
|
2022-11-16 07:47:03 +00:00
|
|
|
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) => this.flood.send(peer, Buffer.from("hello"), 0));
|
2022-11-16 16:15:00 +00:00
|
|
|
this.data = data;
|
2022-11-16 07:47:03 +00:00
|
|
|
[...this.swarm.peers.values()].forEach(this.handlePeerAdd.bind(this));
|
|
|
|
}
|
|
|
|
handlePeerAdd(peer) {
|
|
|
|
const id = peer.remotePublicKey;
|
|
|
|
this.onAddPeer(id);
|
|
|
|
}
|
|
|
|
handlePeerRemove(peer) {
|
|
|
|
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, ttl) {
|
|
|
|
this.flood.broadcast(message, ttl);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
exports.default = DHTOnline;
|