Merge pull request #25 from tgpethan/asyncify

Asyncify EUS
This commit is contained in:
Holly Stubbs 2021-03-16 18:53:07 +00:00 committed by GitHub
commit 78c6d91cb0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

649
EUS.js
View file

@ -1,383 +1,396 @@
const fs = require("fs"), const fs = require("fs"),
config = require("../config/config.json"), config = require("../config/config.json"),
chalk = require("chalk"), chalk = require("chalk"),
busboy = require("connect-busboy"), busboy = require("connect-busboy"),
randomstring = require("randomstring"), randomstring = require("randomstring"),
getSize = require("get-folder-size"), getSize = require("get-folder-size"),
diskUsage = require("diskusage"), diskUsage = require("diskusage-ng"),
emoji = require("../misc/emoji_list.json"); emoji = require("../misc/emoji_list.json");
// Defines the function of this module // Defines the function of this module
const MODULE_FUNCTION = "handle_requests", const MODULE_FUNCTION = "handle_requests",
// Base path for module folder creation and navigation // Base path for module folder creation and navigation
BASE_PATH = "/EUS"; BASE_PATH = "/EUS";
let eusConfig = {}, let eusConfig = {},
image_json = {}, image_json = {},
d = new Date(), d = new Date(),
startTime, startTime,
endTime, endTime,
useUploadKey = true, useUploadKey = true,
cacheJSON = ""; cacheJSON = "";
// Only ran on startup so using sync functions is fine // Only ran on startup so using sync functions is fine
// Makes the folder for files of the module // Makes the folder for files of the module
if (!fs.existsSync(__dirname + BASE_PATH)) { if (!fs.existsSync(__dirname + BASE_PATH)) {
fs.mkdirSync(__dirname + BASE_PATH); fs.mkdirSync(__dirname + BASE_PATH);
console.log(`[EUS] Made EUS module folder`); console.log(`[EUS] Made EUS module folder`);
} }
// Makes the folder for frontend files // Makes the folder for frontend files
if (!fs.existsSync(__dirname + BASE_PATH + "/files")) { if (!fs.existsSync(__dirname + BASE_PATH + "/files")) {
fs.mkdirSync(__dirname + BASE_PATH + "/files"); fs.mkdirSync(__dirname + BASE_PATH + "/files");
console.log(`[EUS] Made EUS web files folder`); console.log(`[EUS] Made EUS web files folder`);
} }
// Makes the folder for images // Makes the folder for images
if (!fs.existsSync(__dirname + BASE_PATH + "/i")) { if (!fs.existsSync(__dirname + BASE_PATH + "/i")) {
fs.mkdirSync(__dirname + BASE_PATH + "/i"); fs.mkdirSync(__dirname + BASE_PATH + "/i");
console.log(`[EUS] Made EUS images folder`); console.log(`[EUS] Made EUS images folder`);
} }
// Makes the image-type file // Makes the image-type file
if (!fs.existsSync(__dirname + BASE_PATH + "/image-type.json")) { if (!fs.existsSync(__dirname + BASE_PATH + "/image-type.json")) {
// Doesn't exist, create it. // Doesn't exist, create it.
fs.writeFileSync(`${__dirname}${BASE_PATH}/image-type.json`, '{}'); fs.writeFileSync(`${__dirname}${BASE_PATH}/image-type.json`, '{}');
console.log("[EUS] Made EUS image-type File!"); console.log("[EUS] Made EUS image-type File!");
// File has been created, load it. // File has been created, load it.
image_json = require(`${__dirname}${BASE_PATH}/image-type.json`); image_json = require(`${__dirname}${BASE_PATH}/image-type.json`);
} else { } else {
// File already exists, load it. // File already exists, load it.
const ijLoadStartTime = new Date().getTime(); const ijLoadStartTime = new Date().getTime();
image_json = require(`${__dirname}${BASE_PATH}/image-type.json`); image_json = require(`${__dirname}${BASE_PATH}/image-type.json`);
console.log(`[EUS] Loaded image-type file, took ${new Date().getTime() - ijLoadStartTime}ms`); console.log(`[EUS] Loaded image-type file, took ${new Date().getTime() - ijLoadStartTime}ms`);
} }
// Makes the config file // Makes the config file
if (!fs.existsSync(__dirname + BASE_PATH + "/config.json")) { if (!fs.existsSync(__dirname + BASE_PATH + "/config.json")) {
// Config doesn't exist, make it. // Config doesn't exist, make it.
fs.writeFileSync(`${__dirname}${BASE_PATH}/config.json`, '{\n\t"baseURL":"http://example.com/",\n\t"acceptedTypes": [\n\t\t".png",\n\t\t".jpg",\n\t\t".jpeg",\n\t\t".gif"\n\t],\n\t"uploadKey": ""\n}'); fs.writeFileSync(`${__dirname}${BASE_PATH}/config.json`, '{\n\t"baseURL":"http://example.com/",\n\t"acceptedTypes": [\n\t\t".png",\n\t\t".jpg",\n\t\t".jpeg",\n\t\t".gif"\n\t],\n\t"uploadKey": ""\n}');
console.log("[EUS] Made EUS config File!"); console.log("[EUS] Made EUS config File!");
console.log("[EUS] Please edit the EUS Config file before restarting."); console.log("[EUS] Please edit the EUS Config file before restarting.");
// Config has been made, close framework. // Config has been made, close framework.
process.exit(0); process.exit(0);
} else { } else {
eusConfig = require(`${__dirname}${BASE_PATH}/config.json`); eusConfig = require(`${__dirname}${BASE_PATH}/config.json`);
if (validateConfig(eusConfig)) console.log("[EUS] EUS config passed all checks"); if (validateConfig(eusConfig)) console.log("[EUS] EUS config passed all checks");
}
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("~");
} }
// Cache for the file count and space usage, this takes a while to do so it's best to cache the result // Cache for the file count and space usage, this takes a while to do so it's best to cache the result
let cacheIsReady = false; let cacheIsReady = false;
async function cacheFilesAndSpace() { async function cacheFilesAndSpace() {
const startCacheTime = new Date().getTime(); return new Promise((resolve, reject) => {
let cachedFilesAndSpace = { const startCacheTime = new Date().getTime();
files: {} let cachedFilesAndSpace = {
}, files: {}
},
// Cache file totals // Cache file totals
total = 0; total = 0;
// Add each accepted file type to the json // Add each accepted file type to the json
for (var i2 = 0; i2 < eusConfig.acceptedTypes.length; i2++) { for (var i2 = 0; i2 < eusConfig.acceptedTypes.length; i2++) {
cachedFilesAndSpace["files"][`${eusConfig.acceptedTypes[i2]}`.replace(".", "")] = 0; cachedFilesAndSpace["files"][`${eusConfig.acceptedTypes[i2]}`.replace(".", "")] = 0;
} }
// Read all files from the images directory // Read all files from the images directory
fs.readdir(__dirname + BASE_PATH + "/i", async (err, files) => { fs.readdir(__dirname + BASE_PATH + "/i", async (err, files) => {
if (err) throw err; if (err) reject(err);
// Loop through all files else {
for (var i = 0; i < files.length; i++) { // Loop through all files
// Loop through all accepted file types to check for a match for (var i = 0; i < files.length; i++) {
for (var i1 = 0; i1 < eusConfig.acceptedTypes.length; i1++) { // Loop through all accepted file types to check for a match
const jsudfg = files[i].split("."); for (var i1 = 0; i1 < eusConfig.acceptedTypes.length; i1++) {
if (`.${jsudfg[jsudfg.length-1]}` == eusConfig.acceptedTypes[i1]) { const readFileName = files[i].split(".");
// There is a match! Add it to the json if (`.${readFileName[readFileName.length-1]}` == eusConfig.acceptedTypes[i1]) {
cachedFilesAndSpace["files"][eusConfig.acceptedTypes[i1].replace(".", "")]++; // There is a match! Add it to the json
// Also increase the total cachedFilesAndSpace["files"][eusConfig.acceptedTypes[i1].replace(".", "")]++;
total++; // Also increase the total
} total++;
} }
} }
// Set the total in the json to the calculated total value }
cachedFilesAndSpace["files"]["total"] = total; // Set the total in the json to the calculated total value
cachedFilesAndSpace["files"]["total"] = total;
// Cache usage // Cache usage
cachedFilesAndSpace["space"] = { cachedFilesAndSpace["space"] = {
usage: {} usage: {}
}; };
// Get the space used on the disk // Get the space used on the disk
getSize(__dirname + BASE_PATH + "/i", async (err, size) => { getSize(__dirname + BASE_PATH + "/i", async (err, size) => {
if (err) throw err; if (err) reject(err);
// Calculate in different units the space taken up on disk else {
let sizeOfFolder = (size / 1024 / 1024); // Calculate in different units the space taken up on disk
cachedFilesAndSpace["space"]["usage"]["mb"] = sizeOfFolder; let sizeOfFolder = (size / 2048);
sizeOfFolder = (size / 1024 / 1024 / 1024); cachedFilesAndSpace["space"]["usage"]["mb"] = sizeOfFolder;
cachedFilesAndSpace["space"]["usage"]["gb"] = sizeOfFolder; sizeOfFolder = (size / 3072);
cachedFilesAndSpace["space"]["usage"]["string"] = spaceToLowest(size, true); cachedFilesAndSpace["space"]["usage"]["gb"] = sizeOfFolder;
// Get total disk space cachedFilesAndSpace["space"]["usage"]["string"] = await spaceToLowest(size, true);
diskUsage.check(__dirname, async (err, data) => { // Get total disk space
if (err) throw err; diskUsage(__dirname, async (err, data) => {
cachedFilesAndSpace["space"]["total"] = { if (err) reject(err);
value: spaceToLowest(data["total"], false), else {
mbvalue: (data["total"] / 1024 / 1024), cachedFilesAndSpace["space"]["total"] = {
gbvalue: (data["total"] / 1024 / 1024 / 1024), value: await spaceToLowest(data["total"], false),
stringValue: spaceToLowest(data["total"], true).split(" ")[1].toLowerCase(), mbvalue: (data["total"] / 2048),
string: spaceToLowest(data["total"], true) gbvalue: (data["total"] / 3072),
}; stringValue: (await spaceToLowest(data["total"], true)).split(" ")[1].toLowerCase(),
string: await spaceToLowest(data["total"], true)
};
cacheIsReady = true; resolve(cachedFilesAndSpace);
cacheJSON = JSON.stringify(cachedFilesAndSpace); global.modules.consoleHelper.printInfo(emoji.folder, `Stats api cache took ${new Date().getTime() - startCacheTime}ms`);
global.modules.consoleHelper.printInfo(emoji.folder, `Stats api cache took ${new Date().getTime() - startCacheTime}ms`); }
}); });
}); }
}); });
}
});
});
} }
function validateConfig(json) { function validateConfig(json) {
let performShutdownAfterValidation = false; let performShutdownAfterValidation = false;
// URL Tests // URL Tests
if (json["baseURL"] == null) { if (json["baseURL"] == null) {
console.error("EUS baseURL property does not exist!"); console.error("EUS baseURL property does not exist!");
performShutdownAfterValidation = true; performShutdownAfterValidation = true;
} else { } else {
if (json["baseURL"] == "") console.warn("EUS baseURL property is blank"); if (json["baseURL"] == "") console.warn("EUS baseURL property is blank");
const bURL = `${json["baseURL"]}`.split(""); const bURL = `${json["baseURL"]}`.split("");
if (bURL.length > 1) { 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!"); if (bURL[bURL.length-1] != "/") console.warn("EUS baseURL property doesn't have a / at the end, this can lead to unpredictable results!");
} }
else { else {
if (json["baseURL"] != "http://" || json["baseURL"] != "https://") console.warn("EUS baseURL property is possibly invalid!"); if (json["baseURL"] != "http://" || json["baseURL"] != "https://") console.warn("EUS baseURL property is possibly invalid!");
} }
} }
// acceptedTypes checks // acceptedTypes checks
if (json["acceptedTypes"] == null) { if (json["acceptedTypes"] == null) {
console.error("EUS acceptedTypes array does not exist!"); console.error("EUS acceptedTypes array does not exist!");
performShutdownAfterValidation = true; performShutdownAfterValidation = true;
} else { } 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["acceptedTypes"].length < 1) console.warn("EUS acceptedTypes array has no extentions in it, users will not be able to upload images!");
} }
// uploadKey checks // uploadKey checks
if (json["uploadKey"] == null) { if (json["uploadKey"] == null) {
console.error("EUS uploadKey property does not exist!"); console.error("EUS uploadKey property does not exist!");
performShutdownAfterValidation = true; performShutdownAfterValidation = true;
} else { } else {
if (json["uploadKey"] == "") useUploadKey = false; if (json["uploadKey"] == "") useUploadKey = false;
} }
// Check if server needs to be shutdown // Check if server needs to be shutdown
if (performShutdownAfterValidation) { if (performShutdownAfterValidation) {
console.error("EUS config properties are missing, refer to docs for more details (https://docs.ethanus.ml)"); console.error("EUS config properties are missing, refer to docs for more details (https://docs.ethanus.ml)");
process.exit(1); process.exit(1);
} }
else return true; 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("~");
} }
module.exports = { module.exports = {
extras:function() { extras:async function() {
// Setup express to use busboy // Setup express to use busboy
global.app.use(busboy()); global.app.use(busboy());
cacheFilesAndSpace(); cacheJSON = JSON.stringify(await cacheFilesAndSpace());
}, cacheIsReady = true;
get:function(req, res) { },
/* get:async function(req, res) {
req - Request from client /*
res - Response from server req - Request from client
*/ res - Response from server
*/
// Set some headers // Set some headers
res.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains"); res.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
res.set("X-XSS-Protection", "1; mode=block"); res.set("X-XSS-Protection", "1; mode=block");
res.set("Feature-Policy", "fullscreen 'none'"); res.set("Feature-Policy", "fullscreen 'none'");
res.set("Permissions-Policy", "microphone=(), geolocation=(), magnetometer=(), camera=(), payment=(), usb=(), accelerometer=(), gyroscope=()"); res.set("Permissions-Policy", "microphone=(), geolocation=(), magnetometer=(), camera=(), payment=(), usb=(), accelerometer=(), gyroscope=()");
res.set("Referrer-Policy", "strict-origin-when-cross-origin"); res.set("Referrer-Policy", "strict-origin-when-cross-origin");
res.set("Content-Security-Policy", "block-all-mixed-content;frame-ancestors 'self'"); res.set("Content-Security-Policy", "block-all-mixed-content;frame-ancestors 'self'");
res.set("X-Frame-Options", "SAMEORIGIN"); res.set("X-Frame-Options", "SAMEORIGIN");
res.set("X-Content-Type-Options", "nosniff"); res.set("X-Content-Type-Options", "nosniff");
req.url = cleanURL(req.url); req.url = cleanURL(req.url);
// Check if returned value is true. // Check if returned value is true.
if (req.url.includes("/api/")) return handleAPI(req, res); if (req.url.includes("/api/")) return handleAPI(req, res);
// Register the time at the start of the request // Register the time at the start of the request
d = new Date(); d = new Date();
startTime = d.getTime(); startTime = d.getTime();
// Get the requested image
let urs = ""+req.url; urs = urs.split("/")[1];
// Get the file type of the image from image_json and make sure it exists
fs.access(__dirname + BASE_PATH + "/i/"+urs+image_json[urs], error => {
if (error) {
// Doesn't exist, handle request normaly
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.
res.status(404).end("404!");
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.cross, `${req.method}: ${chalk.red("[404]")} ${req.url} ${endTime - startTime}ms`);
} else {
// File does exist, send it back to the client.
res.sendFile(__dirname + BASE_PATH + "/files"+req.url);
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
}
});
} else {
// Image does exist, send it back.
res.sendFile(__dirname + BASE_PATH + "/i/"+urs+image_json[urs]);
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
}
});
},
post:function(req, res) {
/*
req - Request from client
res - Response from server
*/
// Make sure the endpoint is /upload // Get the requested image
// If it isn't upload send an empty response let urs = `${req.url}`; urs = urs.split("/")[1];
if (req.url != "/upload") return res.end(""); // Get the file type of the image from image_json and make sure it exists
fs.access(`${__dirname}${BASE_PATH}/i/${urs}${image_json[urs]}`, (error) => {
if (error) {
// Doesn't exist, handle request normaly
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.
res.status(404).send("404!<hr>EUS");
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.cross, `${req.method}: ${chalk.red("[404]")} ${req.url} ${endTime - startTime}ms`);
} else {
// File does exist, send it back to the client.
res.sendFile(__dirname + BASE_PATH + "/files"+req.url);
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
}
});
} else {
// Image does exist, send it back.
res.sendFile(`${__dirname}${BASE_PATH}/i/${urs}${image_json[urs]}`);
d = new Date();
endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
}
});
},
post:async function(req, res) {
/*
req - Request from client
res - Response from server
*/
// Get time at the start of upload // Make sure the endpoint is /upload
// If it isn't upload send an empty response
if (req.url != "/upload") return res.end("");
if (useUploadKey && eusConfig["uploadKey"] != req.header("key")) return res.end("Incorrect key provided for upload"); // Get time at the start of upload
d = new Date(); startTime = d.getTime(); if (useUploadKey && eusConfig["uploadKey"] != req.header("key")) return res.end("Incorrect key provided for upload");
var fstream;
var thefe;
// Pipe the request to busboy
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
// Get the image-type json
image_json = require(`${__dirname}${BASE_PATH}/image-type.json`);
// Make a new file name
fileOutName = randomstring.generate(14);
global.modules.consoleHelper.printInfo(emoji.fast_up, `${req.method}: Upload of ${fileOutName} started.`);
// Check the file is within the accepted file types
if (eusConfig.acceptedTypes.includes(`.${filename.split(".")[filename.split(".").length-1]}`)) {
// File is accepted, set the extention of the file in thefe for later use.
thefe = `.${filename.split(".")[filename.split(".").length-1]}`;
} else {
// File isn't accepted, send response back to client stating so.
res.status(403).end("This file type isn't accepted currently.");
return;
}
// Create a write stream for the file
fstream = fs.createWriteStream(__dirname + BASE_PATH + "/i/" + fileOutName + thefe);
file.pipe(fstream);
fstream.on('close', function () {
// Get the time at the end of the upload
d = new Date(); endTime = d.getTime();
// Add image file type to the image_json array
image_json[fileOutName] = `.${filename.split(".")[filename.split(".").length-1]}`;
// Save image_json array to the file
fs.writeFile(`${__dirname}${BASE_PATH}/image-type.json`, JSON.stringify(image_json), function(err) {
if (err) throw err;
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: Upload of ${fileOutName} finished. Took ${endTime - startTime}ms`);
// Send URL of the uploaded image to the client
res.end(eusConfig.baseURL+""+fileOutName);
// Update cached files & space d = new Date(); startTime = d.getTime();
cacheFilesAndSpace(); var fstream;
}); var thefe;
}); // Pipe the request to busboy
}); req.pipe(req.busboy);
} req.busboy.on('file', function (fieldname, file, filename) {
// Get the image-type json
image_json = require(`${__dirname}${BASE_PATH}/image-type.json`);
// Make a new file name
fileOutName = randomstring.generate(14);
global.modules.consoleHelper.printInfo(emoji.fast_up, `${req.method}: Upload of ${fileOutName} started.`);
// Check the file is within the accepted file types
if (eusConfig.acceptedTypes.includes(`.${filename.split(".")[filename.split(".").length-1]}`)) {
// File is accepted, set the extention of the file in thefe for later use.
thefe = `.${filename.split(".")[filename.split(".").length-1]}`;
} else {
// File isn't accepted, send response back to client stating so.
res.status(403).end("This file type isn't accepted currently.");
return;
}
// Create a write stream for the file
fstream = fs.createWriteStream(__dirname + BASE_PATH + "/i/" + fileOutName + thefe);
file.pipe(fstream);
fstream.on('close', function () {
// Get the time at the end of the upload
d = new Date(); endTime = d.getTime();
// Add image file type to the image_json array
image_json[fileOutName] = `.${filename.split(".")[filename.split(".").length-1]}`;
// Save image_json array to the file
fs.writeFile(`${__dirname}${BASE_PATH}/image-type.json`, JSON.stringify(image_json), async (err) => {
if (err) reject(err);
else {
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: Upload of ${fileOutName} finished. Took ${endTime - startTime}ms`);
// Send URL of the uploaded image to the client
res.end(eusConfig.baseURL+""+fileOutName);
// Update cached files & space
cacheJSON = JSON.stringify(await cacheFilesAndSpace());
}
});
});
});
}
} }
function handleAPI(req, res) { async function handleAPI(req, res) {
d = new Date(); startTime = d.getTime(); d = new Date(); startTime = d.getTime();
let jsonaa = {}, filesaa = 0, spaceaa = 0; let jsonaa = {}, filesaa = 0, spaceaa = 0;
switch (req.url.split("?")[0]) { switch (req.url.split("?")[0]) {
// Status check to see the onlint status of EUS // Status check to see the onlint status of EUS
// Used by ESL to make sure EUS is online // Used by ESL to make sure EUS is online
case "/api/get-server-status": case "/api/get-server-status":
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
return res.end('{ "status":1, "version":"'+global.internals.version+'" }'); return res.end('{ "status":1, "version":"'+global.internals.version+'" }');
/* Stats api endpoint /* Stats api endpoint
Query inputs Query inputs
f : Values [0,1] f : Values [0,1]
s : Values [0,1] s : Values [0,1]
*/ */
case "/api/get-stats": case "/api/get-stats":
filesaa = req.query["f"]; filesaa = req.query["f"];
spaceaa = req.query["s"]; spaceaa = req.query["s"];
if (!cacheIsReady) return res.end("Cache is not ready"); if (!cacheIsReady) return res.end("Cache is not ready");
jsonaa = JSON.parse(cacheJSON); jsonaa = JSON.parse(cacheJSON);
// If total files is asked for // If total files is asked for
if (filesaa == 1) { if (filesaa == 1) {
// If getting the space used on the server isn't required send the json // If getting the space used on the server isn't required send the json
if (spaceaa != 1) { if (spaceaa != 1) {
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
delete jsonaa["space"]; delete jsonaa["space"];
return res.end(JSON.stringify(jsonaa)); return res.end(JSON.stringify(jsonaa));
} }
} }
// Getting space is required // Getting space is required
if (spaceaa == 1) { if (spaceaa == 1) {
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
if (filesaa != 1) delete jsonaa["files"]; if (filesaa != 1) delete jsonaa["files"];
return res.end(JSON.stringify(jsonaa)); return res.end(JSON.stringify(jsonaa));
} }
if (filesaa != 1 && spaceaa != 1) { if (filesaa != 1 && spaceaa != 1) {
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
return res.end("Please add f and or s to your queries to get the files and space"); return res.end("Please add f and or s to your queries to get the files and space");
} }
break; break;
// Information API // Information API
case "/api/get-info": case "/api/get-info":
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
return res.end(JSON.stringify({ return res.end(JSON.stringify({
version: global.internals.version, version: global.internals.version,
instance: config["server"]["instance_type"] instance: config["server"]["instance_type"]
})); }));
default: default:
d = new Date(); endTime = d.getTime(); d = new Date(); endTime = d.getTime();
global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`); global.modules.consoleHelper.printInfo(emoji.heavy_check, `${req.method}: ${chalk.green("[200]")} ${req.url} ${endTime - startTime}ms`);
return res.send(` return res.send(`
<h2>All currently avaliable api endpoints</h2> <h2>All currently avaliable api endpoints</h2>
<a href="/api/get-server-status">/api/get-server-status</a> <a href="/api/get-server-status">/api/get-server-status</a>
<a href="/api/get-stats">/api/get-stats</a> <a href="/api/get-stats">/api/get-stats</a>
<a href="/api/get-info">/api/get-info</a> <a href="/api/get-info">/api/get-info</a>
`); `);
} }
} }
const spaceValues = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]; // Futureproofing:tm: const spaceValues = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]; // Futureproofing:tm:
function spaceToLowest(spaceValue, includeStringValue) { async function spaceToLowest(spaceValue, includeStringValue) {
// Converts space values to lower values e.g MB, GB, TB etc depending on the size of the number return new Promise((resolve, reject) => {
let i1 = 1; // Converts space values to lower values e.g MB, GB, TB etc depending on the size of the number
// Loop through until value is at it's lowest let i1 = 1;
for (let i = 0; i < i1; i++) { // Loop through until value is at it's lowest
if (spaceValue >= 1024) { for (let i = 0; i < i1; i++) {
spaceValue = spaceValue / 1024; if (spaceValue >= 1024) {
} spaceValue = spaceValue / 1024;
}
if (spaceValue >= 1024) i1++; if (spaceValue >= 1024) i1++;
} }
if (includeStringValue) return `${spaceValue.toFixed(2)} ${spaceValues[i1]}`; if (includeStringValue) resolve(`${spaceValue.toFixed(2)} ${spaceValues[i1]}`);
else return spaceValue; else resolve(spaceValue);
});
} }
module.exports.MOD_FUNC = MODULE_FUNCTION; module.exports.MOD_FUNC = MODULE_FUNCTION;