diff --git a/EUS.js b/EUS.js index cdb4762..a1cd072 100644 --- a/EUS.js +++ b/EUS.js @@ -12,11 +12,10 @@ let node_modules = {}; let eusConfig = {}, useUploadKey = true, cacheJSON = "", - startupFinished = false, timeSinceLastCache = Date.now(); class Database { - constructor(databaseAddress, databasePort = 3306, databaseUsername, databasePassword, databaseName, connectedCallback) { + constructor(databaseAddress, databasePort = 3306, databaseUsername, databasePassword, databaseName) { this.connectionPool = node_modules["mysql2"].createPool({ connectionLimit: 128, host: databaseAddress, @@ -25,26 +24,6 @@ class Database { password: databasePassword, database: databaseName }); - - const classCreationTime = Date.now(); - this.dbActive = false; - if (connectedCallback == null) { - this.dbActive = true; - } else { - const connectionCheckInterval = setInterval(() => { - this.query("SELECT id FROM images LIMIT 1") - .then(data => { - global.modules.consoleHelper.printInfo(emoji.globe_europe, `Connected to database. Took ${Date.now() - classCreationTime}ms`); - this.dbActive = true; - clearInterval(connectionCheckInterval); - - connectedCallback(); - }) - .catch(err => { - console.error(err); - }); - }, 167); // Roughly 6 times per sec - } } dataReceived(resolveCallback, data, limited = false) { @@ -139,11 +118,9 @@ function init() { if (validateConfig(eusConfig)) console.log("[EUS] EUS config passed all checks"); } - // This is using a callback but that's fine, the server will just react properly to the db not being ready yet. - dbConnection = new Database(eusConfig["database"]["databaseAddress"], eusConfig["database"]["databasePort"], eusConfig["database"]["databaseUsername"], eusConfig["database"]["databasePassword"], eusConfig["database"]["databaseName"], async () => { - cacheJSON = JSON.stringify(await cacheFilesAndSpace()); - cacheIsReady = true; - }); + if (!eusConfig["noUpload"]) { + dbConnection = new Database(eusConfig["database"]["databaseAddress"], eusConfig["database"]["databasePort"], eusConfig["database"]["databaseUsername"], eusConfig["database"]["databasePassword"], eusConfig["database"]["databaseName"]); + } console.log("[EUS] Finished loading."); } @@ -184,62 +161,70 @@ function cacheFilesAndSpace() { function validateConfig(json) { let performShutdownAfterValidation = false; // URL Tests - if (json["baseURL"] == null) { - console.error("EUS baseURL property does not exist!"); - performShutdownAfterValidation = true; - } else { - if (json["baseURL"] == "") console.warn("EUS baseURL property is blank"); - const bURL = `${json["baseURL"]}`.split(""); - if (bURL.length > 1) { - if (bURL[bURL.length-1] != "/") console.warn("EUS baseURL property doesn't have a / at the end, this can lead to unpredictable results!"); - } - else { - if (json["baseURL"] != "http://" || json["baseURL"] != "https://") console.warn("EUS baseURL property is possibly invalid!"); + if (!json["noUpload"]) { + if (json["baseURL"] == null) { + console.error("EUS baseURL property does not exist!"); + performShutdownAfterValidation = true; + } else { + if (json["baseURL"] == "") console.warn("EUS baseURL property is blank"); + const bURL = `${json["baseURL"]}`.split(""); + if (bURL.length > 1) { + if (bURL[bURL.length-1] != "/") console.warn("EUS baseURL property doesn't have a / at the end, this can lead to unpredictable results!"); + } + else { + if (json["baseURL"] != "http://" || json["baseURL"] != "https://") console.warn("EUS baseURL property is possibly invalid!"); + } } } // acceptedTypes checks - if (json["acceptedTypes"] == null) { - console.error("EUS acceptedTypes list does not exist!"); - performShutdownAfterValidation = true; - } else { - if (json["acceptedTypes"].length < 1) console.warn("EUS acceptedTypes array has no extentions in it, users will not be able to upload images!"); + if (!json["noUpload"]) { + if (json["acceptedTypes"] == null) { + console.error("EUS acceptedTypes list does not exist!"); + performShutdownAfterValidation = true; + } else { + if (json["acceptedTypes"].length < 1) console.warn("EUS acceptedTypes array has no extentions in it, users will not be able to upload images!"); + } } // uploadKey checks - if (json["uploadKey"] == null) { - console.error("EUS uploadKey property does not exist!"); - performShutdownAfterValidation = true; - } else { - if (json["uploadKey"] == "") useUploadKey = false; + if (!json["noUpload"]) { + if (json["uploadKey"] == null) { + console.error("EUS uploadKey property does not exist!"); + performShutdownAfterValidation = true; + } else { + if (json["uploadKey"] == "") useUploadKey = false; + } } // database checks - if (json["database"] == null) { - console.error("EUS database properties do not exist!"); - performShutdownAfterValidation = true; - } else { - // databaseAddress - if (json["database"]["databaseAddress"] == null) { - console.error("EUS database.databaseAddress property does not exist!"); - performShutdownAfterValidation = true; - } - // databasePort - if (json["database"]["databasePort"] == null) { - console.error("EUS database.databasePort property does not exist!"); - performShutdownAfterValidation = true; - } - // databaseUsername - if (json["database"]["databaseUsername"] == null) { - console.error("EUS database.databaseUsername property does not exist!"); - performShutdownAfterValidation = true; - } - // databasePassword - if (json["database"]["databasePassword"] == null) { - console.error("EUS database.databasePassword property does not exist!"); - performShutdownAfterValidation = true; - } - // databaseName - if (json["database"]["databaseName"] == null) { - console.error("EUS database.databaseName property does not exist!"); + if (!json["noUpload"]) { + if (json["database"] == null) { + console.error("EUS database properties do not exist!"); performShutdownAfterValidation = true; + } else { + // databaseAddress + if (json["database"]["databaseAddress"] == null) { + console.error("EUS database.databaseAddress property does not exist!"); + performShutdownAfterValidation = true; + } + // databasePort + if (json["database"]["databasePort"] == null) { + console.error("EUS database.databasePort property does not exist!"); + performShutdownAfterValidation = true; + } + // databaseUsername + if (json["database"]["databaseUsername"] == null) { + console.error("EUS database.databaseUsername property does not exist!"); + performShutdownAfterValidation = true; + } + // databasePassword + if (json["database"]["databasePassword"] == null) { + console.error("EUS database.databasePassword property does not exist!"); + performShutdownAfterValidation = true; + } + // databaseName + if (json["database"]["databaseName"] == null) { + console.error("EUS database.databaseName property does not exist!"); + performShutdownAfterValidation = true; + } } } @@ -251,48 +236,107 @@ function validateConfig(json) { else return true; } -function cleanURL(url = "") { - return url.split("%20").join(" ").split("%22").join("\"").split("%23").join("#").split("%24").join("$").split("%25").join("%").split("%26").join("&").split("%27").join("'").split("%2B").join("+").split("%2C").join(",").split("%2F").join("/") - .split("%3A").join(":").split("%3B").join(";").split("%3C").join("<").split("%3D").join("=").split("%3E").join(">").split("%3F").join("?") - .split("%40").join("@") - .split("%5B").join("[").split("%5C").join("\\").split("%5D").join("]").split("%5E").join("^") - .split("%60").join("`") - .split("%7B").join("{").split("%7C").join("|").split("%7D").join("}").split("%7E").join("~") - .split("%CE%A9").join("Ω"); -} - let existanceCache = {}; -function regularFile(req, res, urs = "", startTime = 0) { - if (req.url === "/") { urs = "/index.html" } else { urs = req.url } - fs.access(`${__dirname}${BASE_PATH}/files${urs}`, (error) => { - if (error) { - // Doesn't exist, send a 404 to the client. - error404Page(res); - global.modules.consoleHelper.printInfo(emoji.cross, `${req.method}: ${node_modules.chalk.red("[404]")} ${req.url} ${Date.now() - startTime}ms`); - } else { - // File does exist, send it back to the client. - res.sendFile(`${__dirname}${BASE_PATH}/files${req.url}`); - global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${node_modules.chalk.green("[200]")} ${req.url} ${Date.now() - startTime}ms`); - } +function fileExists(file) { + return new Promise((resolve) => { + fs.access(file, (error) => { + resolve(!error); + }); }); } +function sendFile(req, res, path, startTime) { + // File does exist, send it back to the client. + res.sendFile(path); + global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${node_modules.chalk.green("[200]")} ${req.url} ${Date.now() - startTime}ms`); +} + +async function regularFile(req, res, urs = "", startTime) { + if (req.url === "/") { urs = "/index.html" } else if (!req.url.includes(".") && !req.url.endsWith("/")) { urs = `${req.url}/index.html` } else { urs = req.url } + + if (await fileExists(`${__dirname}${BASE_PATH}/files${urs}`)) { + sendFile(req, res, `${__dirname}${BASE_PATH}/files${decodeURIComponent(urs)}`, startTime); + } else { + let isSuccess = false; + if (!urs.endsWith(".html")) { + if (await fileExists(`${__dirname}${BASE_PATH}/files${decodeURIComponent(urs)}.html`)) { + isSuccess = true; + sendFile(req, res, `${__dirname}${BASE_PATH}/files${decodeURIComponent(urs)}.html`, startTime); + } + } else if (urs.endsWith("/index.html")) { + const path = `${__dirname}${BASE_PATH}/files${decodeURIComponent(req.url)}.html`; + if (await fileExists(path)) { + isSuccess = true; + sendFile(req, res, path, startTime); + } + } + + if (!isSuccess) { + // Doesn't exist, send a 404 to the client. + await error404Page(res); + global.modules.consoleHelper.printInfo(emoji.cross, `${req.method}: ${node_modules.chalk.red("[404]")} ${req.url} ${Date.now() - startTime}ms`); + } + } +} + function imageFile(req, res, file, startTime = 0) { res.sendFile(`${__dirname}${BASE_PATH}/i/${file}`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${node_modules.chalk.green("[200]")} (ImageReq) ${req.url} ${Date.now() - startTime}ms`); } -function error404Page(res) { - res.status(404).send("404!