node-gamedig/protocols/samp.js

90 lines
2.9 KiB
JavaScript
Raw Normal View History

2019-01-07 07:52:29 +01:00
const Core = require('./core');
class Samp extends Core {
constructor() {
super();
this.encoding = 'win1252';
}
2014-10-29 08:02:03 +01:00
2019-01-07 07:52:29 +01:00
async run(state) {
// read info
{
const reader = await this.sendPacket('i');
state.password = !!reader.uint(1);
state.raw.numplayers = reader.uint(2);
state.maxplayers = reader.uint(2);
state.name = this.readString(reader,4);
state.raw.gamemode = this.readString(reader,4);
this.map = this.readString(reader,4);
}
// read rules
{
const reader = await this.sendPacket('r');
const ruleCount = reader.uint(2);
state.raw.rules = {};
for(let i = 0; i < ruleCount; i++) {
const key = this.readString(reader,1);
const value = this.readString(reader,1);
state.raw.rules[key] = value;
2017-08-09 12:32:09 +02:00
}
2019-01-07 07:52:29 +01:00
if('mapname' in state.raw.rules)
state.map = state.raw.rules.mapname;
}
// read players
{
const reader = await this.sendPacket('d', true);
if (reader !== null) {
const playerCount = reader.uint(2);
for(let i = 0; i < playerCount; i++) {
const player = {};
player.id = reader.uint(1);
player.name = this.readString(reader,1);
player.score = reader.int(4);
player.ping = reader.uint(4);
state.players.push(player);
}
} else {
for(let i = 0; i < state.raw.numplayers; i++) {
state.players.push({});
}
}
}
2017-08-09 12:32:09 +02:00
}
readString(reader,lenBytes) {
const length = reader.uint(lenBytes);
2017-08-09 12:32:09 +02:00
if(!length) return '';
2019-01-07 07:52:29 +01:00
return reader.string({length:length});
2017-08-09 12:32:09 +02:00
}
2019-01-07 07:52:29 +01:00
async sendPacket(type,allowTimeout) {
const outBuffer = Buffer.alloc(11);
outBuffer.writeUInt32BE(0x53414D50,0);
const ipSplit = this.options.address.split('.');
2019-01-07 07:52:29 +01:00
outBuffer.writeUInt8(parseInt(ipSplit[0]),4);
outBuffer.writeUInt8(parseInt(ipSplit[1]),5);
outBuffer.writeUInt8(parseInt(ipSplit[2]),6);
outBuffer.writeUInt8(parseInt(ipSplit[3]),7);
outBuffer.writeUInt16LE(this.options.port,8);
outBuffer.writeUInt8(type.charCodeAt(0),10);
2014-10-29 08:02:03 +01:00
2019-01-07 07:52:29 +01:00
return await this.udpSend(
outBuffer,
(buffer) => {
const reader = this.reader(buffer);
for(let i = 0; i < outBuffer.length; i++) {
if(outBuffer.readUInt8(i) !== reader.uint(1)) return;
}
return reader;
},
() => {
if(allowTimeout) {
return null;
}
2017-08-09 12:32:09 +02:00
}
2019-01-07 07:52:29 +01:00
);
2017-08-09 12:32:09 +02:00
}
}
module.exports = Samp;