From a469f1fdb4d7a01b9f3a7e17355e4cf0ffe5f443 Mon Sep 17 00:00:00 2001 From: utf-4096 Date: Sat, 25 Mar 2023 13:02:49 +0100 Subject: [PATCH] Publish/Discover --- src/Client.js | 56 +++++++++++++++++++++++++++++++++++++++++++++++-- src/Protocol.js | 2 +- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/Client.js b/src/Client.js index 574d20f..9b166e7 100644 --- a/src/Client.js +++ b/src/Client.js @@ -2,9 +2,13 @@ import { Container, AuthenticationRequest, AuthenticationResponse, - Message + Message, + PublishRequest, + PublishResponse, + DiscoverRequest, + DiscoverResponse } from './Protocol.js' -import { EventEmitter } from 'events' +import { EventEmitter } from 'events' const WebSocket = (typeof window === 'undefined' ? import('ws'): window.WebSocket) @@ -94,6 +98,49 @@ export class Client extends EventEmitter { return this.#address } + async #publish(port, flags) { + const response = await this.#protoRequest(PublishRequest.create({ + port, + flags, + publish: true + })) + + const publish = PublishResponse.toObject(response.PublishResponse) + + if(publish.status !== 0) { + throw new Error(`Unexpected response: ${publish.status}`) + } + } + + async #unpublish(port) { + const response = await this.#protoRequest(PublishRequest.create({ + port, + flags: [], + publish: false + })) + + const unpublish = PublishResponse.toObject(response.PublishRespons) + + if(unpublish.status !== 0) { + throw new Error(`Unexpected response: ${unpublish.status}`) + } + } + + async discover(flags, limit = 0) { + const response = await this.#protoRequest(DiscoverRequest.create({ + flags, + limit + })) + + const discover = DiscoverResponse.toObject(response.DiscoverResponse, { longs: String }) + + if(discover.status !== 0) { + throw new Error(`Unexpected response: ${discover.status}`) + } + + return discover.peers.map(sv => { return { ...sv, address: BigInt(sv.address) } }) + } + listen(port, callback) { this.on('raw', container => { if(container.message === 'Message') { @@ -101,5 +148,10 @@ export class Client extends EventEmitter { callback(BigInt(message.address), message.data) } }) + + return { + publish: flags => this.#publish(port, flags), + unpublish: flags => this.#unpublish(port) + } } } diff --git a/src/Protocol.js b/src/Protocol.js index 6f8ab5c..3bd9084 100644 --- a/src/Protocol.js +++ b/src/Protocol.js @@ -19,7 +19,7 @@ export const [ PublishResponse, DiscoverRequest, DiscoverResponse -] = import_proto(protocol20, [ +] = import_proto(encoders, [ 'Container', 'AuthenticationRequest', 'AuthenticationResponse',