From 53e26e39ffde2ad71e24949882c6eb75fbc74689 Mon Sep 17 00:00:00 2001 From: gumi Date: Mon, 2 Apr 2018 14:21:46 -0400 Subject: add a TMWA endpoint to get misc server info --- .gitignore | 1 + package.json | 6 ++++++ server.js | 36 +++++++++++++++++++++++++++++++++++- 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3c12ed1..7297aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /config.json /node_modules /package-lock.json +/online.txt diff --git a/package.json b/package.json index a59d006..b8d511f 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "license": "CC0-1.0", "config": { "port": 8080, + "timezone": "UTC", "sql": { "host": "localhost", @@ -17,6 +18,11 @@ "recaptcha": { "secret": "recaptcha secret key" + }, + + "tmwa" : { + "name": "The Mana World Legacy Server", + "url": "tmwa://server.themanaworld.org:6901" } }, "repository": { diff --git a/server.js b/server.js index 9798951..884ac6d 100644 --- a/server.js +++ b/server.js @@ -2,8 +2,31 @@ const express = require("express"); const mysql = require("mysql"); const bodyParser = require("body-parser"); const https = require("https"); +const fs = require("fs"); const api = express(); +const tmwa = { + status: "OfflineTemporarily", + num_online: 0, + interval: null, + poll: () => { + fs.readFile("./online.txt", "utf8", (err, data) => { + const lines = data.split("\n"); + const last_online = Date.parse(lines[0].match(/\((.+)\)/)[1] + ` ${process.env.npm_package_config_timezone}`); + + if (Date.now() - last_online < 30000) { + tmwa.status = "Online"; + tmwa.num_online = lines[lines.length - 2].match(/([0-9]+) users are online./)[1]; + } else { + tmwa.status = "OfflineTemporarily"; + tmwa.num_online = 0; + } + + setTimeout(tmwa.poll, 2000); + }); + } +}; + const checkCaptcha = (req, res, next) => { const token = String(req.get("X-CAPTCHA-TOKEN")); @@ -43,7 +66,17 @@ const checkCaptcha = (req, res, next) => { }) }; - +api.get("/api/tmwa", (req, res) => { + res.append("Access-Control-Allow-Origin", "*"); // CORS ready + res.status(200).json({ + "@context": "http://schema.org", + "@type": "GameServer", + name: process.env.npm_package_config_tmwa_name, + url: process.env.npm_package_config_tmwa_url, + playersOnline: tmwa.num_online, + serverStatus: tmwa.status, + }); +}); api.use(checkCaptcha); api.use(bodyParser.json()); @@ -130,3 +163,4 @@ if (process.env.npm_package_config_port === undefined) { api.set("trust proxy", "loopback"); // only allow localhost to communicate with the API api.listen(process.env.npm_package_config_port, () => console.info(`Listening on port ${process.env.npm_package_config_port}`)); +tmwa.poll(); -- cgit v1.2.3-60-g2f50