node-gamedig/protocols/minecraftping.js

100 lines
2.3 KiB
JavaScript
Raw Normal View History

const varint = require('varint'),
2014-10-29 08:02:03 +01:00
async = require('async');
function varIntBuffer(num) {
return Buffer.alloc(varint.encode(num));
2014-10-29 08:02:03 +01:00
}
function buildPacket(id,data) {
if(!data) data = Buffer.from([]);
const idBuffer = varIntBuffer(id);
2014-10-29 08:02:03 +01:00
return Buffer.concat([
varIntBuffer(data.length+idBuffer.length),
idBuffer,
data
]);
}
class MinecraftPing extends require('./core') {
run(state) {
let receivedData;
2014-10-29 08:02:03 +01:00
async.series([
(c) => {
2014-10-29 08:02:03 +01:00
// build and send handshake and status TCP packet
const portBuf = Buffer.alloc(2);
portBuf.writeUInt16BE(this.options.port_query,0);
2014-10-29 08:02:03 +01:00
const addressBuf = Buffer.from(this.options.address,'utf8');
2014-10-29 08:02:03 +01:00
const bufs = [
2014-10-29 08:02:03 +01:00
varIntBuffer(4),
varIntBuffer(addressBuf.length),
addressBuf,
portBuf,
varIntBuffer(1)
];
2015-01-18 08:38:45 +01:00
const outBuffer = Buffer.concat([
2014-10-29 08:02:03 +01:00
buildPacket(0,Buffer.concat(bufs)),
buildPacket(0)
]);
this.tcpSend(outBuffer, (data) => {
2014-10-29 08:02:03 +01:00
if(data.length < 10) return false;
const expected = varint.decode(data);
2015-01-18 08:38:45 +01:00
data = data.slice(varint.decode.bytes);
2014-10-29 08:02:03 +01:00
if(data.length < expected) return false;
receivedData = data;
c();
return true;
});
},
(c) => {
2014-10-29 08:02:03 +01:00
// parse response
let data = receivedData;
const packetId = varint.decode(data);
if(this.debug) console.log("Packet ID: "+packetId);
2015-01-18 08:38:45 +01:00
data = data.slice(varint.decode.bytes);
const strLen = varint.decode(data);
if(this.debug) console.log("String Length: "+strLen);
2015-01-18 08:38:45 +01:00
data = data.slice(varint.decode.bytes);
2014-10-29 08:02:03 +01:00
const str = data.toString('utf8');
if(this.debug) {
2015-01-18 08:38:45 +01:00
console.log(str);
}
let json;
2014-10-29 08:02:03 +01:00
try {
json = JSON.parse(str);
delete json.favicon;
} catch(e) {
return this.fatal('Invalid JSON');
2014-10-29 08:02:03 +01:00
}
2015-01-18 08:38:45 +01:00
2014-10-29 08:02:03 +01:00
state.raw.version = json.version.name;
state.maxplayers = json.players.max;
state.raw.description = json.description.text;
if(json.players.sample) {
for(const player of json.players.sample) {
2014-10-29 08:02:03 +01:00
state.players.push({
id: player.id,
name: player.name
2014-10-29 08:02:03 +01:00
});
}
}
while(state.players.length < json.players.online) {
state.players.push({});
}
2015-01-18 08:38:45 +01:00
this.finish(state);
2014-10-29 08:02:03 +01:00
}
]);
}
}
module.exports = MinecraftPing;