node-gamedig/protocols/minecraft.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-01-10 13:03:07 +01:00
const Core = require('./core'),
Varint = require('varint');
2014-10-29 08:02:03 +01:00
class Minecraft extends Core {
2019-01-12 11:43:36 +01:00
constructor() {
super();
this.srvRecord = "_minecraft._tcp";
}
2019-01-10 13:03:07 +01:00
async run(state) {
const portBuf = Buffer.alloc(2);
2019-01-12 11:43:36 +01:00
portBuf.writeUInt16BE(this.options.port,0);
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const addressBuf = Buffer.from(this.options.host,'utf8');
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const bufs = [
this.varIntBuffer(4),
this.varIntBuffer(addressBuf.length),
addressBuf,
portBuf,
this.varIntBuffer(1)
];
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const outBuffer = Buffer.concat([
this.buildPacket(0,Buffer.concat(bufs)),
this.buildPacket(0)
]);
2015-01-18 08:38:45 +01:00
2019-01-10 13:03:07 +01:00
const data = await this.withTcp(async socket => {
return await this.tcpSend(socket, outBuffer, data => {
if(data.length < 10) return;
const reader = this.reader(data);
const length = reader.varint();
if(data.length < length) return;
return reader.rest();
});
});
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const reader = this.reader(data);
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const packetId = reader.varint();
this.debugLog("Packet ID: "+packetId);
2015-01-18 08:38:45 +01:00
2019-01-10 13:03:07 +01:00
const strLen = reader.varint();
this.debugLog("String Length: "+strLen);
2014-10-29 08:02:03 +01:00
2019-01-10 13:03:07 +01:00
const str = reader.rest().toString('utf8');
this.debugLog(str);
2015-01-18 08:38:45 +01:00
2019-01-10 13:03:07 +01:00
const json = JSON.parse(str);
delete json.favicon;
2015-01-18 08:38:45 +01:00
2019-01-10 13:03:07 +01:00
state.raw = json;
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
});
2017-08-09 12:32:09 +02:00
}
2019-01-10 13:03:07 +01:00
}
2019-02-04 08:11:28 +01:00
state.players = json.players.online;
2019-01-10 13:03:07 +01:00
}
varIntBuffer(num) {
return Buffer.from(Varint.encode(num));
}
buildPacket(id,data) {
if(!data) data = Buffer.from([]);
const idBuffer = this.varIntBuffer(id);
return Buffer.concat([
this.varIntBuffer(data.length+idBuffer.length),
idBuffer,
data
2017-08-09 12:32:09 +02:00
]);
}
}
module.exports = Minecraft;