From 02c2766322c5ec341409baa52584d2c9a45503c6 Mon Sep 17 00:00:00 2001 From: Jack Hadrill Date: Sun, 10 Jan 2021 14:01:27 +0000 Subject: [PATCH] Add BitTorrent wire protocol extension for chat and time sync --- src/helpers/vcinema-wire-extension.js | 79 +++++++++++++++++++++++++++ src/helpers/wire-statistics.js | 1 - 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 src/helpers/vcinema-wire-extension.js diff --git a/src/helpers/vcinema-wire-extension.js b/src/helpers/vcinema-wire-extension.js new file mode 100644 index 0000000..7a58349 --- /dev/null +++ b/src/helpers/vcinema-wire-extension.js @@ -0,0 +1,79 @@ + +const { EventEmitter } = require('events') +const bencode = require('bencode') + +const EXTENSION_NAME = 'vcinema' + +class VCinemaWireExtension extends EventEmitter { + static _alias = 'Unknown' + + constructor (wire) { + super() + this._ready = false + this._wire = wire + this._remoteAlias = 'Unknown' + this.emit('info', `Extended handshake using ${this._alias}.`) + wire.extendedHandshake[`${EXTENSION_NAME}_alias`] = Buffer.from(VCinemaWireExtension._alias) + } + + get name () { + return EXTENSION_NAME + } + + get ready () { + return this._ready + } + + get wire () { + return this._wire + } + + get remoteAlias () { + return this._remoteAlias + } + + static get alias () { + return VCinemaWireExtension._alias + } + + static set alias (alias) { + VCinemaWireExtension._alias = alias + } + + onExtendedHandshake (handshake) { + if (!handshake.m || !handshake.m[EXTENSION_NAME]) { + this.emit('info', `Peer does not support ${EXTENSION_NAME}.`) + return + } + + this._ready = true + this._remoteAlias = handshake[`${EXTENSION_NAME}_alias`] || 'Unknown' + this.emit('info', `Peer alias set as ${this._remoteAlias}.`) + this.emit('alias', this._remoteAlias) + } + + onMessage (buffer) { + const decodedBuffer = this._decode(buffer) + this.emit('info', `Message received from ${this._remoteAlias}.`) + this.emit('message', decodedBuffer) + } + + send (message) { + this.emit('info', `Sending message to ${this._remoteAlias}.`) + this._send(message) + } + + _encode (message) { + return bencode.encode(JSON.stringify(message)) + } + + _decode (buffer) { + return JSON.parse(bencode.decode(buffer.toString())) + } + + _send (message) { + this.wire.extended(EXTENSION_NAME, this._encode(message)) + } +} + +module.exports = VCinemaWireExtension diff --git a/src/helpers/wire-statistics.js b/src/helpers/wire-statistics.js index eebb7ec..304069c 100644 --- a/src/helpers/wire-statistics.js +++ b/src/helpers/wire-statistics.js @@ -18,7 +18,6 @@ const updateWireStatistics = (wires, wireStatistics) => { wireStatistic.uploadSpeed = prettyBytes(wire.uploadSpeed()) + 'ps' wireStatistic.downloadSpeed = prettyBytes(wire.downloadSpeed()) + 'ps' }) - window.w = wireStatistics } export default updateWireStatistics