feat: add status api

This commit is contained in:
Derrick Hammer 2023-07-23 09:53:21 -04:00
parent 9683960782
commit 16dcaafd78
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 56 additions and 0 deletions

View File

@ -43,6 +43,7 @@ onmessage = handleMessage;
const moduleDefer = defer(); const moduleDefer = defer();
let activeIpfsPeersDefer = defer(); let activeIpfsPeersDefer = defer();
let networkPeersAvailable = defer(); let networkPeersAvailable = defer();
let networkReady = true;
const networkRegistry = createNetworkRegistryClient(); const networkRegistry = createNetworkRegistryClient();
let swarm; let swarm;
@ -58,6 +59,7 @@ BigInt.prototype.toJSON = function () {
addHandler("presentKey", handlePresentKey); addHandler("presentKey", handlePresentKey);
addHandler("register", handleRegister); addHandler("register", handleRegister);
addHandler("status", handleStatus, { receiveUpdates: true });
addHandler("ready", handleReady); addHandler("ready", handleReady);
addHandler("stat", handleStat); addHandler("stat", handleStat);
addHandler("ls", handleLs, { receiveUpdates: true }); addHandler("ls", handleLs, { receiveUpdates: true });
@ -94,6 +96,7 @@ async function handlePresentKey() {
if (!ipfs.libp2p.isStarted()) { if (!ipfs.libp2p.isStarted()) {
await ipfs.start(); await ipfs.start();
networkPeersAvailable.resolve(); networkPeersAvailable.resolve();
networkReady = true;
} }
}); });
@ -295,3 +298,56 @@ async function handleRegister(aq: ActiveQuery) {
aq.respond(); aq.respond();
} }
async function handleStatus(aq: ActiveQuery) {
function sendUpdate() {
aq.sendUpdate({
peers: netPeers,
ready: netPeers > 0,
});
}
let netPeers = 0;
if (!networkReady) {
sendUpdate();
await ready();
getPeers();
}
function getPeers() {
netPeers = ipfs.libp2p.getPeers().length;
}
function peersListener() {
getPeers();
sendUpdate();
}
const peerEvents = ["connection:prune", "peer:connect", "peer:disconnect"];
peerEvents.forEach((ev) => {
// @ts-ignore
ipfs.libp2p.components.connectionManager.events.addEventListener(
ev,
peersListener,
);
});
// @ts-ignore
ipfs.libp2p.components.connectionManager.events.addEventListener(
"peer:disconnect",
peersListener,
);
aq.setReceiveUpdate?.(() => {
peerEvents.forEach((ev) => {
// @ts-ignore
ipfs.libp2p.components.connectionManager.events.removeEventListener(
ev,
peersListener,
);
});
aq.respond();
});
sendUpdate();
}