1
0
mirror of synced 2024-11-15 04:07:38 +01:00
shadowtenpo/cchub.js
2022-02-27 14:56:44 -08:00

78 lines
1.8 KiB
JavaScript

const ws = require('ws');
const enc = require('./ccencap');
// Note: src and dst addresses in this file are numerical suffixes only.
function CCHub(url) {
var conn = new ws.WebSocket(url);
this.ready = new Promise((resolve) => {
conn.on('open', () => {
this.conn = conn;
resolve();
});
});
this.conn = this.ready;
this.onNetForward = function(src, dst, sport, dport, type, msg) {};
this.onPartyJoin = function(subnet, suffix) {};
this.onPartyUpdate = function(members) {};
conn.on('message', (data) => {
msg = enc.decode(data);
switch (msg.op) {
case 'party_update':
this._updateParty(msg);
break;
case 'net_tcp':
case 'net_udp':
case 'net_tcpfin':
case 'net_tcpclose':
var type = msg.op.slice(4);
var payload = data.subarray(7);
this.onNetForward(msg.src, msg.dst, msg.sport, msg.dport, type, payload);
break;
case 'sys_msg':
console.log('Hub message: ' + msg.msg);
break;
default:
console.warn('Unhandled packed: ', msg)
}
});
this.subnet = null;
this.mysuffix = 0;
this.members = [];
}
CCHub.prototype.send = function(msg) {
if (this.conn instanceof Promise) {
this.conn.then(() => {
this.send(msg);
});
return;
}
this.conn.send(msg);
};
CCHub.prototype.hello = function(req) {
this.send(enc.encodePartyHello(req));
};
CCHub.prototype._updateParty = function(msg) {
if (!this.subnet) {
this.subnet = msg.subnet;
this.mysuffix = msg.suffix;
this.onPartyJoin(this.subnet, this.mysuffix);
}
var diff = msg.members.filter(suffix => this.members.indexOf(suffix) == -1);
this.members = this.members.concat(diff);
this.onPartyUpdate(diff);
};
CCHub.prototype.sendNetForward = function(src, dst, sport, dport, type, data) {
var msg = enc.encodePacket(src, dst, sport, dport, type, data);
this.send(msg);
};
module.exports = CCHub;