From 80bf4eb4eab5ce0369eefb91292c15c1193c2530 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 22 Apr 2021 16:50:37 +1000 Subject: [PATCH] Implement /peers and /connect commands --- web-chat/src/App.tsx | 85 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 69 insertions(+), 16 deletions(-) diff --git a/web-chat/src/App.tsx b/web-chat/src/App.tsx index f0aecdc0ff..48138bb966 100644 --- a/web-chat/src/App.tsx +++ b/web-chat/src/App.tsx @@ -24,7 +24,14 @@ export default function App() { useEffect(() => { async function initWaku() { try { - const waku = await Waku.create({ config: { pubsub: { enabled: true, emitSelf: true } } }); + const waku = await Waku.create({ + config: { + pubsub: { + enabled: true, + emitSelf: true + } + } + }); setState(({ messages }) => { return { waku, messages }; @@ -67,28 +74,74 @@ export default function App() { } }); - const commandHandler = (cmd: string) => { - let commandResponse = 'internal error'; - switch (cmd) { - case '/help': - commandResponse = '/help Display this help'; - break; - default: - commandResponse = 'Unknown Command' - } + const commandHandler = (input: string) => { + let commandResponses: string[] = []; + const args = input.split(' '); + const cmd = args.shift()!; + const waku = state.waku; + if (!waku) { + commandResponses.push('Waku is not yet initialized'); + } else { + switch (cmd) { + case '/help': + commandResponses.push('/connect : connect to the given peer'); + commandResponses.push('/help: Display this help'); + break; + case '/connect': + const peer = args.shift(); + if (!peer) { + commandResponses.push('No peer provided'); + } else { + try { + const peerMultiaddr = multiaddr(peer); + const peerId = peerMultiaddr.getPeerId(); + if (!peerId) { + commandResponses.push('Peer Id needed to dial'); + } else { + waku.libp2p.peerStore.addressBook.add( + PeerId.createFromB58String(peerId), + [peerMultiaddr]); + } + } catch (e) { + commandResponses.push('Invalid multaddr: ' + e); + } + } + break; + case '/peers': + waku.libp2p.peerStore.peers.forEach((peer, peerId) => { + commandResponses.push(peerId + ":") + let addresses = " addresses: [" + peer.addresses.forEach(({multiaddr}) => { + addresses += " " + multiaddr.toString() + ","; + }) + addresses = addresses.replace(/,$/,""); + addresses += "]"; + commandResponses.push(addresses); + let protos = " protos: ["; + protos += peer.protocols; + protos+= "]" + commandResponses.push(protos) + }) + break; + default: + commandResponses.push('Unknown Command'); + } - setState(({waku, messages}) => { - messages.push(new ChatMessage(new Date(), 'Command Response', commandResponse)); - return {waku, messages}; - }) - } + } + setState(({ waku, messages }) => { + commandResponses.forEach((res) => { + messages.push(new ChatMessage(new Date(), cmd, res)); + }); + return { waku, messages }; + }); + }; return (
- +