From 7f273b3696623a15935c4729c14407c1e52569ba Mon Sep 17 00:00:00 2001 From: Matheus sampaio Queiroga Date: Mon, 19 Jul 2021 15:03:16 -0300 Subject: [PATCH 1/3] Move scripts/ to src/ folder --- .Build/test/ci.js | 22 +++ BdsManegerInfo.json | 2 +- bin/bds_maneger.js | 14 +- bin/telegram_bot.js | 8 +- index.js | 16 +- lib/BdsSettings.js | 2 +- lib/git_simples.js | 2 +- lib/tempHost.js | 2 +- package.json | 3 +- rest/api.js | 210 --------------------- {scripts => src/Scripts}/CheckKill.js | 0 {scripts => src/Scripts}/LoadCronBackup.js | 2 +- {scripts => src/Scripts}/PlayersSave.js | 4 +- {scripts => src/Scripts}/ServerSettings.js | 2 +- {scripts => src/Scripts}/backups.js | 4 +- {scripts => src/Scripts}/basic_server.js | 6 +- {scripts => src/Scripts}/check.js | 2 +- {scripts => src/Scripts}/download.js | 10 +- {scripts => src/Scripts}/external_ip.js | 0 {clouds => src/clouds}/Auth/Google.js | 4 +- {clouds => src/clouds}/Azure.js | 2 +- {clouds => src/clouds}/GoogleDriver.js | 2 +- {clouds => src/clouds}/OracleCI.js | 2 +- src/rest/api.js | 69 +++++++ src/rest/html/Home.html | 11 ++ src/rest/routes/bds.js | 101 ++++++++++ src/rest/routes/players.js | 51 +++++ 27 files changed, 299 insertions(+), 254 deletions(-) create mode 100644 .Build/test/ci.js delete mode 100644 rest/api.js rename {scripts => src/Scripts}/CheckKill.js (100%) rename {scripts => src/Scripts}/LoadCronBackup.js (94%) rename {scripts => src/Scripts}/PlayersSave.js (98%) rename {scripts => src/Scripts}/ServerSettings.js (99%) rename {scripts => src/Scripts}/backups.js (96%) rename {scripts => src/Scripts}/basic_server.js (98%) rename {scripts => src/Scripts}/check.js (96%) rename {scripts => src/Scripts}/download.js (96%) rename {scripts => src/Scripts}/external_ip.js (100%) rename {clouds => src/clouds}/Auth/Google.js (97%) rename {clouds => src/clouds}/Azure.js (95%) rename {clouds => src/clouds}/GoogleDriver.js (94%) rename {clouds => src/clouds}/OracleCI.js (96%) create mode 100644 src/rest/api.js create mode 100644 src/rest/html/Home.html create mode 100644 src/rest/routes/bds.js create mode 100644 src/rest/routes/players.js diff --git a/.Build/test/ci.js b/.Build/test/ci.js new file mode 100644 index 0000000..7a18fbd --- /dev/null +++ b/.Build/test/ci.js @@ -0,0 +1,22 @@ +(async ()=>{ + try { + const bds = require("../../index"); + await bds.download("latest", true) + console.log("Date:", await bds.BdsDate()); + console.log("Api:", await bds.api()); + console.log("Backup:", await bds.backup()); + console.log("Detect Server:", await bds.detect()); + console.log("Kill Server:", await bds.kill()); + console.log("Get Config:", await bds.get_config()); + console.log("Start:", await bds.start()); + setTimeout(() => { + console.log("Kill Server:", bds.kill()); + }, 1 * 30 * 1000); + setTimeout(() => { + process.exit(0); + }, 1 * 60 * 1000); + } catch (err) { + console.log("Detect Error:", err); + process.exit(1) + } +})() \ No newline at end of file diff --git a/BdsManegerInfo.json b/BdsManegerInfo.json index b9dfc33..df0cfc7 100644 --- a/BdsManegerInfo.json +++ b/BdsManegerInfo.json @@ -1,7 +1,7 @@ { "docs_base": "https://docs.bdsmaneger.com/docs/Bds Maneger core", "docs": { - "url": "https://docs.the-bds-maneger.org", + "url": "https://docs.bdsmaneger.com", "main": "Bds Maneger core", "rest_api": "docs/Bds Maneger core/REST API/" }, diff --git a/bin/bds_maneger.js b/bin/bds_maneger.js index 0fd6443..9fcf6a6 100755 --- a/bin/bds_maneger.js +++ b/bin/bds_maneger.js @@ -1,11 +1,11 @@ #!/usr/bin/env node if (process.platform === "win32") process.title = "Bds Maneger CLI";else process.title = "Bds_Manger_CLI" const readline = require("readline"); -const bds = require("../index"); -const { valid_platform } = require("../lib/BdsSystemInfo"); -const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings"); -const commandExits = require("../lib/commandExist"); -const download = require("../scripts/download"); +const bds = require("../../index"); +const { valid_platform } = require("../../lib/BdsSystemInfo"); +const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../../lib/BdsSettings"); +const commandExits = require("../../lib/commandExist"); +const download = require("../src/Scripts/download"); process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true; // Bds Maneger ArgV const argv = require("minimist")(process.argv.slice(2)); @@ -24,7 +24,7 @@ if (kill) bds.kill(); if (server) UpdatePlatform(server); function StartServer(){ - const { Servers } = require("../lib/ServerURL"); + const { Servers } = require("../../lib/ServerURL"); // Check Server Update if (Versions[GetPlatform()] !== null) { if (Versions[GetPlatform()] !== Servers.latest[GetPlatform()]) { @@ -161,7 +161,7 @@ if (bds_version){ try { if (argv.interactive) { console.log(`Geting versions to ${GetPlatform()}`); - const LoadVersion = require("../lib/ServerURL").Servers[GetPlatform()] + const LoadVersion = require("../../lib/ServerURL").Servers[GetPlatform()] const Version = Object.getOwnPropertyNames(LoadVersion) // List Version for (let version in Version) console.log(`${version}: ${GetPlatform()} version ${Version[version]}`); // deepscan-disable-line FORIN_ARRAY diff --git a/bin/telegram_bot.js b/bin/telegram_bot.js index 971c7ff..fd297df 100644 --- a/bin/telegram_bot.js +++ b/bin/telegram_bot.js @@ -1,10 +1,10 @@ const { Telegraf } = require("telegraf"); const fs = require("fs"); const path = require("path"); -const bds = require("../index"); -const { GetPlatform, GetPaths } = require("../lib/BdsSettings"); -const { GetKernel, arch, system } = require("../lib/BdsSystemInfo"); -const { Detect } = require("../scripts/CheckKill"); +const bds = require("../../index"); +const { GetPlatform, GetPaths } = require("../../lib/BdsSettings"); +const { GetKernel, arch, system } = require("../../lib/BdsSystemInfo"); +const { Detect } = require("../src/Scripts/CheckKill"); const TelegramOptions = require("minimist")(process.argv.slice(2)); if (TelegramOptions.h || TelegramOptions.help) { diff --git a/index.js b/index.js index 05939fe..a68b664 100644 --- a/index.js +++ b/index.js @@ -32,14 +32,14 @@ const { GetPaths, GetJsonConfig, UpdatePlatform, UpdateTelegramToken, GetTelegra module.exports.arch = arch if (typeof fetch === "undefined") global.fetch = require("node-fetch"); -const maneger_ips = require("./scripts/external_ip") +const maneger_ips = require("./src/Scripts/external_ip") module.exports.internal_ip = maneger_ips.internal_ip module.exports.external_ip = maneger_ips.external_ip module.exports.save_google_id = require("./lib/BdsSettings").CloudConfig.Driver module.exports.getBdsConfig = GetJsonConfig module.exports.change_platform = module.exports.platform_update = UpdatePlatform module.exports.telegram_token_save = UpdateTelegramToken -module.exports.api = require("./rest/api"); +module.exports.api = require("./src/rest/api"); // ------------ const user_file_connected = GetPaths("player"); @@ -89,10 +89,10 @@ function token_register() { module.exports.BdsSettigs = require("./lib/BdsSettings"); // Requires -const { World_BAckup } = require("./scripts/backups"); -const { config, get_config, config_example } = require("./scripts/ServerSettings"); -const download = require("./scripts/download"); -const { start, stop, BdsCommand } = require("./scripts/basic_server") +const { World_BAckup } = require("./src/Scripts/backups"); +const { config, get_config, config_example } = require("./src/Scripts/ServerSettings"); +const download = require("./src/Scripts/download"); +const { start, stop, BdsCommand } = require("./src/Scripts/basic_server") /** * Register tokens to use in Bds Maneger REST and other supported applications @@ -130,7 +130,7 @@ module.exports.stop = stop */ module.exports.backup = World_BAckup -const { Kill, Detect } = require("./scripts/CheckKill") +const { Kill, Detect } = require("./src/Scripts/CheckKill") /** * identify if there are any servers running in the background @@ -196,4 +196,4 @@ module.exports.tmphost = require("./lib/tempHost") /** * Load Crontab Backup */ -module.exports.Cron_Loaded = require("./scripts/LoadCronBackup") \ No newline at end of file +module.exports.Cron_Loaded = require("./src/Scripts/LoadCronBackup") \ No newline at end of file diff --git a/lib/BdsSettings.js b/lib/BdsSettings.js index 57f824e..d5dc267 100644 --- a/lib/BdsSettings.js +++ b/lib/BdsSettings.js @@ -6,7 +6,7 @@ const yaml = { stringify: require("js-yaml").dump } const FetchSync = require("@the-bds-maneger/fetchsync"); -const { external_ip } = require("../scripts/external_ip"); +const { external_ip } = require("../src/Scripts/external_ip"); const { valid_platform } = require("./BdsSystemInfo"); // PATHs diff --git a/lib/git_simples.js b/lib/git_simples.js index fc42bab..614d0dd 100644 --- a/lib/git_simples.js +++ b/lib/git_simples.js @@ -1,5 +1,5 @@ const { execSync, execFileSync } = require("child_process") -const commandExists = require("../lib/commandExist").sync +const commandExists = require("./commandExist").sync const { existsSync } = require("fs"); const { resolve, join } = require("path") diff --git a/lib/tempHost.js b/lib/tempHost.js index 7a716c8..09ec949 100644 --- a/lib/tempHost.js +++ b/lib/tempHost.js @@ -1,5 +1,5 @@ const fetchSync = require("@the-bds-maneger/fetchsync"); -const { external_ip, Interfaces } = require("../scripts/external_ip"); +const { external_ip, Interfaces } = require("../src/Scripts/external_ip"); const { GetTempHost } = require("./BdsSettings") if (GetTempHost()){ diff --git a/package.json b/package.json index d723cab..a878fdd 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "scripts": { "start": "node bin/bds_maneger.js -s", "stop": "node -p 'console.log(require(\"./\").kill());'", - "test": "exit 0", + "test": "node .Build/test/ci.js", + "ci": "node .Build/test/ci.js", "eslint": "eslint --debug .", "eslint:debug": "eslint --debug .", "eslint:fix": "eslint --fix .", diff --git a/rest/api.js b/rest/api.js deleted file mode 100644 index 439f75f..0000000 --- a/rest/api.js +++ /dev/null @@ -1,210 +0,0 @@ -const { readFileSync, existsSync } = require("fs"); -const { resolve } = require("path"); -const express = require("express"); -const bds = require("../index"); -const cors = require("cors"); -const rateLimit = require("express-rate-limit"); -const bodyParser = require("body-parser"); -const fileUpload = require("express-fileupload"); -const { GetKernel } = require("../lib/BdsSystemInfo"); -const commandExist = require("../lib/commandExist"); -const { GetPlatform, GetServerVersion, GetPaths, UpdatePlatform, bds_dir } = require("../lib/BdsSettings") -const admzip = require("adm-zip"); -const pretty = require("express-prettify"); -const latest_log = resolve(GetPaths("log"), "latest.log") -const docs = require("../BdsManegerInfo.json").docs; -const { CheckPlayer, token_verify } = require("../scripts/check"); - -function api(port_api = 1932){ - const app = express(); - // Enable if you"re behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc) - // see https://expressjs.com/en/guide/behind-proxies.html - // app.set("trust proxy", 1); - - app.use(cors()); - app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */ - app.use(bodyParser.urlencoded({ extended: true })); - app.use(rateLimit({windowMs: 15 * 60 * 1000, /* 15 minutes */ max: 100 /* limit each IP to 100 requests per windowMs*/ })); - app.use(pretty({always: true, spaces: 2})); - app.use(fileUpload({limits: { fileSize: 512 * 1024 }})); - app.use(require("request-ip").mw()); - - // Main - app.get("/", (req, res) => { - return res.send(` - -

Hello From Bds Maneger Core

- If this page has loaded it means that the API is working as planned, More information access the API documentation at: Bds Maneger Core. -

Bds Maneger core Version: ${bds.package_json.version}

-

GET

-

Basic Info server and System

-

Players who logged on to the server

-

POST

-

basic Services: Stop, start and restart

- -

by Sirherobrine23

- `); - }); - - app.post("/bds_command", (req, res) => { - const body = req.body; - var comand = body.command - const status = { - code: 401, - status: false - } - if (token_verify(body.token)) { - bds.command(comand) - status.code = 201 - status.status = true - } - res.status(status.code).send(status) - }); - - // Players info and maneger - app.get("/players", (req, res) => { - var { player, status, platform} = req.query; - const players_json = JSON.parse(readFileSync(bds.players_files, "utf8"))[(platform || GetPlatform())]; - var response = {}; - - if (player) { - if (players_json[player]) response = players_json[player]; - else response = { - date: null, - connected: null, - xboxID: null, - update: [{date: null, connected: null}] - } - return res.json(response); - } else if (status) { - status = (() => {if (status === "online" || status === "true") return true; else return false})() - for (let index of Object.getOwnPropertyNames(players_json)) if (players_json[index].connected === status) response[index] = players_json[index] - return res.json(response); - } - response = players_json - return res.json(response); - }); - - app.get("/players/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => { - const { TYPE, TOKEN, PLAYER } = req.params; - const { text } = req.query; - // Pre Check - if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters"); - - // Post Check - if (TYPE === "ban") res.json({ok: bds.command(`ban ${PLAYER}`)}); - else if (TYPE === "kick") res.json({ok: bds.command(`kick ${PLAYER} ${text}`)}); - else if (TYPE === "op") res.json({ok: bds.command(`op ${PLAYER}`)}); - else if (TYPE === "deop") res.json({ok: bds.command(`deop ${PLAYER}`)}); - else res.sendStatus(422) - }); - - // Actions Redirect - app.all("/players/actions/*", ({ res }) => res.redirect(`${docs.url}/${docs.rest_api}#players-actions`)) - app.all("/players/actions", ({ res }) => res.redirect(`${docs.url}/${docs.rest_api}#players-actions`)) - - // Backup - app.get("/backup", (req, res) => { - const { token } = req.query; - // Check Token - if (!(token_verify(token))) return res.status(401).send("Check your token"); - - // Return File - const backup = bds.backup() - return res.sendFile(backup.file_path) - }); - - // Server Sevices - app.all("/service", ({res}) => res.redirect(`${docs.url}/${docs.rest_api}#disable-basic-services`)); - - // bds maneger - app.post("/bds/download", (req, res) => { - const { token, version, platform } = req.body - if (!(token_verify(token))) return res.status(401).send("Check your token"); - - // Server Download - if (platform) UpdatePlatform(platform); - try { - bds.download(version, true, function(){ - return res.json({ - version: version, - platform: GetPlatform() - }) - }) - } catch (error) { - res.status(501).send("Unable to download server for current platform, more details will be in terminal log!") - } - }); - - app.post("/bds/upload", (req, res) => { - const { token } = req.headers; - if (!(token_verify(token))) return res.status(401).send("Check your token"); - if (!req.files || Object.keys(req.files).length === 0) return res.status(400).send("No files were uploaded."); - - // Extract - for (let index of Object.getOwnPropertyNames(req.files)){ - const fileWorld = req.files[index]; - const unzip = new admzip(Buffer.from(fileWorld.data)); - unzip.extractAllTo(bds_dir) - } - return res.send("Ok") - }); - - // System and Server info - app.get("/info", ({ res }) => res.redirect("bds/info")) - app.get("/bds/info", ({ res }) => { - const config = bds.get_config(); - var info = { - server: { - platform: GetPlatform(), - world_name: config.world, - running: bds.detect(), - port: config.portv4, - port6: config.portv6, - max_players: config.players, - whitelist: config.whitelist, - }, - sys: { - arch: bds.arch, - system: process.platform, - Kernel: GetKernel(), - IS_CLI: JSON.parse(process.env.IS_BDS_CLI || false), - IS_DOCKER: JSON.parse(process.env.BDS_DOCKER_IMAGE || false), - IS_NPX: (process.env.npm_lifecycle_event === "npx"), - QEMU_STATIC: commandExist("qemu-x86_64-static") - }, - bds_maneger_core: { - version: bds.package_json.version, - server_versions: GetServerVersion(), - } - }; - return res.send(info); - }); - - app.get("/log", (req, res) => { - if (!(existsSync(latest_log))) return res.sendStatus(400); - - let RequestConfig = {format: req.query.format, text: readFileSync(latest_log, "utf8").toString().split("\n").filter(d=>{if (d) return true;return false}).join("\n")} - if (RequestConfig.format === "html") { - var text = "" - for (let log of RequestConfig.text.split("\n")) text += `

${log}

`; - res.send(text); - } else res.json(RequestConfig.text.split("\n")); - }); - - app.all("*", (req, res)=>{ - res.status(400) - res.send(`
This request does not exist, more information
`) - }); - const port = (port_api||1932) - app.listen(port, function (){console.log(`Bds Maneger Core REST API, http port: ${port}`);}); - return true -} - -// module exports -module.exports = function (json_config = {api_port: 1932}){ - var port_rest; - if (json_config.api_port === undefined) port_rest = 1932; else port_rest = json_config.rest_port; - return api(port_rest) -} -module.exports.api = api diff --git a/scripts/CheckKill.js b/src/Scripts/CheckKill.js similarity index 100% rename from scripts/CheckKill.js rename to src/Scripts/CheckKill.js diff --git a/scripts/LoadCronBackup.js b/src/Scripts/LoadCronBackup.js similarity index 94% rename from scripts/LoadCronBackup.js rename to src/Scripts/LoadCronBackup.js index c2e5efd..95c6370 100644 --- a/scripts/LoadCronBackup.js +++ b/src/Scripts/LoadCronBackup.js @@ -1,5 +1,5 @@ const { CronJob } = require("cron"); -const { GetCronBackup } = require("../lib/BdsSettings"); +const { GetCronBackup } = require("../../lib/BdsSettings"); const { Backup } = require("./backups") const Cloud = { Azure: require("../clouds/Azure").Uploadbackups, diff --git a/scripts/PlayersSave.js b/src/Scripts/PlayersSave.js similarity index 98% rename from scripts/PlayersSave.js rename to src/Scripts/PlayersSave.js index fa62440..d8250fc 100644 --- a/scripts/PlayersSave.js +++ b/src/Scripts/PlayersSave.js @@ -1,6 +1,6 @@ -const bds = require("../index") +const bds = require("../../index") const { CheckBan } = require("./check"); -const { GetPlatform, GetPaths } = require("../lib/BdsSettings"); +const { GetPlatform, GetPaths } = require("../../lib/BdsSettings"); const fs = require("fs"); function MytypeKill(player) { diff --git a/scripts/ServerSettings.js b/src/Scripts/ServerSettings.js similarity index 99% rename from scripts/ServerSettings.js rename to src/Scripts/ServerSettings.js index 7ed5bf7..9b81d48 100644 --- a/scripts/ServerSettings.js +++ b/src/Scripts/ServerSettings.js @@ -2,7 +2,7 @@ var fs = require("fs"); const path = require("path"); const propertiesToJSON = require("properties-to-json"); const { join } = require("path"); -const { GetServerPaths, GetPlatform } = require("../lib/BdsSettings"); +const { GetServerPaths, GetPlatform } = require("../../lib/BdsSettings"); const bds_dir_bedrock = GetServerPaths("bedrock"), bds_dir_java = GetServerPaths("java"), bds_dir_pocketmine = GetServerPaths("pocketmine"); const bedrockCPUThread = require("os").cpus().length; diff --git a/scripts/backups.js b/src/Scripts/backups.js similarity index 96% rename from scripts/backups.js rename to src/Scripts/backups.js index 07aa807..c2cc038 100644 --- a/scripts/backups.js +++ b/src/Scripts/backups.js @@ -1,8 +1,8 @@ -const bds = require("../index") +const bds = require("../../index") const { join } = require("path"); const { readdirSync, existsSync, readFileSync } = require("fs") const AdmZip = require("adm-zip"); -const { GetServerPaths, GetPaths, bds_dir } = require("../lib/BdsSettings") +const { GetServerPaths, GetPaths, bds_dir } = require("../../lib/BdsSettings") function Backup() { const zip = new AdmZip(); diff --git a/scripts/basic_server.js b/src/Scripts/basic_server.js similarity index 98% rename from scripts/basic_server.js rename to src/Scripts/basic_server.js index e0097b5..71fc4a3 100644 --- a/scripts/basic_server.js +++ b/src/Scripts/basic_server.js @@ -2,10 +2,10 @@ const { exec, execFile } = require("child_process"); const fs = require("fs"); const path = require("path"); const { resolve, join } = require("path"); -const commandExists = require("../lib/commandExist"); +const commandExists = require("../../lib/commandExist"); const saveUser = require("./PlayersSave"); -const bds = require("../index"); -const { GetServerPaths, GetPaths, GetServerSettings, GetPlatform } = require("../lib/BdsSettings"); +const bds = require("../../index"); +const { GetServerPaths, GetPaths, GetServerSettings, GetPlatform } = require("../../lib/BdsSettings"); const BdsDetect = require("./CheckKill").Detect; const { randomUUID } = require("crypto"); const { warn } = console; diff --git a/scripts/check.js b/src/Scripts/check.js similarity index 96% rename from scripts/check.js rename to src/Scripts/check.js index 8f2b2c1..a1b0f76 100644 --- a/scripts/check.js +++ b/src/Scripts/check.js @@ -1,4 +1,4 @@ -const { bds_dir, GetServerBan, GetTelegramAdmins, GetPlatform, GetPaths } = require("../lib/BdsSettings"); +const { bds_dir, GetServerBan, GetTelegramAdmins, GetPlatform, GetPaths } = require("../../lib/BdsSettings"); const { existsSync, readFileSync } = require("fs") const { join } = require("path") diff --git a/scripts/download.js b/src/Scripts/download.js similarity index 96% rename from scripts/download.js rename to src/Scripts/download.js index 4bf129a..527d7e7 100644 --- a/scripts/download.js +++ b/src/Scripts/download.js @@ -1,12 +1,12 @@ var AdmZip = require("adm-zip"); const { writeFileSync, existsSync, readFileSync, readdirSync } = require("fs"); const { join, resolve } = require("path"); -const bds = require("../index") -const { valid_platform } = require("../lib/BdsSystemInfo"); -const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../lib/BdsSettings"); -const { GitClone } = require("../lib/git_simples"); +const bds = require("../../index") +const { valid_platform } = require("../../lib/BdsSystemInfo"); +const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../../lib/BdsSettings"); +const { GitClone } = require("../../lib/git_simples"); const { execSync } = require("child_process"); -const Extra = require("../BdsManegerInfo.json"); +const Extra = require("../../BdsManegerInfo.json"); const bds_dir_bedrock = GetServerPaths("bedrock"), diff --git a/scripts/external_ip.js b/src/Scripts/external_ip.js similarity index 100% rename from scripts/external_ip.js rename to src/Scripts/external_ip.js diff --git a/clouds/Auth/Google.js b/src/clouds/Auth/Google.js similarity index 97% rename from clouds/Auth/Google.js rename to src/clouds/Auth/Google.js index 7c9bb6c..2fad56f 100644 --- a/clouds/Auth/Google.js +++ b/src/clouds/Auth/Google.js @@ -1,14 +1,14 @@ const fs = require("fs"); const { join } = require("path") const { google } = require("googleapis"); -const { bds_dir } = require("../../lib/BdsSettings") +const { bds_dir } = require("../../../lib/BdsSettings") const express = require("express"); const app = express(); var cors = require("cors"); const rateLimit = require("express-rate-limit"); const bodyParser = require("body-parser"); const fetchSync = require("@the-bds-maneger/fetchsync"); -const Ips = require("../../scripts/external_ip") +const Ips = require("../../Scripts/external_ip"); const DefaultLoginDrive = { access_type: "offline", scope: [ diff --git a/clouds/Azure.js b/src/clouds/Azure.js similarity index 95% rename from clouds/Azure.js rename to src/clouds/Azure.js index d1ec573..4271a41 100644 --- a/clouds/Azure.js +++ b/src/clouds/Azure.js @@ -1,6 +1,6 @@ const { resolve } = require("path"); const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob"); -const NewBdsSettings = require("../lib/BdsSettings"); +const NewBdsSettings = require("../../lib/BdsSettings"); const Uploadbackups = async function (object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) { const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure"); const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey); diff --git a/clouds/GoogleDriver.js b/src/clouds/GoogleDriver.js similarity index 94% rename from clouds/GoogleDriver.js rename to src/clouds/GoogleDriver.js index 80a7f25..4227439 100644 --- a/clouds/GoogleDriver.js +++ b/src/clouds/GoogleDriver.js @@ -1,7 +1,7 @@ const fs = require("fs"); const { google } = require("googleapis"); const { authorize } = require("./Auth/Google"); -const { GetCloudConfig } = require("../lib/BdsSettings"); +const { GetCloudConfig } = require("../../lib/BdsSettings"); module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation = "Backup.zip", BackupCallback){ const parent_id = GetCloudConfig("Driver").RootID diff --git a/clouds/OracleCI.js b/src/clouds/OracleCI.js similarity index 96% rename from clouds/OracleCI.js rename to src/clouds/OracleCI.js index 383ffd1..37259b6 100644 --- a/clouds/OracleCI.js +++ b/src/clouds/OracleCI.js @@ -2,7 +2,7 @@ const oci_storage = require("oci-objectstorage"); const oci_common = require("oci-common"); const fs = require("fs"); const { resolve } = require("path"); -const { CloudConfig } = require("../lib/BdsSettings") +const { CloudConfig } = require("../../lib/BdsSettings"); const Uploadbackups = async function ( object = "Backup.zip", diff --git a/src/rest/api.js b/src/rest/api.js new file mode 100644 index 0000000..23829ee --- /dev/null +++ b/src/rest/api.js @@ -0,0 +1,69 @@ +const { readFileSync, existsSync } = require("fs"); +const { resolve } = require("path"); +const express = require("express"); +const cors = require("cors"); +const rateLimit = require("express-rate-limit"); +const bodyParser = require("body-parser"); +const fileUpload = require("express-fileupload"); +const { GetPaths } = require("../../lib/BdsSettings") +const pretty = require("express-prettify"); +const latest_log = resolve(GetPaths("log"), "latest.log") +const docs = require("../../BdsManegerInfo.json").docs; + +const app = express(); +// Enable if you"re behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc) +// see https://expressjs.com/en/guide/behind-proxies.html +// app.set("trust proxy", 1); + +app.use(cors()); +app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */ +app.use(bodyParser.urlencoded({ extended: true })); +app.use(rateLimit({windowMs: 15 * 60 * 1000, /* 15 minutes */ max: 100 /* limit each IP to 100 requests per windowMs*/ })); +app.use(pretty({always: true, spaces: 2})); +app.use(fileUpload({limits: { fileSize: 512 * 1024 }})); +app.use(require("request-ip").mw()); + +// Main +let Home = readFileSync(resolve(__dirname, "./html/Home.html"), "utf8").replace(/\{\{([^{^}]+)\}\}/g, (..._b) => eval(_b[1])); +app.get("/", (req, res) => res.send(Home)); + +// Bds route +app.use("/bds", require("./routes/bds")) +app.use("/players", require("./routes/players")) +app.post("/bds_command", ({res}) => res.redirect("/bds/command")) +app.get("/info", ({ res }) => res.redirect("bds/info")) + +// Server Sevices +app.all("/service", ({res}) => res.redirect(`${docs.url}/${docs.rest_api}#disable-basic-services`)); + +app.get("/log", (req, res) => { + if (!(existsSync(latest_log))) return res.sendStatus(400); + + let RequestConfig = {format: req.query.format, text: readFileSync(latest_log, "utf8").toString().split("\n").filter(d=>{if (d) return true;return false}).join("\n")} + if (RequestConfig.format === "html") { + var text = "" + for (let log of RequestConfig.text.split("\n")) text += `

${log}

`; + res.send(text); + } else res.json(RequestConfig.text.split("\n")); +}); + +app.all("*", (req, res)=>{ + res.status(404) + return res.send(`
This request does not exist, more information
`) +}); + + +// module exports +function api(port_api = 1932, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){ + const port = (port_api || 1932) + app.listen(port) + if (typeof callback === "function") callback(port); + return port; +} +module.exports = function (apiConfig = {api_port: 1932}, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){ + var port_rest = 1932; + if (typeof apiConfig == "object" && apiConfig.api_port !== undefined) port_rest = apiConfig.api_port; + else if (typeof apiConfig === "number") port_rest = apiConfig; + return api(port_rest, callback); +} +module.exports.api = api; diff --git a/src/rest/html/Home.html b/src/rest/html/Home.html new file mode 100644 index 0000000..b8b3d5f --- /dev/null +++ b/src/rest/html/Home.html @@ -0,0 +1,11 @@ + + +

Hello From Bds Maneger Core

+ If this page has loaded it means that the API is working as planned, More information access the API documentation at: Bds Maneger Core. +

Bds Maneger core Version: {{require("../../index").package_json.version}}

+

GET

+

Basic Info server and System

+

Players who logged on to the server

+ +

by Sirherobrine23

+ \ No newline at end of file diff --git a/src/rest/routes/bds.js b/src/rest/routes/bds.js new file mode 100644 index 0000000..7d1b19b --- /dev/null +++ b/src/rest/routes/bds.js @@ -0,0 +1,101 @@ +const express = require("express"); +const app = express.Router(); +const { GetKernel } = require("../../../lib/BdsSystemInfo"); +const commandExist = require("../../../lib/commandExist"); +const { GetPlatform, GetServerVersion, UpdatePlatform, bds_dir } = require("../../../lib/BdsSettings") +const admzip = require("adm-zip"); +const bds = require("../../../index"); +const { token_verify } = require("../../Scripts/check"); + +// Backup +app.get("/backup", (req, res) => { + const { token } = req.query; + // Check Token + if (!(token_verify(token))) return res.status(401).send("Check your token"); + + // Return File + const backup = bds.backup() + return res.sendFile(backup.file_path) +}); + + +// bds maneger +app.post("/download", (req, res) => { + const { token, version, platform } = req.body + if (!(token_verify(token))) return res.status(401).send("Check your token"); + + // Server Download + if (platform) UpdatePlatform(platform); + try { + bds.download(version, true, function(){ + return res.json({ + version: version, + platform: GetPlatform() + }) + }) + } catch (error) { + res.status(501).send("Unable to download server for current platform, more details will be in terminal log!") + } +}); + +app.post("/upload", (req, res) => { + const { token } = req.headers; + if (!(token_verify(token))) return res.status(401).send("Check your token"); + if (!req.files || Object.keys(req.files).length === 0) return res.status(400).send("No files were uploaded."); + + // Extract + for (let index of Object.getOwnPropertyNames(req.files)){ + const fileWorld = req.files[index]; + const unzip = new admzip(Buffer.from(fileWorld.data)); + unzip.extractAllTo(bds_dir) + } + return res.send("Ok") +}); + +// Command +app.post("/command", (req, res) => { + const body = req.body; + var comand = body.command + const status = { + code: 401, + status: false + } + if (token_verify(body.token)) { + bds.command(comand) + status.code = 201 + status.status = true + } + res.status(status.code).send(status) +}); + +// System and Server info +app.get("/info", ({ res }) => { + const config = bds.get_config(); + var info = { + server: { + platform: GetPlatform(), + world_name: config.world, + running: bds.detect(), + port: config.portv4, + port6: config.portv6, + max_players: config.players, + whitelist: config.whitelist, + }, + sys: { + arch: bds.arch, + system: process.platform, + Kernel: GetKernel(), + IS_CLI: JSON.parse(process.env.IS_BDS_CLI || false), + IS_DOCKER: JSON.parse(process.env.BDS_DOCKER_IMAGE || false), + IS_NPX: (process.env.npm_lifecycle_event === "npx"), + QEMU_STATIC: commandExist("qemu-x86_64-static") + }, + bds_maneger_core: { + version: bds.package_json.version, + server_versions: GetServerVersion(), + } + }; + return res.send(info); +}); + +module.exports = app; \ No newline at end of file diff --git a/src/rest/routes/players.js b/src/rest/routes/players.js new file mode 100644 index 0000000..83d71cf --- /dev/null +++ b/src/rest/routes/players.js @@ -0,0 +1,51 @@ +const express = require("express"); +const app = express.Router(); +const { GetPlatform } = require("../../../lib/BdsSettings") +const bds = require("../../../index"); +const { token_verify, CheckPlayer } = require("../../Scripts/check"); +const { readFileSync } = require("fs"); +const docs = require("../../../BdsManegerInfo.json").docs; + +// Players info and maneger +app.get("/", (req, res) => { + var { player, status, platform} = req.query; + const players_json = JSON.parse(readFileSync(bds.players_files, "utf8"))[(platform || GetPlatform())]; + var response = {}; + + if (player) { + if (players_json[player]) response = players_json[player]; + else response = { + date: null, + connected: null, + xboxID: null, + update: [{date: null, connected: null}] + } + return res.json(response); + } else if (status) { + status = (() => {if (status === "online" || status === "true") return true; else return false})() + for (let index of Object.getOwnPropertyNames(players_json)) if (players_json[index].connected === status) response[index] = players_json[index] + return res.json(response); + } + response = players_json + return res.json(response); +}); + +app.get("/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => { + const { TYPE, TOKEN, PLAYER } = req.params; + const { text } = req.query; + // Pre Check + if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters"); + + // Post Check + if (TYPE === "ban") res.json({ok: bds.command(`ban ${PLAYER}`)}); + else if (TYPE === "kick") res.json({ok: bds.command(`kick ${PLAYER} ${text}`)}); + else if (TYPE === "op") res.json({ok: bds.command(`op ${PLAYER}`)}); + else if (TYPE === "deop") res.json({ok: bds.command(`deop ${PLAYER}`)}); + else res.sendStatus(422) +}); + +// Actions Redirect +app.all("/actions/*", ({ res }) => res.send(`${docs.url}/${docs.rest_api}#players-actions`)) +app.all("/*", ({ res }) => res.send(`${docs.url}/${docs.rest_api}#players-actions`)) + +module.exports = app; \ No newline at end of file -- 2.49.0 From ad77737a4553401df8466e401a188a6f05cf939a Mon Sep 17 00:00:00 2001 From: Matheus sampaio Queiroga Date: Mon, 19 Jul 2021 16:44:09 -0300 Subject: [PATCH 2/3] Push --- bin/bds_maneger.js | 18 ++++++++++++----- bin/telegram_bot.js | 6 +++--- lib/BdsSettings.js | 3 ++- src/Scripts/backups.js | 46 +++++++++++++++--------------------------- 4 files changed, 34 insertions(+), 39 deletions(-) diff --git a/bin/bds_maneger.js b/bin/bds_maneger.js index 9fcf6a6..36b2081 100755 --- a/bin/bds_maneger.js +++ b/bin/bds_maneger.js @@ -1,10 +1,10 @@ #!/usr/bin/env node if (process.platform === "win32") process.title = "Bds Maneger CLI";else process.title = "Bds_Manger_CLI" const readline = require("readline"); -const bds = require("../../index"); -const { valid_platform } = require("../../lib/BdsSystemInfo"); -const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../../lib/BdsSettings"); -const commandExits = require("../../lib/commandExist"); +const bds = require("../index"); +const { valid_platform } = require("../lib/BdsSystemInfo"); +const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings"); +const commandExits = require("../lib/commandExist"); const download = require("../src/Scripts/download"); process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true; // Bds Maneger ArgV @@ -12,7 +12,15 @@ const argv = require("minimist")(process.argv.slice(2)); if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true // Options -const server = (argv.p || argv.platform), version = (argv.v || argv.version), SystemCheck = (argv.S || argv.system_info), bds_version = (argv.d || argv.server_download), start = (argv.s || argv.server_version), help = (argv.h || argv.help), kill = (argv.k || argv.kill), docker_runner = (argv.DOCKER_IMAGE) +const + server = (argv.p || argv.platform), + version = (argv.v || argv.version), + SystemCheck = (argv.S || argv.system_info), + bds_version = (argv.d || argv.server_download), + start = (argv.s || argv.server_version), + help = (argv.h || argv.help), + kill = (argv.k || argv.kill), + docker_runner = (argv.DOCKER_IMAGE); // -------------------------- const Versions = GetServerVersion(); diff --git a/bin/telegram_bot.js b/bin/telegram_bot.js index fd297df..3da9b4a 100644 --- a/bin/telegram_bot.js +++ b/bin/telegram_bot.js @@ -1,9 +1,9 @@ const { Telegraf } = require("telegraf"); const fs = require("fs"); const path = require("path"); -const bds = require("../../index"); -const { GetPlatform, GetPaths } = require("../../lib/BdsSettings"); -const { GetKernel, arch, system } = require("../../lib/BdsSystemInfo"); +const bds = require("../index"); +const { GetPlatform, GetPaths } = require("../lib/BdsSettings"); +const { GetKernel, arch, system } = require("../lib/BdsSystemInfo"); const { Detect } = require("../src/Scripts/CheckKill"); const TelegramOptions = require("minimist")(process.argv.slice(2)); diff --git a/lib/BdsSettings.js b/lib/BdsSettings.js index d5dc267..3fbf07e 100644 --- a/lib/BdsSettings.js +++ b/lib/BdsSettings.js @@ -154,7 +154,8 @@ module.exports = { GetJsonConfig: function(){return Config}, GetPaths: function(path = null){ if (!(path)) throw new Error("Set path to get"); - if (!(Config.paths[path])) throw new Error("Put a valid path: " + Object.getOwnPropertyNames(Config.paths).join(", ")); + if (!(path === "all" || Config.paths[path])) throw new Error("Put a valid path: " + Object.getOwnPropertyNames(Config.paths).join(", ")); + if (path === "all") return Config.paths return Config.paths[path] }, GetServerPaths: function(path = null){ diff --git a/src/Scripts/backups.js b/src/Scripts/backups.js index c2cc038..5c6be49 100644 --- a/src/Scripts/backups.js +++ b/src/Scripts/backups.js @@ -1,6 +1,6 @@ const bds = require("../../index") -const { join } = require("path"); -const { readdirSync, existsSync, readFileSync } = require("fs") +const { join, resolve } = require("path"); +const { readdirSync, existsSync, readFileSync, statSync } = require("fs") const AdmZip = require("adm-zip"); const { GetServerPaths, GetPaths, bds_dir } = require("../../lib/BdsSettings") @@ -18,49 +18,35 @@ function Backup() { const PathBackup = join(GetPaths("backups"), name); // Bedrock - if (existsSync(join(Paths.bedrock, (() => {if (process.platform === "win32") return "bedrock_server.exe";else if (process.platform === "linux") return "bedrock_server";})()))) { - zip.addLocalFolder(join(Paths.bedrock, "worlds"), join("Servers", "bedrock", "worlds")); - for (let index of [ - "server.properties", - "permissions.json", - "whitelist.json" - ]) if (existsSync(join(Paths.bedrock, index))) zip.addLocalFile(join(Paths.bedrock, index), join("Servers", "bedrock")); + if (readdirSync(Paths.bedrock).filter(a=>/worlds/.test(a)).length >= 1) { + zip.addLocalFolder(join(Paths.bedrock, "worlds"), join("Servers", "Bedrock", "worlds")); + for (let index of ["server.properties", "permissions.json", "whitelist.json"]) {if (existsSync(join(Paths.bedrock, index))) zip.addLocalFile(join(Paths.bedrock, index), join("Servers", "Bedrock"));} } else console.info("Skipping the bedrock as it was not installed"); // Java if (existsSync(join(Paths.java, "MinecraftServerJava.jar"))) { - let javaDir = readdirSync(Paths.java).filter(function(value) {if (value === "banned-ips.json" || value === "banned-players.json" || value === "eula.txt" || value === "logs" || value === "ops.json" || value === "server.jar" || value === "MinecraftServerJava.jar" || value === "server.properties" || value === "usercache.json" || value === "whitelist.json") return false;return true}); - for (let index of javaDir) zip.addLocalFolder(join(Paths.java, index), join("Servers", "java", index)) - for (let index of [ - "banned-ips.json", - "banned-players.json", - "ops.json", - "server.properties", - "whitelist.json" - ]) if (existsSync(join(Paths.java, index))) zip.addLocalFile(join(Paths.java, index), join("Servers", "java")); + for (let index of readdirSync(Paths.java).filter(value => !/banned-ips.json|banned-players.json|eula.txt|logs|ops.json|server.jar|MinecraftServerJava.jar|server.properties|usercache.json|whitelist.json/.test(value))) zip.addLocalFolder(join(Paths.java, index), join("Servers", "Java", index)); + for (let index of ["banned-ips.json", "banned-players.json", "ops.json", "server.properties", "whitelist.json"]) {if (existsSync(join(Paths.java, index))) zip.addLocalFile(join(Paths.java, index), join("Servers", "Java"))} } else console.info("Skipping the java as it was not installed"); // PocketMine if (existsSync(join(Paths.pocketmine, "PocketMine-MP.phar"))) { if (existsSync(join(Paths.pocketmine, "worlds"))) zip.addLocalFolder(join(Paths.pocketmine, "worlds"), join("Servers", "pocketmine", "worlds")); - for (let index of [ - "pocketmine.yml", - "server.properties", - "white-list.txt", - "ops.txt", - "banned-players.txt", - "banned-ips.txt" - ]) if (existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine"); + for (let index of ["pocketmine.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine"); } else console.info("Skipping the pocketmine as it was not installed"); // JSPrismarine // The Bds Maneger Core Backup - for (let index of [ - "BdsConfig.yaml", - "bds_tokens.json" - ]) if (existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index)); + for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index)); + + for (let index of Object.getOwnPropertyNames(GetPaths("all")).filter(path => !/servers|backups/.test(path)).map(name => GetPaths(name))) { + if (existsSync(index)) { + const _S = statSync(resolve(index)); + if (_S.isFile() || _S.isSymbolicLink()) zip.addLocalFile(index); else zip.addLocalFolder(index) + } + } zip.addZipComment("Settings and World Backups, by The Bds Maneger Project©"); zip.writeZip(PathBackup); -- 2.49.0 From 158952aca9e838c762b5dd5b062650b9794227fb Mon Sep 17 00:00:00 2001 From: Matheus sampaio Queiroga Date: Mon, 19 Jul 2021 17:20:32 -0300 Subject: [PATCH 3/3] Fix bds_maneger.js --- bin/bds_maneger.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/bds_maneger.js b/bin/bds_maneger.js index 36b2081..5fb8004 100755 --- a/bin/bds_maneger.js +++ b/bin/bds_maneger.js @@ -32,7 +32,7 @@ if (kill) bds.kill(); if (server) UpdatePlatform(server); function StartServer(){ - const { Servers } = require("../../lib/ServerURL"); + const { Servers } = require("../lib/ServerURL"); // Check Server Update if (Versions[GetPlatform()] !== null) { if (Versions[GetPlatform()] !== Servers.latest[GetPlatform()]) { @@ -169,7 +169,7 @@ if (bds_version){ try { if (argv.interactive) { console.log(`Geting versions to ${GetPlatform()}`); - const LoadVersion = require("../../lib/ServerURL").Servers[GetPlatform()] + const LoadVersion = require("../lib/ServerURL").Servers[GetPlatform()] const Version = Object.getOwnPropertyNames(LoadVersion) // List Version for (let version in Version) console.log(`${version}: ${GetPlatform()} version ${Version[version]}`); // deepscan-disable-line FORIN_ARRAY -- 2.49.0