From 3b891869b8c057642239b4d9b193cda2beb6893e Mon Sep 17 00:00:00 2001 From: tgpethan Date: Sat, 23 Nov 2019 19:06:31 +0000 Subject: [PATCH] Make the code more sane and improve the modularity of Revolution --- index.js | 71 +++++++++++++++++++----------- misc/emoji_list.json | 3 +- modules/consoleHelper.js | 36 +++++++++++++++ modules/example_request_handler.js | 46 +++++++++++++++++++ modules/logger.js | 37 ---------------- modules/request_handler.js | 28 ------------ 6 files changed, 129 insertions(+), 92 deletions(-) create mode 100644 modules/consoleHelper.js create mode 100644 modules/example_request_handler.js delete mode 100644 modules/logger.js delete mode 100644 modules/request_handler.js diff --git a/index.js b/index.js index 8e86eb9..39e0f91 100644 --- a/index.js +++ b/index.js @@ -1,27 +1,26 @@ -const express = require("express"), app = express(), fs = require("fs"), chalk = require("chalk"), config = require("./config/config.json"), emoji = require("./misc/emoji_list.json"), -internals = { - version:"0.0.4 RELEASE", - types: { - a:"INFO", - b:"REQUEST", - c:"WARN" - } +const express = require("express"), +app = express(), +fs = require("fs"), +chalk = require("chalk"), +config = require("./config/config.json"), +emoji = require("./misc/emoji_list.json"); +global.actualDir = __dirname; +global.internals = { + version:"Open Source", }; -let dE = new Date(), startTime = dE.getTime(), endTime, modules = []; +global.modules = []; +let dE = new Date(), +startTime = dE.getTime(), +endTime, +reqhandler; // Clear console before printing anything console.clear(); fs.readFile('./misc/ascii.txt', function(err, data) { if (err) throw err; - // Generate the banner - let asciiOut = data.toString() - .replace("|replaceVersion|", `${chalk.yellow("Version:")} ${chalk.cyan(internals.version)}`) - .replace("|titlecard|", chalk.yellow("The web server made for EUS")) - .replace("DEV", chalk.red("DEV")).replace("RELEASE", chalk.green("RELEASE")) - .replace("|replaceType|", `${chalk.yellow("Type: ")}${chalk.cyan(config.server.instance_type)}`); - // Print the banner - console.log(asciiOut); + // Generate and Print the banner + console.log(highlightHeader(data)); // Get the modules from the ./modules folder fs.readdir("./modules", (err, files) => { if (err) throw err; @@ -31,21 +30,41 @@ fs.readFile('./misc/ascii.txt', function(err, data) { in the console and attempt to load it using require. Oh, and check that it has .js in it's file name! */ - if (files[i].includes(".js")) { - modules[files[i].toString().replace(".js", "")] = require(`./modules/${files[i].toString()}`); - console.log(`[Modules] Found module ${files[i].toString()}`); - } else { - console.log(`[Modules] Found file ${files[i]}. It is not a module.`) + try { + if (files[i].includes(".js")) { + global.modules[files[i].toString().replace(".js", "")] = require(`./modules/${files[i].toString()}`); + console.log(`[Modules] Found module ${files[i].toString()}`); + // We want to find out what the request handler module is + if (global.modules[files[i].toString().replace(".js", "")].MOD_FUNC == "handle_requests") { + reqhandler = global.modules[files[i].toString().replace(".js", "")]; + } + } else { + if (files[i].split(".").length < 2) continue; + console.log(`[Modules] Found file ${files[i]}. It is not a module.`) + } + } catch (err) { + console.log(chalk.bgRed(` ! [Modules] There was an issue loading ${files[i]} ! `)); + console.log(chalk.bgRed(` ! [Modules] ${err} ! `)); } } - modules.logger.log(internals.types.a, emoji.wave, "Starting Revolution..."); + global.modules.consoleHelper.printInfo(emoji.wave, "Starting Revolution..."); server(); }); }); function server() { - app.get('*', (req, res) => { modules.request_handler.handle(modules, internals, emoji, req, res); }); - app.listen(config.server.port, () => { dE = new Date(), endTime = dE.getTime(); - modules.logger.log(internals.types.a, emoji.thumb_up, `Started Revolution on port ${config.server.port}! Took ${endTime - startTime}ms`); + app.get('*', (req, res) => reqhandler.get(req, res)); + app.post('*', (req, res) => reqhandler.post(req, res)); + app.listen(config.server.port, () => { + dE = new Date(), + endTime = dE.getTime(); + global.modules.consoleHelper.printInfo(emoji.thumb_up, `Started Revolution on port ${config.server.port}! Took ${endTime - startTime}ms`); }); +} + +function highlightHeader(s) { + const s1 = s.toString().replace("|replaceVersion|", `${chalk.yellow("Version:")} ${chalk.cyan(internals.version)}`) + .replace("|titlecard|", chalk.yellow("A modular and fexible server")) + .replace("|replaceType|", `${chalk.yellow("Instance: ")}${chalk.cyan(config.server.instance_type)}`); + return s1; } \ No newline at end of file diff --git a/misc/emoji_list.json b/misc/emoji_list.json index be4a260..e330c85 100644 --- a/misc/emoji_list.json +++ b/misc/emoji_list.json @@ -5,5 +5,6 @@ "dizzy":"😵", "heavy_check":"✔️", "folder":"📁", - "fast_up":"⏫" + "fast_up":"⏫", + "cross":"❌" } \ No newline at end of file diff --git a/modules/consoleHelper.js b/modules/consoleHelper.js new file mode 100644 index 0000000..c46a1a7 --- /dev/null +++ b/modules/consoleHelper.js @@ -0,0 +1,36 @@ +const chalk = require("chalk"); + +// Defines the function of this module +const MODULE_FUNCTION = "handle_console", + +// Base path for module folder creation and navigation +BASE_PATH = null; + +module.exports = { + printInfo:function(emoji, s) { + console.log(chalk.green(`[${this.getTime24()}] `)+chalk.bgGreen(chalk.black(" INFO "))+` ${emoji} ${s}`); + }, + + printWarn:function(emoji, s) { + console.warn(chalk.green(`[${this.getTime24()}] `)+chalk.bgYellow(chalk.black(" WARN "))+` ${emoji} ${s}`); + }, + + printError:function(emoji, s) { + console.error(chalk.green(`[${this.getTime24()}] `)+chalk.bgRed(chalk.black(" ERROR "))+` ${emoji} ${s}`); + }, + + getTime24:function() { + const time = new Date(); + return `${correctValue(time.getHours())}:${correctValue(time.getMinutes())}:${correctValue(time.getSeconds())}` + } +} + +module.exports.MOD_FUNC = MODULE_FUNCTION; + +function correctValue(i) { + if (i < 10) { + return "0"+i; + } else { + return i; + } +} \ No newline at end of file diff --git a/modules/example_request_handler.js b/modules/example_request_handler.js new file mode 100644 index 0000000..73ef0ee --- /dev/null +++ b/modules/example_request_handler.js @@ -0,0 +1,46 @@ +const fs = require("fs"), +emoji = require("../misc/emoji_list.json"); + +// Defines the function of this module +const MODULE_FUNCTION = "handle_requests", + +// Base path for module folder creation and navigation +BASE_PATH = "/example_request_handler"; + +// Only ran on startup so using sync functions is fine +// Makes the folders for files of the module +if (!fs.existsSync(__dirname + BASE_PATH)) { + fs.mkdirSync(__dirname + BASE_PATH); +} +if (!fs.existsSync(__dirname + BASE_PATH + "/files")) { + fs.mkdirSync(__dirname + BASE_PATH + "/files"); +} + +module.exports = { + get:function(req, res) { + /* + req - Request from client + res - Response from server + */ + + fs.access(__dirname + BASE_PATH + "/files" + req.url, fs.F_OK, error => { + if (error) { + global.modules.consoleHelper.printWarn(emoji.page, `${req.method}: ${req.url} was requested - Returned 404`); + res.status(404).send("404!
Revolution"); + } else { + global.modules.consoleHelper.printInfo(emoji.page, `${req.method}: ${req.url} was requested`); + res.sendFile(__dirname + BASE_PATH + "/files" + req.url); + } + }); + }, + post:function(req, res) { + /* + req - Request from client + res - Response from server + */ + + // Anything that needs to be done with a post can be done here. + } +} + +module.exports.MOD_FUNC = MODULE_FUNCTION; \ No newline at end of file diff --git a/modules/logger.js b/modules/logger.js deleted file mode 100644 index 7aede69..0000000 --- a/modules/logger.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -const fs = require("fs"); -const chalk = require("chalk"); -let d = new Date(); - -module.exports = { - log: function(type, emoji, text) { - d = new Date(); - console.log(`${chalk.green(`[${timeNumbers(d.getHours())}:${timeNumbers(d.getMinutes())}:${timeNumbers(d.getSeconds())} - ${type}]`)} ${emoji} ${text}`) - } -} - -function timeNumbers(inp) { - if (inp == 0) { - return "00"; - } else if (inp == 1) { - return "01"; - } else if (inp == 2) { - return "02"; - } else if (inp == 3) { - return "03"; - } else if (inp == 4) { - return "04"; - } else if (inp == 5) { - return "05"; - } else if (inp == 6) { - return "06"; - } else if (inp == 7) { - return "07"; - } else if (inp == 8) { - return "08"; - } else if (inp == 9) { - return "09"; - } else { - return inp; - } -} \ No newline at end of file diff --git a/modules/request_handler.js b/modules/request_handler.js deleted file mode 100644 index 645fe89..0000000 --- a/modules/request_handler.js +++ /dev/null @@ -1,28 +0,0 @@ -const fs = require("fs"); - -module.exports = { - handle:function(modules, internals, emoji, req, res) { - /* - modules - Modules that are loaded when Revolution starts - internals - Predefined variables, e.g the version and lables like "INFO" - emoji - Pretty self explanitory, the list of emojis used in Revolution. - req - Request from client - res - Response from server - */ - res.set("Server-Type", "Revolution"); - if (req.url == "/") { - modules.logger.log(`${internals.types.b}: ${req.method}`, emoji.page, `${req.url} was requested`); - res.end(); // Send a blank response, this can be changed to make it do whatever. - } else { - fs.access(__dirname + req.url, fs.constants.F_OK | fs.constants.W_OK, (err) => { - if (err) { - modules.logger.log(`${internals.types.b}: ${req.method}`, emoji.page, `${req.url} was requested - Returned 404`); - res.status(404).send("404!
Revolution"); - } else { - modules.logger.log(`${internals.types.b}: ${req.method}`, emoji.page, `${req.url} was requested`); - res.sendFile(__dirname + req.url); - } - }); - } - } -} \ No newline at end of file