const http = require('http'); const fs = require("fs"); const YAML = require('yaml'); const crypto = require('crypto'); global.variables = { get version() { const fs = require('fs'); if (fs.existsSync(".git/refs/heads/trunk")) { return fs.readFileSync(".git/refs/heads/trunk").toString().substring(0, 8); } else { return "dev"; } }, bodyOptions: { limit: 10485760 } } console.log("Reading config..."); global.databases = YAML.parse(fs.readFileSync('data/databases.yml').toString()); console.log("Restoring databases..."); global.heads = {}; for (let entry of Object.keys(databases)) { let database = databases[entry]; let dbid = crypto.createHash('md5').update(entry).digest('hex'); if (fs.existsSync("data/" + dbid)) { console.log("[" + entry + "] Opening database..."); heads[entry] = JSON.parse(Buffer.from(fs.readFileSync("data/" + dbid + "/HEAD").toString(), "hex").toString("utf-8")); } else { console.log("[" + entry + "] Creating database..."); fs.mkdirSync("data/" + dbid); fs.writeFileSync("data/" + dbid + "/HEAD", Buffer.from(JSON.stringify({})).toString("hex")); let chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e" ,"f"]; for (let c1 of chars) { for (let c2 of chars) { fs.mkdirSync("data/" + dbid + "/" + c1 + c2); } } } } console.log("Starting server..."); let server = http.createServer(function (req, res) { try { if (req.headers["x-equestriadb-token"]) { req.headers["x-pawerdb-token"] = req.headers["x-equestriadb-token"]; } if (req.headers["x-eqdb-token"]) { req.headers["x-pawerdb-token"] = req.headers["x-eqdb-token"]; } parts = req.url.split("/").filter(i => i.trim() !== ""); console.log(req.socket.address(), parts); if (parts.length === 0) { require('./modules/_.js')(req, res); } else if (!parts[0].includes("/") && parts[0].trim() !== "." && parts[0].trim() !== "..") { if (fs.existsSync(__dirname + '/modules/' + parts[0].trim() + '.js')) { if (typeof req.headers["x-pawerdb-token"] === "string") { processed = false; for (let entry of Object.keys(databases)) { if (databases[entry].access_tokens.includes(Buffer.from(req.headers["x-pawerdb-token"], "base64").toString("utf-8").trim())) { processed = true; try { require('./modules/' + parts[0].trim() + '.js')(req, res, entry, crypto.createHash('md5').update(entry).digest('hex')); } catch (e) { console.error(e); res.writeHead(502, {'Content-Type':'application/json'}); res.write("{\"error\":502}"); res.end(); } } } if (!processed) { res.writeHead(401, {'Content-Type':'application/json'}); res.write("{\"error\":401}"); res.end(); } } else { res.writeHead(401, {'Content-Type':'application/json'}); res.write("{\"error\":401}"); res.end(); } } else { res.writeHead(404, {'Content-Type':'application/json'}); res.write("{\"error\":404}"); res.end(); } } } catch (e) { console.error(e); res.writeHead(500, {'Content-Type':'application/json'}); res.write("{\"error\":500}"); res.end(); } }); server.listen(4459); console.log("EquestriaDB listening on port 4459")