node-gamedig/protocols/gamespy1.js

79 lines
2.7 KiB
JavaScript
Raw Normal View History

2019-01-09 12:35:11 +01:00
const Core = require('./core');
2014-10-29 08:02:03 +01:00
class Gamespy1 extends Core {
2017-08-09 12:32:09 +02:00
constructor() {
super();
this.encoding = 'latin1';
this.byteorder = 'be';
}
2014-10-29 08:02:03 +01:00
2019-01-09 12:35:11 +01:00
async run(state) {
{
const data = await this.sendPacket('info');
state.raw = data;
if ('hostname' in state.raw) state.name = state.raw.hostname;
if ('mapname' in state.raw) state.map = state.raw.mapname;
if (this.trueTest(state.raw.password)) state.password = true;
if ('maxplayers' in state.raw) state.maxplayers = parseInt(state.raw.maxplayers);
2019-01-12 12:45:09 +01:00
if ('hostport' in state.raw) state.gamePort = parseInt(state.raw.hostport);
2019-01-09 12:35:11 +01:00
}
{
const data = await this.sendPacket('rules');
state.raw.rules = data;
}
{
const data = await this.sendPacket('players');
const players = {};
const teams = {};
for (const ident of Object.keys(data)) {
const split = ident.split('_');
let key = split[0];
const id = split[1];
let value = data[ident];
2014-10-29 08:02:03 +01:00
2019-01-09 12:35:11 +01:00
if (key === 'teamname') {
teams[id] = value;
} else {
if (!(id in players)) players[id] = {};
if (key === 'playername') key = 'name';
else if (key === 'team') value = parseInt(value);
else if (key === 'score' || key === 'ping' || key === 'deaths') value = parseInt(value);
players[id][key] = value;
}
2017-08-09 12:32:09 +02:00
}
2019-01-09 12:35:11 +01:00
state.raw.teams = teams;
for (const id of Object.keys(players)) {
state.players.push(players[id]);
}
}
2017-08-09 12:32:09 +02:00
}
2019-01-09 12:35:11 +01:00
async sendPacket(type) {
2017-08-09 12:32:09 +02:00
const queryId = '';
const output = {};
2019-01-09 12:35:11 +01:00
return await this.udpSend('\\'+type+'\\', buffer => {
const reader = this.reader(buffer);
const str = reader.string({length:buffer.length});
const split = str.split('\\');
2017-08-09 12:32:09 +02:00
split.shift();
const data = {};
2017-08-09 12:32:09 +02:00
while(split.length) {
const key = split.shift();
const value = split.shift() || '';
2017-08-09 12:32:09 +02:00
data[key] = value;
}
if(!('queryid' in data)) return;
if(queryId && data.queryid !== queryId) return;
for(const i of Object.keys(data)) output[i] = data[i];
if('final' in output) {
delete output.final;
delete output.queryid;
2019-01-09 12:35:11 +01:00
return output;
2017-08-09 12:32:09 +02:00
}
});
}
}
module.exports = Gamespy1;