const { EventEmitter: e } = require("events"),
s = require("safety-catch"),
t = require("hypercore"),
i = require("hypercore-id-encoding"),
{ HandshakeMessage: r, SignalMessage: h } = require("../lib/messages"),
n = "127.0.0.1",
o = "keet-webrtc/v1"
module.exports = class extends e {
constructor(e, s, r, h = {}) {
super()
const { onerror: n = console.error, onsignal: a } = h
;((this.callId = e),
(this.rawMuxer = s),
(this.closed = !1),
(this.proxyPort = 0),
(this.channelOpened = !1),
(this.stream = this.rawMuxer.connection),
(this.localAlias = this.rawMuxer.createLocalAlias()),
(this.remoteAlias = -1),
(this._proxy = r),
(this._onerror = n),
(this._onsignal = a),
(this._rinfo = null),
(this._sendBuffer = []),
(this._recvBuffer = []),
(this._muxer = t.getProtocolMuxer(this.stream)),
this._muxer ||
((this.stream = t.createProtocolStream(this.stream)),
(this._muxer = t.getProtocolMuxer(this.stream))),
(this._channel = null),
(this._senders = null),
(this._muxerInfo = { protocol: o, id: i.decode(this.callId) }),
this._muxer.pair(this._muxerInfo, () => this._createChannel()),
this._createChannel(),
this._openProxy())
}
_openProxy() {
;(this._proxy.bind(0, n),
this._proxy.on("message", this._handleLocalData.bind(this)),
(this.proxyPort = this._proxy.address().port))
}
close() {
this.closed ||
((this.closed = !0),
this._channel.close(),
this._proxy.close().catch(s),
this._muxer.unpair(this._muxerInfo))
}
_createChannel() {
const e = [{ encoding: h, onmessage: (e) => this._onsignal(e) }],
s = this._muxer.createChannel({
protocol: o,
handshake: r,
onclose: this._onChannelClose.bind(this),
onopen: this._onChannelOpen.bind(this),
onerror: (e) => console.error("ERR HERE:", e),
id: i.decode(this.callId),
messages: e,
})
null !== s &&
((this._channel = s),
(this._senders = { signal: s.messages[0] }),
this._channel.open({ alias: this.localAlias }))
}
_onChannelOpen({ alias: e }) {
for (
this.channelOpened = !0,
this.remoteAlias = e,
this.rawMuxer.registerProxy(this.remoteAlias, this),
this.emit("channel-open");
this._sendBuffer.length;
)
this.rawMuxer.send(this.localAlias, this._sendBuffer.pop())
}
_onChannelClose() {
;((this.channelOpened = !1),
-1 !== this.remoteAlias &&
(this.rawMuxer.unregisterProxy(this.remoteAlias, this),
(this.remoteAlias = -1),
(this._rinfo = null),
this.emit("channel-close")))
}
_handleLocalData(e, s) {
if (!this.closed && -1 !== this.remoteAlias && s.host === n) {
if (!this._rinfo)
for (this._rinfo = s; this._recvBuffer.length; )
this._proxy.trySend(this._recvBuffer.pop(), s.port, n)
;-1 === this.remoteAlias
? this._sendBuffer.unshift(e)
: this.rawMuxer.send(this.localAlias, e)
}
}
handleRawStreamData(e) {
this.closed ||
(this._rinfo ? this._proxy.trySend(e, this._rinfo.port, n) : this._recvBuffer.unshift(e))
}
sendSignal(e) {
this.closed || this._senders.signal.send(e)
}
}