const fs = require('fs'); const express = require('express'); const bodyParser = require('body-parser'); const config = JSON.parse(fs.readFileSync('config.json', 'utf-8')); const pg = require('postgresupdater')( config.database.host, config.database.port, config.database.user, config.database.password, config.database.database ); const app = express(); const tryParseJSON = function(text) { try { return JSON.parse(text); } catch { console.log('invalid json'); } }; app.use(bodyParser.text({ type: '*/*' })); app.post('/', (req, res, next) => { const json = tryParseJSON(req.body); if (typeof req.query.json != 'undefined') { //json mod requests } else { pg.query( `INSERT INTO "Log" ("App", "Type", "Client", "Message", "Misc", "Stack") Values($1, $2, $3, $4, $5, $6)`, [json.app, json.type, json.client, json.message, json.misc, json.stack] ); } res.status(201).end(); next(); }); app.get('/', async (req, res, next) => { if (typeof req.query.json != 'undefined') { if ( config.restrictClients && !config.allowedClients.includes(req.connection.remoteAddress) ) { console.log('blocked request from ' + req.connection.remoteAddress); res.status(403).end(); return; } const data = await pg.query( `SELECT "ID", "Timestamp", "Type", "App", "Client", "Message", "Misc", "Stack" FROM "Log" ORDER BY "Timestamp" ASC` ); const rows = []; const headings = data.rows.length > 0 ? Object.keys(data.rows[0]) : []; const hiddenData = [0]; for (let row of data.rows) { rows.push(Object.values(row)); } res .status(200) .type('application/json') .end( JSON.stringify({ headings: headings, data: rows, hidden: hiddenData }) ); try { const clearLogInterval = Number.parseInt(config.clearLogAfterDays); if (clearLogInterval > 0) await pg.query(`DELETE FROM "Log" WHERE "Timestamp" < now() - interval '${clearLogInterval} days'`); } catch (e) {} } else { next(); } }); app.use(express.static('html')); app.listen(config.port); console.log('server listening on', config.port);