node-gamedig/protocols/minecraft.js

99 lines
3 KiB
JavaScript
Raw Normal View History

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