Make the code more sane and improve the modularity of Revolution

This commit is contained in:
tgpethan 2019-11-23 19:06:31 +00:00
parent e042f3e4dd
commit 3b891869b8
6 changed files with 129 additions and 92 deletions

View file

@ -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!
*/
try {
if (files[i].includes(".js")) {
modules[files[i].toString().replace(".js", "")] = require(`./modules/${files[i].toString()}`);
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;
}

View file

@ -5,5 +5,6 @@
"dizzy":"😵",
"heavy_check":"✔️",
"folder":"📁",
"fast_up":"⏫"
"fast_up":"⏫",
"cross":"❌"
}

36
modules/consoleHelper.js Normal file
View file

@ -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;
}
}

View file

@ -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!<hr>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;

View file

@ -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;
}
}

View file

@ -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!<hr>Revolution");
} else {
modules.logger.log(`${internals.types.b}: ${req.method}`, emoji.page, `${req.url} was requested`);
res.sendFile(__dirname + req.url);
}
});
}
}
}