node-gamedig/lib/typeresolver.js

95 lines
2.4 KiB
JavaScript
Raw Normal View History

const Path = require('path'),
2014-10-29 08:02:03 +01:00
fs = require('fs');
const protocolDir = Path.normalize(__dirname+'/../protocols');
const gamesFile = Path.normalize(__dirname+'/../games.txt');
2014-10-29 08:02:03 +01:00
function parseList(str) {
if(!str) return {};
const out = {};
for (const one of str.split(',')) {
const equals = one.indexOf('=');
const key = equals === -1 ? one : one.substr(0,equals);
let value = equals === -1 ? '' : one.substr(equals+1);
2014-10-29 08:02:03 +01:00
if(value === 'true' || value === '') value = true;
else if(value === 'false') value = false;
else if(!isNaN(value)) value = parseInt(value);
out[key] = value;
}
2014-10-29 08:02:03 +01:00
return out;
}
function readGames() {
const lines = fs.readFileSync(gamesFile,'utf8').split('\n');
const games = {};
2014-10-29 08:02:03 +01:00
for (let line of lines) {
2014-10-29 08:02:03 +01:00
// strip comments
const comment = line.indexOf('#');
if(comment !== -1) line = line.substr(0,comment);
2014-10-29 08:02:03 +01:00
line = line.trim();
if(!line) continue;
2014-10-29 08:02:03 +01:00
const split = line.split('|');
2014-10-29 08:02:03 +01:00
games[split[0].trim()] = {
pretty: split[1].trim(),
protocol: split[2].trim(),
options: parseList(split[3]),
params: parseList(split[4])
};
}
2014-10-29 08:02:03 +01:00
return games;
}
const games = readGames();
2014-10-29 08:02:03 +01:00
function createProtocolInstance(type) {
type = Path.basename(type);
const path = protocolDir+'/'+type;
2014-10-29 08:02:03 +01:00
if(!fs.existsSync(path+'.js')) throw Error('Protocol definition file missing: '+type);
const protocol = require(path);
2014-10-29 08:02:03 +01:00
return new protocol();
}
class TypeResolver {
static lookup(type) {
2014-10-29 08:02:03 +01:00
if(!type) throw Error('No game specified');
if(type.substr(0,9) === 'protocol-') {
2014-10-29 08:02:03 +01:00
return createProtocolInstance(type.substr(9));
}
const game = games[type];
2014-10-29 08:02:03 +01:00
if(!game) throw Error('Invalid game: '+type);
const query = createProtocolInstance(game.protocol);
2014-10-29 08:02:03 +01:00
query.pretty = game.pretty;
for(const key of Object.keys(game.options)) {
query.options[key] = game.options[key];
}
for(const key of Object.keys(game.params)) {
query[key] = game.params[key];
}
2014-10-29 08:02:03 +01:00
return query;
}
static printReadme() {
let out = '';
for(const key of Object.keys(games)) {
const game = games[key];
2014-10-29 08:02:03 +01:00
out += "* "+game.pretty+" ("+key+")";
if(game.options.port_query_offset || game.options.port_query)
out += " [[Separate Query Port](#separate-query-port)]";
if(game.params.doc_notes)
out += " [[Additional Notes](#"+game.params.doc_notes+")]";
2014-10-29 08:02:03 +01:00
out += "\n";
}
return out;
}
}
module.exports = TypeResolver;