37 lines
918 B
JavaScript
37 lines
918 B
JavaScript
|
const DHT = require('bittorrent-dht');
|
||
|
|
||
|
class DhtWrapper {
|
||
|
constructor(DHT_PORT = 20000) {
|
||
|
this._peerMap = new Map();
|
||
|
this._port = DHT_PORT;
|
||
|
|
||
|
this._dht = new DHT();
|
||
|
this._dht.listen(this._port);
|
||
|
this._dht.on('peer', ({ host, port }, infoHash) => {
|
||
|
const hexHash = Buffer.from(infoHash).toString('hex');
|
||
|
if (!this._peerMap.has(hexHash)) {
|
||
|
return;
|
||
|
}
|
||
|
this._peerMap.get(hexHash).add(`${host}:${port}`);
|
||
|
});
|
||
|
}
|
||
|
async lookup(infoHash) {
|
||
|
const peers = new Set();
|
||
|
this._peerMap.set(infoHash, peers);
|
||
|
return await new Promise((resolve, reject) => {
|
||
|
this._dht.lookup(infoHash, (e) => {
|
||
|
if (!!e) {
|
||
|
reject(e);
|
||
|
return;
|
||
|
}
|
||
|
if (this._peerMap.get(infoHash) === peers) {
|
||
|
this._peerMap.delete(infoHash);
|
||
|
}
|
||
|
resolve(Array.from(peers));
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = DhtWrapper;
|