node-gamedig/protocols/gamespy1.js

89 lines
2.3 KiB
JavaScript
Raw Normal View History

const async = require('async');
2014-10-29 08:02:03 +01:00
class Gamespy1 extends require('./core') {
constructor() {
super();
2014-10-29 08:02:03 +01:00
this.sessionId = 1;
this.encoding = 'latin1';
this.byteorder = 'be';
}
2014-10-29 08:02:03 +01:00
run(state) {
2014-10-29 08:02:03 +01:00
async.series([
(c) => {
this.sendPacket('info', (data) => {
2014-10-29 08:02:03 +01:00
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;
2014-10-29 08:02:03 +01:00
if('maxplayers' in state.raw) state.maxplayers = parseInt(state.raw.maxplayers);
c();
});
},
(c) => {
this.sendPacket('rules', (data) => {
2014-10-29 08:02:03 +01:00
state.raw.rules = data;
c();
});
},
(c) => {
this.sendPacket('players', (data) => {
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
if(key === 'teamname') {
2014-10-29 08:02:03 +01:00
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);
2014-10-29 08:02:03 +01:00
players[id][key] = value;
}
}
state.raw.teams = teams;
for(const id of Object.keys(players)) {
state.players.push(players[id]);
}
this.finish(state);
2014-10-29 08:02:03 +01:00
});
}
]);
}
sendPacket(type,callback) {
const queryId = '';
const output = {};
this.udpSend('\\'+type+'\\', (buffer) => {
const reader = this.reader(buffer);
const str = reader.string({length:buffer.length});
const split = str.split('\\');
2014-10-29 08:02:03 +01:00
split.shift();
const data = {};
2014-10-29 08:02:03 +01:00
while(split.length) {
const key = split.shift();
const value = split.shift() || '';
2014-10-29 08:02:03 +01: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];
2014-10-29 08:02:03 +01:00
if('final' in output) {
delete output.final;
delete output.queryid;
callback(output);
return true;
}
});
}
}
module.exports = Gamespy1;