From 7a2be7eb4fb7be2bedda0bd922e641e25eeba690 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Thu, 12 Aug 2021 20:22:37 -0300 Subject: [PATCH 01/11] Binary and Command fix duplicate log --- bin/bds_maneger.js | 12 +-- index.js | 22 ------ lib/BdsSettings.js | 1 + src/BdsBackup.js | 4 +- src/BdsManegerServer.js | 147 ++++++++++++++++++------------------- src/rest/routes/players.js | 17 +++-- 6 files changed, 93 insertions(+), 110 deletions(-) diff --git a/bin/bds_maneger.js b/bin/bds_maneger.js index 723dadb..7319769 100755 --- a/bin/bds_maneger.js +++ b/bin/bds_maneger.js @@ -54,8 +54,12 @@ function StartServer(){ console.log("Send a \"@stop\" command to stop the server and exit\nUse CTRL + C to force exit\n"); // Start Server const bds_server = bds.start(); - bds_server.log(echo) - bds_server.exit(function (code){if (code === 3221225781) return open("https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll");console.log("leaving the server, status code: ", code);process.exit(code)}); + bds_server.log(data => process.stdout.write(data)); + bds_server.exit(function (code){ + if (code === 3221225781 && process.platform === "win32") return open("https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll"); + console.log("leaving the server, status code:", code); + process.exit(code) + }); // CLI Commands const rl = readline.createInterface({input: process.stdin,output: process.stdout}); @@ -207,8 +211,4 @@ if (bds_version){ } // Start server -function echo(data = ""){ - data = data.split("\n").filter(data => {return (data !== "")}) - data.forEach(data => console.log(data)) -} if (start && !(server || version || SystemCheck || bds_version || help)) StartServer(); diff --git a/index.js b/index.js index 29f8271..0555a4a 100644 --- a/index.js +++ b/index.js @@ -7,23 +7,6 @@ const { bds_dir } = require("./lib/BdsSettings"); if (typeof fetch === "undefined") global.fetch = require("node-fetch"); -function date(format) { - const today = new Date(), - yaer = today.getFullYear(), - day = String(today.getDate()).padStart(2, "0"), - month = String(today.getMonth() + 1).padStart(2, "0"), - hour = today.getHours(), - minute = today.getMinutes(); - // --------------------------------------------------------- - if (format === "year") return yaer - else if (format === "day") return day - else if (format === "month") return month - else if (format === "hour") return hour - else if (format === "minute") return minute - else if (format === "hour_minu") return `${hour}-${minute}` - else return `${day}-${month}-${yaer}_${hour}-${minute}` -} - const bds_core_package = resolve(__dirname, "package.json") module.exports.package_path = bds_core_package module.exports.package_json = require("./package.json"); @@ -104,11 +87,6 @@ const { config, get_config } = require("./src/ServerSettings"); const download = require("./src/BdsServersDownload"); const { start, stop, BdsCommand, CronBackups } = require("./src/BdsManegerServer") -/** - * Take the current date - */ -module.exports.BdsDate = module.exports.date = date - /** * sending commands more simply to the server * diff --git a/lib/BdsSettings.js b/lib/BdsSettings.js index 7db3a6d..77e95f9 100644 --- a/lib/BdsSettings.js +++ b/lib/BdsSettings.js @@ -46,6 +46,7 @@ var Config = { java: null, pocketmine: null, jsprismarine: null, + spigot: null, }, Settings: { java: { diff --git a/src/BdsBackup.js b/src/BdsBackup.js index 213d677..aad848a 100644 --- a/src/BdsBackup.js +++ b/src/BdsBackup.js @@ -1,4 +1,3 @@ -const bds = require("../index") const { join, resolve } = require("path"); const { readdirSync, existsSync, readFileSync, statSync } = require("fs") const AdmZip = require("adm-zip"); @@ -14,7 +13,8 @@ function Backup() { pocketmine: GetServerPaths("pocketmine"), jsprismarine: GetServerPaths("jsprismarine") } - const name = `Bds_Maneger-Backups_${bds.date()}.zip` + const CurrentDate = new Date(); + const name = `Bds_Maneger_Core_Backups_${CurrentDate.getDate()}-${CurrentDate.getMonth()}-${CurrentDate.getFullYear()}.zip` const PathBackup = join(GetPaths("backups"), name); // Bedrock diff --git a/src/BdsManegerServer.js b/src/BdsManegerServer.js index f627923..b074629 100644 --- a/src/BdsManegerServer.js +++ b/src/BdsManegerServer.js @@ -101,8 +101,7 @@ function start() { } // Log file - - const LogFile = join(GetPaths("log"), `${bds.date()}_${GetPlatform()}_Bds_log.log`); + const LogFile = join(GetPaths("log"), `${GetPlatform()}_${new Date().toString()}_Bds_log.log`); const LatestLog_Path = path.join(GetPaths("log"), "latest.log"); const LogSaveFunction = data => { fs.appendFileSync(LogFile, data); @@ -123,81 +122,80 @@ function start() { global.bds_log_string = "" ServerExec.stdout.on("data", data => {if (global.bds_log_string) global.bds_log_string = data; else global.bds_log_string += data}); + // sets bds core commands + const command = async function (command = "list", callback = function (){}) { + return new Promise((resolve) => { + ServerExec.stdin.write(`${command}\n`); + if (typeof callback === "function") { + const TempLog = [] + const ControlTempHost = data => {TempLog.push(data); return data;} + ServerExec.stdout.on("data", data => ControlTempHost(data)); + ServerExec.stderr.on("data", data => ControlTempHost(data)); + setTimeout(() => { + callback(TempLog.join("\n")); + resolve(TempLog.join("\n")); + }, 2500); + } + }); + }; + const log = function (logCallback = data => process.stdout.write(data)){ + if (typeof logCallback !== "function") throw new Error("Log Callback is not a function"); + ServerExec.stdout.on("data", data => logCallback(data)); + ServerExec.stderr.on("data", data => logCallback(data)); + }; + const exit = function (exitCallback = process.exit){if ( + typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code)); + }; + const on = function(action = String, callback = Function) { + if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect"); + + // Functions + const data = data => Player_Json(data, function (array_status){ + for (let _player of array_status) { + if (action === "all") callback(_player); + else if (_player.Action === action) callback(_player) + } + }); + ServerExec.stdout.on("data", data); + ServerExec.stderr.on("data", data); + }; + const stop = function (){ + ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n"); + return BdsInfo.Servers[GetPlatform()].stop; + }; + const op = function (player = "Steve") { + let command = BdsInfo.Servers[GetPlatform()].op.replace("{{Player}}", player); + ServerExec.stdin.write(command+"\n"); + return command; + }; + const deop = function (player = "Steve") { + let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player); + ServerExec.stdin.write(command+"\n"); + return command; + }; + const ban = function (player = "Steve") { + let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player); + ServerExec.stdin.write(command+"\n"); + return command; + }; + const kick = function (player = "Steve", text = "you got kicked") { + let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text); + ServerExec.stdin.write(command+"\n"); + return command; + }; + const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) { + let command = BdsInfo.Servers[GetPlatform()].tp.replace("{{Player}}", player); + if (cord.x) command = command.replace("{{X}}", cord.x); else command = command.replace("{{X}}", 0); + if (cord.y) command = command.replace("{{Y}}", cord.y); else command = command.replace("{{Y}}", 128); + if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0); + ServerExec.stdin.write(command+"\n"); + return command; + }; const returnFuntion = { uuid: randomUUID(), - stop: function (){ - ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n"); - return BdsInfo.Servers[GetPlatform()].stop; - }, - command: async function (command = "list", callback = data => console.log(data)){ - return new Promise((resolve) => { - ServerExec.stdin.write(`${command}\n`); - if (typeof callback === "function") { - const TempLog = [] - const ControlTempHost = data => {TempLog.push(data); return data;} - ServerExec.stdout.on("data", data => ControlTempHost(data)); - ServerExec.stderr.on("data", data => ControlTempHost(data)); - setTimeout(() => { - callback(TempLog.join("\n")); - resolve(TempLog.join("\n")); - }, 2500); - } - }); - }, - log: function (logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}){ - if (typeof logCallback !== "function") { - console.warn("The log callback is not a function using console.log"); - logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))} - } - ServerExec.stdout.on("data", data => logCallback(data)); - ServerExec.stderr.on("data", data => logCallback(data)); - }, - exit: function (exitCallback = process.exit){if ( - typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code)); - }, - on: function(action = String(), callback = Function) { - if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect"); - - // Functions - const data = data => Player_Json(data, function (array_status){ - for (let _player of array_status) { - if (action === "all") callback(_player); - else if (_player.Action === action) callback(_player) - } - }); - ServerExec.stdout.on("data", data); - ServerExec.stderr.on("data", data); - }, - op: function (player = "Steve") { - let command = BdsInfo.Servers[GetPlatform()].op.replace("{{Player}}", player); - ServerExec.stdin.write(command+"\n"); - return command; - }, - deop: function (player = "Steve") { - let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player); - ServerExec.stdin.write(command+"\n"); - return command; - }, - ban: function (player = "Steve") { - let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player); - ServerExec.stdin.write(command+"\n"); - return command; - }, - kick: function (player = "Steve", text = "you got kicked") { - let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text); - ServerExec.stdin.write(command+"\n"); - return command; - }, - tp: function (player = "Steve", cord = {x: 0, y: 128, z: 0}) { - let command = BdsInfo.Servers[GetPlatform()].tp.replace("{{Player}}", player); - if (cord.x) command = command.replace("{{X}}", cord.x); else command = command.replace("{{X}}", 0); - if (cord.y) command = command.replace("{{Y}}", cord.y); else command = command.replace("{{Y}}", 128); - if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0); - ServerExec.stdin.write(command+"\n"); - return command; - } + command, log, exit, on, stop, op, deop, ban, kick, tp } - ServerExec.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]}); + ServerExec.on("exit", () => delete global.BdsExecs[returnFuntion.uuid]); global.BdsExecs[returnFuntion.uuid] = returnFuntion; return returnFuntion; } @@ -347,6 +345,7 @@ module.exports = { start, BdsCommand, stop, + GetSessions, CronBackups: CurrentBackups, Player_Search, } diff --git a/src/rest/routes/players.js b/src/rest/routes/players.js index 45ae281..5323c53 100644 --- a/src/rest/routes/players.js +++ b/src/rest/routes/players.js @@ -5,6 +5,7 @@ const bds = require("../../../index"); const { token_verify, CheckPlayer } = require("../../UsersAndtokenChecks"); const { readFileSync } = require("fs"); const docs = require("../../../BdsManegerInfo.json").docs; +const { GetSessions } = require("../../BdsManegerServer"); // Players info and maneger app.get("/", (req, res) => { @@ -35,13 +36,17 @@ app.get("/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => { const { text } = req.query; // Pre Check if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters"); - + const bds = GetSessions() // 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) + if (TYPE === "ban") res.json({ + ok: bds.ban(PLAYER) + }); else if (TYPE === "kick") res.json({ + ok: bds.kick(PLAYER, text) + }); else if (TYPE === "op") res.json({ + ok: bds.op(PLAYER) + }); else if (TYPE === "deop") res.json({ + ok: bds.deop(PLAYER) + }); else res.sendStatus(422); }); // Actions Redirect -- 2.47.2 From a08b1322f32435b5f3f8ce1d268dc719c5ae99a6 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Fri, 13 Aug 2021 20:36:41 -0300 Subject: [PATCH 02/11] CU --- .Build/test/ci.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.Build/test/ci.js b/.Build/test/ci.js index 7a18fbd..8333556 100644 --- a/.Build/test/ci.js +++ b/.Build/test/ci.js @@ -1,8 +1,7 @@ (async ()=>{ try { const bds = require("../../index"); - await bds.download("latest", true) - console.log("Date:", await bds.BdsDate()); + await bds.download("latest", true); console.log("Api:", await bds.api()); console.log("Backup:", await bds.backup()); console.log("Detect Server:", await bds.detect()); -- 2.47.2 From f14faf2e5e7a79ee38a25a6e47953337241e5257 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Fri, 13 Aug 2021 20:39:04 -0300 Subject: [PATCH 03/11] Update ci.js --- .Build/test/ci.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.Build/test/ci.js b/.Build/test/ci.js index 7a18fbd..8cd01ac 100644 --- a/.Build/test/ci.js +++ b/.Build/test/ci.js @@ -1,8 +1,7 @@ (async ()=>{ try { const bds = require("../../index"); - await bds.download("latest", true) - console.log("Date:", await bds.BdsDate()); + await bds.download("latest", true); console.log("Api:", await bds.api()); console.log("Backup:", await bds.backup()); console.log("Detect Server:", await bds.detect()); @@ -19,4 +18,4 @@ console.log("Detect Error:", err); process.exit(1) } -})() \ No newline at end of file +})() -- 2.47.2 From 5776479eba07aa3c636799493b3207525d7b001d Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sat, 14 Aug 2021 10:18:56 -0300 Subject: [PATCH 04/11] Android remove Java default false verification --- lib/BdsSystemInfo.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/BdsSystemInfo.js b/lib/BdsSystemInfo.js index 9d1b747..cc75fb3 100644 --- a/lib/BdsSystemInfo.js +++ b/lib/BdsSystemInfo.js @@ -49,7 +49,6 @@ if (process.platform == "win32") { } else if (process.platform === "android") { system = "Android"; valid_platform["bedrock"] = false - valid_platform["java"] = false } else { console.log(`The Bds Maneger Core does not support ${process.platform} systems, as no tests have been done.`); system = "Other"; @@ -112,4 +111,4 @@ function GetKernel() { module.exports.valid_platform = valid_platform module.exports.require_qemu = require_qemu module.exports.system = system -module.exports.GetKernel = GetKernel; \ No newline at end of file +module.exports.GetKernel = GetKernel; -- 2.47.2 From 5d86a26c8e1676600545ee18ca27a463922e93e9 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 08:55:53 -0300 Subject: [PATCH 05/11] Update package_test.yml --- .github/workflows/package_test.yml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/package_test.yml b/.github/workflows/package_test.yml index 7e45239..2a654ea 100644 --- a/.github/workflows/package_test.yml +++ b/.github/workflows/package_test.yml @@ -1,5 +1,5 @@ name: Test - The Bds Maneger Core -on: [push, pull_request] +on: [pull_request] jobs: Test: @@ -16,3 +16,22 @@ jobs: cache: 'npm' - run: npm install -d --no-save - run: npm test + + Test_Docker: + runs-on: ubuntu-latest + steps: + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: checkout + uses: actions/checkout@master + + - name: Build Docker Image + uses: docker/build-push-action@v2 + with: + target: bdscore + tags: coretest:latest + platforms: linux/amd64,linux/arm64,linux/arm/v7 -- 2.47.2 From 9e93bbbc92c3921c8ecf2d3ae8b1fd67c2f425a0 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 09:01:44 -0300 Subject: [PATCH 06/11] add path. in line 102 --- src/BdsManegerServer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BdsManegerServer.js b/src/BdsManegerServer.js index 56194e5..f6d8668 100644 --- a/src/BdsManegerServer.js +++ b/src/BdsManegerServer.js @@ -99,7 +99,7 @@ function start() { } // Log file - const LogFile = join(GetPaths("log"), `${GetPlatform()}_${new Date().toString()}_Bds_log.log`); + const LogFile = path.join(GetPaths("log"), `${GetPlatform()}_${new Date().toString()}_Bds_log.log`); const LatestLog_Path = path.join(GetPaths("log"), "latest.log"); const LogSaveFunction = data => { fs.appendFileSync(LogFile, data); -- 2.47.2 From 81a55636745ff9645c896e3676778f7062e08d22 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 09:15:57 -0300 Subject: [PATCH 07/11] Add package libatomic1 and moved npm update after installed libs --- .Build/Docker/Configure.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.Build/Docker/Configure.sh b/.Build/Docker/Configure.sh index 13c5276..4114a66 100644 --- a/.Build/Docker/Configure.sh +++ b/.Build/Docker/Configure.sh @@ -23,12 +23,12 @@ tar -xJf /tmp/node.tar.xz -C /tmp/Node rm -rf /tmp/node.tar.xz cp -rfv /tmp/Node/*/* /usr +# Install Build Dependencies and others Packages +apt install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libatomic1 libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev + # Update npm npm -g install npm@$(curl -sL https://api.github.com/repos/npm/cli/releases/latest | grep tag_name | cut -d '"' -f 4) -# Install Build Dependencies and others Packages -apt install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev - # Install Dependencies to diferent architectures if ! [ "$(uname -m)" == "x86_64" ];then mkdir -p /lib64 -- 2.47.2 From 3827b0cad4fe387dc582e8d6cbfab59a2a958b42 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 10:20:21 -0300 Subject: [PATCH 08/11] Quiet mode apt and copy nodejs --- .Build/Docker/Configure.sh | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.Build/Docker/Configure.sh b/.Build/Docker/Configure.sh index 4114a66..6aaacda 100644 --- a/.Build/Docker/Configure.sh +++ b/.Build/Docker/Configure.sh @@ -4,7 +4,7 @@ set -ex apt update # Install Necessary Packages -apt install -y curl wget git zsh sudo unzip zip jq python python3 screen +apt -qq install -y curl wget git zsh sudo unzip zip jq python python3 screen # Install nodejs from github release get_current_node_version=$(curl -sL https://api.github.com/repos/nodejs/node/releases/latest | grep tag_name | cut -d '"' -f 4) @@ -21,10 +21,10 @@ esac mkdir /tmp/Node tar -xJf /tmp/node.tar.xz -C /tmp/Node rm -rf /tmp/node.tar.xz -cp -rfv /tmp/Node/*/* /usr +cp -rf /tmp/Node/*/* /usr # Install Build Dependencies and others Packages -apt install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libatomic1 libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev +apt -qq install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libatomic1 libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev # Update npm npm -g install npm@$(curl -sL https://api.github.com/repos/npm/cli/releases/latest | grep tag_name | cut -d '"' -f 4) @@ -39,16 +39,17 @@ if ! [ "$(uname -m)" == "x86_64" ];then fi # Install openjdk -case "$(uname -m)" in - x86_64 | aarch64 ) apt install -y openjdk-17*;; - * ) apt install -y openjdk-11*;; +case `apt search openjdk` in + *openjdk-17* ) apt install -y openjdk-17*;; + *openjdk-11* ) apt install -y openjdk-11*;; + * ) echo "No openjdk version found, skipping";; esac # Setup non root user useradd -m -p "$(perl -e 'print crypt($ARGV[0], "password")' "LucaA1113ba21")" "thebds" addgroup thebds sudo addgroup thebds root -usermod --shell /bin/bash thebds; +usermod --shell /usr/bin/zsh thebds; echo "thebds ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers # Remove Unnecessary Packages -- 2.47.2 From 49599c25a612c5e272d7e7491a17b0d6cbcc4984 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 11:22:25 -0300 Subject: [PATCH 09/11] Update Configure.sh --- .Build/Docker/Configure.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.Build/Docker/Configure.sh b/.Build/Docker/Configure.sh index 6aaacda..c7e2e4b 100644 --- a/.Build/Docker/Configure.sh +++ b/.Build/Docker/Configure.sh @@ -39,7 +39,7 @@ if ! [ "$(uname -m)" == "x86_64" ];then fi # Install openjdk -case `apt search openjdk` in +case "$(apt search openjdk)" in *openjdk-17* ) apt install -y openjdk-17*;; *openjdk-11* ) apt install -y openjdk-11*;; * ) echo "No openjdk version found, skipping";; -- 2.47.2 From 72508658275e876a8a839313e500d31deb415583 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Sun, 15 Aug 2021 22:29:00 -0300 Subject: [PATCH 10/11] Move Azure Conatiner deploy and remove JSPrismarine modifications to Github Actions Modifications in nexe build file Add Docker.js to Docker image modifications in ignores files --- .Build/nexe_build.js | 19 +- .github/workflows/Base.yml | 42 ----- .github/workflows/main.yml | 67 +++++-- .github/workflows/package_test.yml | 23 ++- .github/workflows/rc.yml | 50 ------ .github/workflows/tag_version.yml | 43 ++++- .gitignore | 27 ++- .gitlab/.gitlab-webide.yml | 2 +- .gitlab/workflows/Nightly.yml | 21 --- .gitlab/workflows/Stable.yml | 8 +- .npmignore | 33 ++-- Docker/AzureContainerDeploy.json | 201 --------------------- bin/Docker.js | 100 +++++++++++ bin/bds_maneger.js | 41 +++-- index.js | 18 +- lib/BdsSettings.js | 78 ++++---- lib/BdsSystemInfo.js | 103 +++++------ src/BdsBackup.js | 3 - src/BdsManegerServer.js | 14 +- src/BdsServersDownload.js | 279 ++++++++++++++++------------- src/CheckKill.js | 5 - src/rest/routes/bds.js | 4 +- 22 files changed, 516 insertions(+), 665 deletions(-) delete mode 100644 .github/workflows/Base.yml delete mode 100644 .github/workflows/rc.yml delete mode 100644 .gitlab/workflows/Nightly.yml delete mode 100644 Docker/AzureContainerDeploy.json create mode 100644 bin/Docker.js diff --git a/.Build/nexe_build.js b/.Build/nexe_build.js index dea4aa7..1054506 100755 --- a/.Build/nexe_build.js +++ b/.Build/nexe_build.js @@ -50,15 +50,14 @@ if (options.system || options.S) { } // nexe options -var files = readdirSync(resolve(__dirname, "..")).filter(retu => {if (/[Dd]ocker*.js/gi.test(retu) || retu.includes("docker_config.json", ".log")) return false; else if (retu.includes(".js")) return true; else if (retu === "rest" || retu === "scripts") return true; else return false;}); -const nexeCopiler = { - name: "Bds Maneger Core", - build: true, - // loglevel: "verbose", - input: resolve(__dirname, "bds_maneger.js"), - output: fileout, - resources: files, -} +const nexeCopiler = {} if (options.v || options.verbose) nexeCopiler.loglevel = "verbose" // Build Binarie -compile(nexeCopiler).then(() => {console.log("success")}) +compile({ + name: "Bds Maneger Core", + build: true, + input: resolve(__dirname, "bds_maneger.js"), + output: fileout, + resources: readdirSync(resolve(__dirname, "..")).filter(retu => !/[Dd]ocker*.js|docker_config.json|*\.log/gi.test(retu)), + ...nexeCopiler +}).then(() => process.exit(0)).catch(() => process.exit(1)); diff --git a/.github/workflows/Base.yml b/.github/workflows/Base.yml deleted file mode 100644 index ade6a22..0000000 --- a/.github/workflows/Base.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: Bds Maneger - Docker Base -on: - push: - tags: - - v* - - V* - -# schedule: -# - cron: 0 0 * * */6 - -env: - DOCKER_ARCHS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6 - -jobs: - base: - runs-on: ubuntu-latest - steps: - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - username: ${{ secrets.DOCKER_ORG_USER }} - password: ${{ secrets.DOCKER_ORG_PASS }} - - - name: checkout - uses: actions/checkout@master - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - push: true - target: bdsbase - tags: | - bdsmaneger/node_image:latest - bdsmaneger/node_image:${{ github.run_id }} - platforms: ${{ env.DOCKER_ARCHS }} diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 002d7f2..99da2ac 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -3,11 +3,9 @@ on: push: branches: - main - paths-ignore: - - 'README.md' - - '.github/*/**' - - 'package-lock.json' - - '.devcontainer/**' + +env: + DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7 jobs: npm: @@ -20,16 +18,18 @@ jobs: with: node-version: 16.x registry-url: https://registry.npmjs.org/ + - name: Edit Version - run: | - id_run1=$(echo ${{ github.run_id }} |cut -b 1-2) - id_run2=$(echo ${{ github.run_id }} |cut -b 3-6) - id_run3=$(echo ${{ github.run_id }} |cut -b 7-) - old="$(cat package.json |grep "version"|head -1)" - new_version="$id_run1.$id_run2.$id_run3" - sed "s|$old|\"version\": \"$new_version\",|g" package.json > package2.json - cat package2.json > package.json - rm -rfv package2.json + uses: actions/github-script@v4 + id: set-result + with: + script: | + const fs = require('fs'); + const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8')); + const run_ID = "${{ github.run_id }}"; + Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`; + fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_Json, null, 2)); + result-encoding: string - name: Install Packages run: npm install @@ -37,9 +37,10 @@ jobs: - name: NPM Publish run: npm publish --tag dev env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }} + NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}" - docker: + docker_core: + needs: [npm] runs-on: ubuntu-latest steps: - name: Set up QEMU @@ -63,5 +64,35 @@ jobs: with: push: true target: bdscore - tags: bdsmaneger/core:nightly - platforms: linux/amd64,linux/arm64,linux/arm/v7 + tags: bdsmaneger/core:main + platforms: ${{ env.DOCKER_ARCH }} + + docker_base: + needs: [npm] + runs-on: ubuntu-latest + steps: + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_ORG_USER }} + password: ${{ secrets.DOCKER_ORG_PASS }} + + - name: checkout + uses: actions/checkout@master + + - name: Build and push + id: docker_build + uses: docker/build-push-action@v2 + with: + push: true + target: bdsbase + tags: | + bdsmaneger/base:main + bdsmaneger/node_image:main + platforms: ${{ env.DOCKER_ARCH }} \ No newline at end of file diff --git a/.github/workflows/package_test.yml b/.github/workflows/package_test.yml index 2a654ea..f4e7851 100644 --- a/.github/workflows/package_test.yml +++ b/.github/workflows/package_test.yml @@ -9,13 +9,30 @@ jobs: node-version: [14.x, 15.x, 16.x] steps: - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2.4.0 with: node-version: ${{ matrix.node-version }} - cache: 'npm' - - run: npm install -d --no-save - - run: npm test + + - name: Edit Version + uses: actions/github-script@v4 + with: + script: | + const fs = require('fs'); + const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8')); + const run_ID = "${{ github.run_id }}"; + Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`; + fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_Json, null, 2)); + console.log(Package_JSon.version); + return Package_JSon.version; + result-encoding: string + + - name: Install node depedencies + run: npm install -d --no-save + + - name: Run test + run: npm run ci Test_Docker: runs-on: ubuntu-latest diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml deleted file mode 100644 index e2d4361..0000000 --- a/.github/workflows/rc.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: Bds Core Release Candidate -on: - push: - tags: - - rc** - -jobs: - npm: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@master - - uses: actions/setup-node@v2.4.0 - with: - node-version: 16.x - registry-url: https://registry.npmjs.org/ - - - name: Install Depedencies - run: npm install --no-save - - - name: Publish - run: npm publish --tag rc - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }} - - docker: - runs-on: ubuntu-latest - steps: - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - username: ${{ secrets.DOCKER_ORG_USER }} - password: ${{ secrets.DOCKER_ORG_PASS }} - - - name: checkout - uses: actions/checkout@master - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - push: true - target: bdscore - tags: bdsmaneger/core:rc_${{ github.run_id }} - platforms: linux/amd64,linux/arm64,linux/arm/v7 diff --git a/.github/workflows/tag_version.yml b/.github/workflows/tag_version.yml index db85832..214596f 100644 --- a/.github/workflows/tag_version.yml +++ b/.github/workflows/tag_version.yml @@ -5,9 +5,13 @@ on: - v** - V** +env: + DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7 + jobs: npm: runs-on: ubuntu-latest + if: ${{ github.actor }} == ${{ github.repository_owner }} steps: - uses: actions/checkout@master - uses: actions/setup-node@v2.4.0 @@ -21,9 +25,10 @@ jobs: - name: Publish run: npm publish env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }} + NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}" - docker: + docker_core: + needs: [npm] runs-on: ubuntu-latest steps: - name: Set up QEMU @@ -48,4 +53,36 @@ jobs: push: true target: bdscore tags: bdsmaneger/core:latest - platforms: linux/amd64,linux/arm64,linux/arm/v7 + platforms: ${{ env.DOCKER_ARCH }} + + docker_base: + needs: [npm] + runs-on: ubuntu-latest + steps: + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_ORG_USER }} + password: ${{ secrets.DOCKER_ORG_PASS }} + + - name: checkout + uses: actions/checkout@master + + - name: Build and push + id: docker_build + uses: docker/build-push-action@v2 + with: + push: true + target: bdsbase + tags: | + bdsmaneger/base:latest + bdsmaneger/base:${{ github.run_id }} + bdsmaneger/node_image:latest + bdsmaneger/node_image:${{ github.run_id }} + platforms: ${{ env.DOCKER_ARCH }} diff --git a/.gitignore b/.gitignore index 33ef586..de9db14 100644 --- a/.gitignore +++ b/.gitignore @@ -1,26 +1,23 @@ +# Log +*.log + +# test files +*.test +*test*.js* +test/ +Test/ + +# Node node_modules/ -*-Test/ -*teste/ -debug.log Bds_Maneger .dccache docs/ -run.log -build.log -Docker.js.log -Docker.js + +# Bds Maneger Core Binaries bds_maneger BdsManager-bin* Bds-Maneger-Core -# Docker Build -Docker.exe - -# Bin Ignores -bin/* -!bin/bds_maneger.js -!bin/telegram_bot.js - # ** .husky Servers \ No newline at end of file diff --git a/.gitlab/.gitlab-webide.yml b/.gitlab/.gitlab-webide.yml index bfa8401..2a2d0ee 100644 --- a/.gitlab/.gitlab-webide.yml +++ b/.gitlab/.gitlab-webide.yml @@ -1,5 +1,5 @@ terminal: - image: bdsmaneger/node_image:latest + image: bdsmaneger/core:latest services: - docker:dind before_script: diff --git a/.gitlab/workflows/Nightly.yml b/.gitlab/workflows/Nightly.yml deleted file mode 100644 index 2765c0b..0000000 --- a/.gitlab/workflows/Nightly.yml +++ /dev/null @@ -1,21 +0,0 @@ -Docker_Nightly: - image: ubuntu:latest - variables: - DOCKER_TLS_CERTDIR: "" - DOCKER_DRIVER: overlay2 - DOCKER_HOST: tcp://docker:2375 - services: - - docker:dind - before_script: - - | - apt update && apt install -y curl &> /dev/null - curl https://get.docker.com | bash - &> /dev/null - docker info - docker run --privileged --rm tonistiigi/binfmt --install all - docker run --privileged --rm multiarch/qemu-user-static --reset -p yes - docker buildx create --name multiarch --driver docker-container --use - docker buildx inspect --bootstrap - docker login --username="$DOCKER_USER" --password="$DOCKER_TOKEN" &> /dev/null - script: - - docker pull bdsmaneger/maneger:nightly - - docker buildx build -t bdsmaneger/maneger:nightly --platform=linux/amd64,linux/arm64/v8,linux/arm/v7 . diff --git a/.gitlab/workflows/Stable.yml b/.gitlab/workflows/Stable.yml index 5672f55..4042f0e 100644 --- a/.gitlab/workflows/Stable.yml +++ b/.gitlab/workflows/Stable.yml @@ -1,8 +1,5 @@ -Docker_Stable: +Docker: image: ubuntu:latest - only: - - v* - - V* variables: DOCKER_TLS_CERTDIR: "" DOCKER_DRIVER: overlay2 @@ -18,6 +15,5 @@ Docker_Stable: docker run --privileged --rm multiarch/qemu-user-static --reset -p yes docker buildx create --name multiarch --driver docker-container --use docker buildx inspect --bootstrap - docker login --username="$DOCKER_USER" --password="$DOCKER_TOKEN" &> /dev/null script: - - docker buildx build -t bdsmaneger/maneger:latest --platform=linux/amd64,linux/arm64/v8,linux/arm/v7 . + - docker buildx build -t bdsmaneger/maneger:latest --platform=linux/amd64,linux/arm64,linux/arm/v7 . diff --git a/.npmignore b/.npmignore index 32550d8..99693aa 100644 --- a/.npmignore +++ b/.npmignore @@ -1,17 +1,16 @@ -Docker/ -.docker* -.github/ -.devconatiner/ -.vscode/ -node_modules/ -*-Test/ -*teste/ -debug.log -Bds_Maneger -.dccache -run.log -build.log -Docker.js.log -Docker.js -bds_maneger -BdsManager-bin* \ No newline at end of file +# Log +*.log + +# test files +*.test +*test*.js* +test/ +Test/ + +# Git +git* +.git* + +# Docker +.dockerignore +Docker* \ No newline at end of file diff --git a/Docker/AzureContainerDeploy.json b/Docker/AzureContainerDeploy.json deleted file mode 100644 index 6e932cd..0000000 --- a/Docker/AzureContainerDeploy.json +++ /dev/null @@ -1,201 +0,0 @@ -{ - "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json", - "contentVersion": "1.50.0.0", - "parameters": { - "containerName": { - "type": "string", - "maxLength": 63, - "defaultValue": "bds-maneger" - }, - "TelegramBotToken": { - "type": "string", - "defaultValue": "null" - }, - "WorldName": { - "type": "string", - "defaultValue": "Minecraft Bedrock" - }, - "ServerDescription": { - "type": "string", - "defaultValue": "The Bds Maneger in Docker" - }, - "ServerGameMode": { - "type": "string", - "defaultValue": "survival", - "allowedValues": ["survival","creative","hardcore"] - }, - "ServerDifficulty": { - "type": "string", - "defaultValue": "normal", - "allowedValues": ["normal","easy"] - }, - "ServerPlayers": { - "type": "string", - "defaultValue": "30", - "metadata": { - "description": "The more players, the more CPU, the more RAM will be needed." - }, - "allowedValues": ["5","10","15","20","25","30","35","40","45","50","70","100","200"] - }, - "ServerPlatform": { - "type": "string", - "defaultValue": "bedrock", - "allowedValues": ["bedrock", "java", "pocketmine", "jsprismarine"], - "metadata": { - "description": "Bedrock: Phones, Xbox, Nintendo switch, etc. Java: Desktops" - } - }, - "numberCpuCores": { - "type": "string", - "defaultValue": "2", - "allowedValues": ["1","2","3","4"] - }, - "RamMemory": { - "type": "string", - "allowedValues": ["1","2","4","6","8","10"], - "defaultValue": "4" - } - }, - "variables": { - "bdsstorage": "bdssave", - "StorageName": "[concat('bdssave', uniqueString(resourceGroup().id))]", - "DnsName": "[concat('bdsdns-', uniqueString(resourceGroup().id))]", - "bds_ports": [ - { - "port": "1932", - "protocol": "TCP" - }, - { - "port": "6565", - "protocol": "TCP" - }, - { - "port": "19132", - "protocol": "UDP" - }, - { - "port": "19133", - "protocol": "UDP" - } - ] - }, - "resources": [ - { - "type": "Microsoft.Storage/storageAccounts", - "apiVersion": "2019-06-01", - "name": "[variables('StorageName')]", - "location": "[resourceGroup().location]", - "kind": "StorageV2", - "sku": { - "name": "Standard_LRS", - "tier": "Standard" - }, - "properties": { - "accessTier": "Hot", - "allowBlobPublicAccess": true, - "allowSharedKeyAccess": true, - "largeFileSharesState": "Enabled" - } - }, - { - "type": "Microsoft.Storage/storageAccounts/fileServices/shares", - "apiVersion": "2019-06-01", - "name": "[concat(variables('StorageName'), '/default/', variables('bdsstorage'))]", - "dependsOn": [ - "[resourceId('Microsoft.Storage/storageAccounts', variables('StorageName'))]" - ] - }, - // Docker Bds Manegerg Image - { - "location": "[resourceGroup().location]", - "name": "[parameters('containerName')]", - "dependsOn": [ - "[resourceId('Microsoft.Storage/storageAccounts/fileServices/shares', variables('StorageName'), 'default', variables('bdsstorage') )]" - ], - "type": "Microsoft.ContainerInstance/containerGroups", - "apiVersion": "2019-12-01", - "properties": { - "containers": [ - { - "name": "[parameters('containerName')]", - "properties": { - "image": "bdsmaneger/core:latest", - "resources": { - "requests": { - "cpu": "[int(parameters('numberCpuCores'))]", - "memoryInGB": "[float(parameters('RamMemory'))]" - } - }, - "ports": "[variables('bds_ports')]", - "environmentVariables": [ - { - "name": "TELEGRAM_TOKEN", - "value": "[parameters('TelegramBotToken')]" - }, - { - "name": "WORLD_NAME", - "value": "[parameters('WorldName')]" - }, - { - "name": "DESCRIPTION", - "value": "[parameters('ServerDescription')]" - }, - { - "name": "GAMEMODE", - "value": "[parameters('ServerGameMode')]" - }, - { - "name": "DIFFICULTY", - "value": "[parameters('ServerDifficulty')]" - }, - { - "name": "PLAYERS", - "value": "[parameters('ServerPlayers')]" - }, - { - "name": "SERVER", - "value": "[parameters('ServerPlatform')]" - }, - { - "name": "BDS_VERSION", - "value": "latest" - } - ], - "volumeMounts": [ - { - "name": "save", - "mountPath": "/home/bds" - } - ] - } - } - ], - "restartPolicy": "OnFailure", - "osType": "Linux", - "ipAddress": { - "type": "Public", - "ports": "[variables('bds_ports')]", - "dnsNameLabel": "[variables('DnsName')]" - }, - "volumes": [ - { - "name": "save", - "azureFile": { - "shareName": "[variables('bdsstorage')]", - "StorageAccountName": "[variables('StorageName')]", - // https://stackoverflow.com/a/33227123 - "storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('StorageName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[1].value]" - } - } - ] - }, - "tags": {} - } - ], - "outputs": { - "containerIPv4Address": { - "type": "string", - "value": "[reference(resourceId('Microsoft.ContainerInstance/containerGroups/', parameters('containerName'))).ipAddress.ip]" - } - } -} \ No newline at end of file diff --git a/bin/Docker.js b/bin/Docker.js new file mode 100644 index 0000000..be9209f --- /dev/null +++ b/bin/Docker.js @@ -0,0 +1,100 @@ +#!/usr/bin/env node +const BdsCore = require("../index"); +const { GetPlatform } = require("../lib/BdsSettings"); +const { Servers } = require("../lib/ServerURL"); +const { CronJob } = require("cron"); +const BdsInfo = require("../BdsManegerInfo.json"); + +process.env.BDS_DOCKER_IMAGE = true; + +function StartServer(){ + console.log("The entire log can be accessed via the api and/or the docker log"); + const ServerStarted = BdsCore.start(); + ServerStarted.log(a => process.stdout.write(a)); + ServerStarted.exit(process.exit); + BdsCore.api(); + new CronJob("0 */1 * * *", async () => { + try { + const CurrentLocalVersion = BdsCore.getBdsConfig().server.versions[GetPlatform()], + CurrentRemoteVersion = Object.getOwnPropertyNames((await (await fetch(BdsInfo.download.servers)).json())[GetPlatform()])[0]; + if (CurrentLocalVersion !== CurrentRemoteVersion) { + let currenttime = `Hello we are starting the server upgrade from version ${CurrentLocalVersion} to version ${CurrentRemoteVersion}, you have 20 seconds to exit the server` + console.log("Update Server:", currenttime); + ServerStarted.say(currenttime); + let countdown = 20; + while (countdown > 1) { + currenttime = `${countdown} seconds remaining to stop Server!`; + console.log(currenttime); + ServerStarted.say(currenttime); + countdown--; + await new Promise(resolve => setTimeout(resolve, 1000)); + } + currenttime = "Stopping the server" + console.log(currenttime); + ServerStarted.say(currenttime); + await new Promise(resolve => setTimeout(resolve, 600)); + ServerStarted.stop(); + } + } catch (err) { + console.log(err); + } + }); +} + +// Check Installed Server +const AllVersions = BdsCore.BdsSettigs.GetJsonConfig().server.versions; +if (Object.getOwnPropertyNames(AllVersions).filter(platform => AllVersions[platform]).length >= 1) { + if (process.env.UPDATE_SERVER === "true") { + BdsCore.download(true, true, (err) => { + if (err) { + console.log(err); + process.exit(1); + } + StartServer(); + }); + } else { + // Check for Update + if (AllVersions[GetPlatform()] === Object.getOwnPropertyNames(Servers[GetPlatform()])[0]) { + console.log("The entire log can be accessed via the api and/or the docker log"); + const ServerStarted = BdsCore.start(); + ServerStarted.log(a => process.stdout.write(a)); + ServerStarted.exit(process.exit); + BdsCore.api(); + } else { + BdsCore.download(true, true, (err) => { + if (err) { + console.log(err); + process.exit(1); + } + StartServer(); + }); + } + } +} else { + console.log("Server is not installed, starting server implementation"); + // Import ENV to Settings Server + const { DESCRIPTION, WORLD_NAME, GAMEMODE, DIFFICULTY, ACCOUNT, PLAYERS, SERVER, ENABLE_COMMANDS } = process.env; + // Update Platform + BdsCore.change_platform(SERVER || "bedrock"); + BdsCore.download(true, true, (err) => { + if (err) { + console.log(err); + process.exit(1); + } + // Create JSON Config + const ServerConfig = { + world: WORLD_NAME, + description: DESCRIPTION, + gamemode: GAMEMODE, + difficulty: DIFFICULTY, + players: parseInt(PLAYERS), + commands: ENABLE_COMMANDS === "true", + account: ACCOUNT === "true", + whitelist: false, + port: 19132, + portv6: 19133, + } + BdsCore.set_config(ServerConfig); + StartServer(); + }); +} \ No newline at end of file diff --git a/bin/bds_maneger.js b/bin/bds_maneger.js index f254b85..9aeb4c6 100755 --- a/bin/bds_maneger.js +++ b/bin/bds_maneger.js @@ -18,7 +18,7 @@ const server = (argv.p || argv.platform), version = (argv.v || argv.version), SystemCheck = (argv.S || argv.system_info), - bds_version = (argv.d || argv.server_download), + bds_version = (argv.d || argv.download), start = (argv.s || argv.server_version), help = (argv.h || argv.help), kill = (argv.k || argv.kill); @@ -93,7 +93,7 @@ if (help) { " -s --start Start Server", " -k --kill Detect and kill bds servers", " -p --platform Select server platform", - " -d --server_download server version to install, default \"latest\"", + " -d --download server version to install, default \"latest\"", " --interactive Install the server interactively", " -S --system_info System info and test", " -h --help Print this list and exit.", @@ -158,21 +158,30 @@ if (SystemCheck) { 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 - // deepcode ignore MissingClose: - const DownloadOptions = readline.createInterface({input: process.stdin,output: process.stdout}); - console.log("\nSelect Option"); - DownloadOptions.on("line", (input) => { - download(Version[parseInt(input)], true, function(){ - console.log("Installation was successful, so start the server with the -s option"); - if (start) StartServer(); - else process.exit(0) - }) - }); + + const StartQuestion = (Readline) => { + Readline.question("Select a version to download: ", input => { + if (Version[parseInt(input) - 1]) { + Readline.close(); + download(Version[parseInt(input) - 1], true, function(){ + if (start) return StartServer(); + console.log("Installation was successful, so start the server with the -s option"); + process.exit(0); + }) + } else { + console.log("Invalid Option"); + StartQuestion(Readline); + } + }); + } + + console.log(`Selected platform: ${GetPlatform()}, Total available versions: ${Version.length}`); + console.log("Option Version"); + + for (let option in Version) console.log(`${parseInt(option) + 1} -------- ${Version[option]}`); + StartQuestion(readline.createInterface({input: process.stdin,output: process.stdout})); } else bds.download(bds_version, true, function(){ if (start) StartServer(); diff --git a/index.js b/index.js index eb14cb5..9d730f1 100644 --- a/index.js +++ b/index.js @@ -49,10 +49,11 @@ module.exports.telegram_token_save = UpdateTelegramToken */ module.exports.api = require("./src/rest/api"); -function token_register() { +function token_register(Admin_Scoper = ["web_admin", "admin"]) { + Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper)); const bds_token_path = path.join(bds_dir, "bds_tokens.json"); - if (!(fs.existsSync(bds_token_path))) fs.writeFileSync(bds_token_path, "[]"); - const tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8")); + let tokens = [] + if (fs.existsSync(bds_token_path)) tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8")); // Get UUID const getBdsUUId = randomUUID().split("-"); @@ -62,7 +63,7 @@ function token_register() { tokens.push({ token: bdsuid, date: new Date(), - scopers: ["admin"] + scopers: Admin_Scoper }); fs.writeFileSync(bds_token_path, JSON.stringify(tokens, null, 4), "utf8"); console.log(`Bds Maneger API REST token: "${bdsuid}"`); @@ -76,6 +77,13 @@ function token_register() { */ module.exports.token_register = token_register +/** + * Register tokens to use in Bds Maneger REST and other supported applications + * + * @example token_register() + */ +module.exports.bds_maneger_token_register = token_register + /** * Update, Get and more to Modifications Bds Settings File */ @@ -143,7 +151,7 @@ module.exports.kill = Kill * * java: download("1.16.5") * - * any platform: download("latest") // It will download the latest version available for download + * any platform: download("latest") || download(true) // It will download the latest version available for download */ module.exports.download = download diff --git a/lib/BdsSettings.js b/lib/BdsSettings.js index 77e95f9..d286ee4 100644 --- a/lib/BdsSettings.js +++ b/lib/BdsSettings.js @@ -1,4 +1,4 @@ -const { join, resolve } = require("path"); +const { join, resolve, basename } = require("path"); const { existsSync, writeFileSync, mkdirSync, readFileSync } = require("fs"); const { homedir } = require("os"); const { valid_platform } = require("./BdsSystemInfo"); @@ -17,7 +17,7 @@ var default_platformConfig; if (valid_platform["bedrock"]) default_platformConfig = "bedrock"; else if (valid_platform["java"]) default_platformConfig = "java"; else if (valid_platform["pocketmine"]) default_platformConfig = "pocketmine"; -else default_platformConfig = "jsprismarine" +else throw new Error("We cannot run any platforms on this system/device"); // Config Base to Bds Maneger Core and others Projects var Config = { @@ -76,6 +76,7 @@ var Config = { java: true, pocketmine: true, jsprismarine: true, + spigot: true, }, { username: "Alex", @@ -84,6 +85,7 @@ var Config = { java: true, pocketmine: true, jsprismarine: true, + spigot: true, }, { username: "steve", @@ -92,6 +94,7 @@ var Config = { java: true, pocketmine: true, jsprismarine: true, + spigot: true, }, { username: "alex", @@ -100,6 +103,7 @@ var Config = { java: true, pocketmine: true, jsprismarine: true, + spigot: true, } ], telegram: { @@ -115,7 +119,7 @@ if (existsSync(ConfigPath)) Config = { ...Config, ...yaml.parse(readFileSync(ConfigPath, "utf8")) }; else writeFileSync(ConfigPath, yaml.stringify(Config)) -process.on("exit", ()=>SaveConfig()) +process.on("exit", () => SaveConfig()) // Paths if (!(existsSync(Config.paths["backups"]))) mkdirSync(Config.paths["backups"], {recursive: true}) @@ -128,18 +132,15 @@ const ServersPaths = { java: join(Config.paths.servers, "Java"), pocketmine: join(Config.paths.servers, "Pocketmine-MP"), jsprismarine: join(Config.paths.servers, "JSPrismarine"), + dragonfly: join(Config.paths.servers, "Dragonfly_go"), + spigot: join(Config.paths.servers, "Spigot") } -for (let Servers of Object.getOwnPropertyNames(ServersPaths)) { - if (!(existsSync(ServersPaths[Servers]))) { - console.log(`Creating the ${Servers} Folder`); - mkdirSync(ServersPaths[Servers], {recursive: true}) +Object.getOwnPropertyNames(ServersPaths).map(Servers => ServersPaths[Servers]).forEach(Servers => { + if (!(existsSync(Servers))) { + console.log(`Creating the ${basename(Servers)} Folder`); + mkdirSync(Servers, {recursive: true}) } -} - -// return settings by function -function GetJsonConfig(){ - return Config -} +}); // get the path from the settings and return by function function GetPaths(path = null){ @@ -156,11 +157,6 @@ function GetServerPaths(path = null){ return ServersPaths[path] } -// Get the server settings for now it's only being used in Java -function GetServerSettings(platform = Config.server.platform){ - return Config.server.Settings[platform] -} - // Update the settings and save at the same time so as not to lose any information from the Bds Maneger settings function UpdateServerVersion(version = null, platform = Config.server.platform){ if (Config.server.versions[platform] || Config.server.versions[platform] === null) { @@ -170,21 +166,6 @@ function UpdateServerVersion(version = null, platform = Config.server.platform){ } else throw new Error("Platform invalid") } -// Return an Object with all server versions installed -function GetServerVersion(){ - return Config.server.versions -} - -// Catch Players/People from Servers/Telegram to be banned or removed from Server/Minecraft -function GetServerBan(){ - return Config.ban -} - -// Cron for Backup -function GetCronBackup(){ - return Config.server.BackupCron -} - // Update the entire Bds Manager Core platform function UpdatePlatform(platform = Config.server.platform){ platform = platform.toLocaleLowerCase(); @@ -197,6 +178,9 @@ function UpdatePlatform(platform = Config.server.platform){ } else if (/pocketmine/.test(platform)) { Config.server.platform = "pocketmine"; SaveConfig() + } else if (/spigot/.test(platform)) { + Config.server.platform = "spigot"; + SaveConfig() } else if (/jsprismarine/.test(platform)) { Config.server.platform = "jsprismarine"; SaveConfig() @@ -204,11 +188,6 @@ function UpdatePlatform(platform = Config.server.platform){ return platform } -// Return to platform -function GetPlatform(){ - return Config.server.platform -} - // Telegram function UpdateTelegramToken(token = null){ if (!(token)) throw new Error("Telegram Token invalid") @@ -217,18 +196,20 @@ function UpdateTelegramToken(token = null){ return token } -function GetTelegramToken(){ - return Config.telegram.token -} +const GetJsonConfig = () => Config; -function GetTelegramAdmins(){ - return Config.telegram.admins -} +const GetCronBackup = () => Config.server.BackupCron; +const GetPlatform = () => Config.server.platform; + +const GetServerBan = () => Config.ban; +const GetServerVersion = () => Config.server.versions; +const GetServerSettings = (platform = Config.server.platform) => Config.server.Settings[platform]; + +const GetTelegramToken = () => Config.telegram.token; +const GetTelegramAdmins = () => Config.telegram.admins; // Get a temporary host to connect to the server. -function GetTempHost(){ - return Config.bds.enable_tmp_host -} +const GetTempHost = () => Config.bds.enable_tmp_host // Enable and/or disable pick up temporary host. function UpdateTempHost(enable = false){ @@ -237,7 +218,8 @@ function UpdateTempHost(enable = false){ // Save Config.bds.enable_tmp_host = enable - return SaveConfig(); + SaveConfig(); + return true; } // Get the server settings diff --git a/lib/BdsSystemInfo.js b/lib/BdsSystemInfo.js index cc75fb3..dd571ea 100644 --- a/lib/BdsSystemInfo.js +++ b/lib/BdsSystemInfo.js @@ -1,41 +1,40 @@ -const commadExist = require("./commandExist"); const { execSync } = require("child_process"); -const { readdirSync } = require("fs"); const { release } = require("os"); +const { readdirSync } = require("fs"); +const commadExist = require("./commandExist"); const { PHPBin, Servers } = require("./ServerURL"); // System Architect (x64, aarch64 and others) var arch; -if (process.arch === "arm64") arch = "aarch64"; else arch = process.arch +if (process.arch === "arm64") arch = "aarch64"; +else arch = process.arch module.exports.arch = arch var system, -require_qemu = false, -valid_platform = { - bedrock: true, - pocketmine: true, - java: commadExist("java"), - jsprismarine: commadExist("node") -} + require_qemu = false, + valid_platform = { + bedrock: true, + pocketmine: true, + java: commadExist("java"), + dragonfly: commadExist("go"), + } // check php bin -if (PHPBin[process.platform]) { - if (PHPBin[process.platform][arch]) valid_platform["pocketmine"] = true; else valid_platform["pocketmine"] = false -} else valid_platform["pocketmine"] = false +if ((PHPBin[process.platform] || {})[arch]) valid_platform["pocketmine"] = true; + else valid_platform["pocketmine"] = false; // SoSystem X if (process.platform == "win32") { system = "Windows"; - // arm64 and X64 - // if (!(arch === "x64" || arch === "aarch64")) valid_platform["bedrock"] = false; } else if (process.platform == "linux") { system = "Linux"; + + // Bedrock Check if (Servers.bedrock[Servers.latest.bedrock][arch]) { - if (Servers.bedrock[Servers.latest.bedrock][arch][process.platform]) valid_platform["bedrock"] = true; else valid_platform["bedrock"] = false; - } else valid_platform["bedrock"] = false - - if (PHPBin[process.platform][arch]) valid_platform["pocketmine"] = true; else valid_platform["pocketmine"] = false - + if (Servers.bedrock[Servers.latest.bedrock][arch][process.platform]) valid_platform["bedrock"] = true; + else valid_platform["bedrock"] = false; + } else valid_platform["bedrock"] = false; + if (valid_platform["bedrock"] === false) { if (commadExist("qemu-x86_64-static")) { console.warn("The Minecraft Bedrock Server is only being validated because you can use 'qemu-x86_64-static'"); @@ -51,10 +50,7 @@ if (process.platform == "win32") { valid_platform["bedrock"] = false } else { console.log(`The Bds Maneger Core does not support ${process.platform} systems, as no tests have been done.`); - system = "Other"; - valid_platform["bedrock"] = false - valid_platform["pocketmine"] = false - process.exit(254) + process.exit(127); } function GetKernel() { @@ -65,43 +61,32 @@ function GetKernel() { else if (kernelVersion <= 6.3) return "Windows 8.1"; else if (kernelVersion <= 10.0) return "Windows 10"; else return "Other Windows or Windows 11"; - } - else if (process.platform === "android") return `${release()}, CPU Core ${readdirSync("/sys/devices/system/cpu/").filter(data=>{return /cpu[0-9]/.test(data)}).length}`; - else if (commadExist("uname")){ + } else if (process.platform === "android") return `Android: ${release()}, CPU Core ${readdirSync("/sys/devices/system/cpu/").filter(data => /cpu[0-9]/.test(data)).length}`; + else if (commadExist("uname")) { const str = execSync("uname -rv").toString("ascii"); - switch (true) { - // amazon aws EC2 - case /aws/.test(str): - if (process.arch === "arm64" || process.arch === "aarch64") return "Amazon AWS Cloud arm64: AWS Graviton"; - else return `Amazon AWS Cloud ${process.arch}: ${require("os").cpus()[0].model}`; - - // Windows WSL 1 - case /WSL2|microsft/.test(str): - return "Microsoft WSL 2"; - // Windows WSL 2 - case /microsoft/.test(str): - return "Microsoft WSL 1"; - - // Azure Virtual Machinime (VM) - case /[aA]zure/.test(str): - return "Microsoft Azure"; - - // Google Cloud Virtual Machinime (VM) - case /[gG]cp/.test(str): - return "Google Cloud Platform"; - - // Oracle cloud Virtual Machinime (VM) - case /[oO]racle/.test(str): - return "Oracle Cloud infrastructure"; - - // Darwin - case /[dD]arwin/.test(str): - return "Apple MacOS"; - - // Others Kernels - default: - return str.split("\n").join(""); + // Amazon web services + if (/aws/.test(str)) { + if (/arm64|aarch64/.test(process.arch)) return "Amazon AWS Cloud arm64: AWS Graviton Serie"; + else return `Amazon AWS Cloud ${process.arch}: ${require("os").cpus()[0].model}`; } + + // Windows subsystem for Linux + else if (/WSL2|microsft/.test(str)) return "Microsoft WSL"; + + // Azure Virtual Machinime (VM) + else if (/[aA]zure/.test(str)) return "Microsoft Azure"; + + // Google Cloud Virtual Machinime (VM) + else if (/[gG]cp/.test(str)) return "Google Cloud Platform"; + + // Oracle cloud Virtual Machinime (VM) + else if (/[oO]racle/.test(str)) return "Oracle Cloud infrastructure"; + + // Darwin + else if (/[dD]arwin/.test(str)) return "Apple MacOS"; + + // Others Kernels + else return str.replace(/\n|\t|\r/gi, ""); } else return "Not identified"; } diff --git a/src/BdsBackup.js b/src/BdsBackup.js index aad848a..0689d42 100644 --- a/src/BdsBackup.js +++ b/src/BdsBackup.js @@ -35,9 +35,6 @@ function Backup() { 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)); diff --git a/src/BdsManegerServer.js b/src/BdsManegerServer.js index f6d8668..4ae0efb 100644 --- a/src/BdsManegerServer.js +++ b/src/BdsManegerServer.js @@ -74,13 +74,8 @@ function start() { SetupCommands.cwd = GetServerPaths("pocketmine"); } - // Minecraft Bedrock (JSPrismarine) - else if (GetPlatform() === "jsprismarine") { - // Start JSPrismarine - SetupCommands.command = "node"; - SetupCommands.args.push("./packages/server/dist/Server.js"); - SetupCommands.cwd = GetServerPaths("jsprismarine"); - } else throw Error("Bds Config Error") + // Show Error platform + else throw Error("Bds Config Error") // Setup commands const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, { @@ -149,10 +144,7 @@ function start() { // Functions const data = data => Player_Json(data, function (array_status){ - for (let _player of array_status) { - if (action === "all") callback(_player); - else if (_player.Action === action) callback(_player) - } + array_status.filter(On => {if ("all" === action || On.Action === action) return true; else return false;}).forEach(_player => callback(_player)) }); ServerExec.stdout.on("data", data); ServerExec.stderr.on("data", data); diff --git a/src/BdsServersDownload.js b/src/BdsServersDownload.js index a0f25f7..b569b57 100644 --- a/src/BdsServersDownload.js +++ b/src/BdsServersDownload.js @@ -1,16 +1,158 @@ -var AdmZip = require("adm-zip"); const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = require("fs"); const { join, resolve, basename } = require("path"); -const bds = require("../index") +var AdmZip = require("adm-zip"); 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 bds = require("../index"); +const { execSync } = require("child_process"); + +module.exports = async function (version, force_install, callback) { + return new Promise(async (promise_resolve, promise_reject) => { + try { + // Server Paths + const bds_dir_bedrock = GetServerPaths("bedrock"), + bds_dir_java = GetServerPaths("java"), + bds_dir_pocketmine = GetServerPaths("pocketmine"), + bds_dir_spigot = GetServerPaths("spigot"), + bds_dir_dragonfly = GetServerPaths("dragonfly"); + + // JSON Configs and others + const Servers = (await (await fetch(Extra.download.servers)).json()); + const ServerVersion = GetServerVersion(); + const CurrentPlatform = GetPlatform(); + if (force_install === true) { + ServerVersion.java = "latest"; + ServerVersion.bedrock = "latest" + ServerVersion.pocketmine = "latest" + } + if (!(version) || version === true || version === "true" || version === "latest") version = Servers.latest[CurrentPlatform] + var url; + + console.log(`Installing version ${version}`); + // Bedrock Installer Script + if (CurrentPlatform === "bedrock") { + if (valid_platform.bedrock === true){ + if (version === "latest") version = Servers.latest.bedrock + if (!(force_install === true) && ServerVersion.bedrock === version) { + console.warn("Jumping, installed version") + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } else { + if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`) + url = Servers.bedrock[version][bds.arch][process.platform] + var server_configs, permissions, whitelist; + if (existsSync(join(bds_dir_bedrock, "server.properties"))) server_configs = readFileSync(join(bds_dir_bedrock, "server.properties"), "utf8"); + if (existsSync(join(bds_dir_bedrock, "permissions.json"))) permissions = readFileSync(join(bds_dir_bedrock, "permissions.json"), "utf8"); + if (existsSync(join(bds_dir_bedrock, "whitelist.json"))) whitelist = readFileSync(join(bds_dir_bedrock, "whitelist.json"), "utf8"); + + // Download and Add to Adm_Zip + const zip = new AdmZip(Buffer.from((await (await fetch(url)).arrayBuffer()))) + console.log("Download Sucess") + + zip.extractAllTo(bds_dir_bedrock, true) + console.log("Extract Sucess") + if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs); + if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions) + if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist) + UpdateServerVersion(version); + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } + } else throw Error("Bedrock Not suported") + } + + // Java + else if (CurrentPlatform === "java") { + if (valid_platform.java === true){ + if (version === "latest") version = Servers.latest.java + if (!(force_install === true) && version === ServerVersion.java) { + console.warn("Jumping, installed version") + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true) + } else { + url = Servers.java[version].url + console.log(`Server data publish: ${Servers.java[version].data}`) + + writeFileSync(join(bds_dir_java, "MinecraftServerJava.jar"), Buffer.from((await (await fetch(url)).arrayBuffer())), "binary") + console.log("Success when downloading and saving Minecraft Server java"); + UpdateServerVersion(version); + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } + } else throw Error("Java is not supported or required software is not installed") + } + + // Pocketmine-MP + else if (CurrentPlatform === "pocketmine") { + if (valid_platform.pocketmine === true) { + if (version === "latest") version = Servers.latest.pocketmine + if (!(force_install === true) && version === ServerVersion.pocketmine) { + console.warn("Jumping, installed version") + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true) + } else { + const PocketMineJson = Servers.pocketmine[version] + console.log(`Server data publish: ${PocketMineJson.data}`); + + writeFileSync(join(bds_dir_pocketmine, "PocketMine-MP.phar"), Buffer.from((await (await fetch(PocketMineJson.url)).arrayBuffer())), "binary") + console.log("Success downloading and saving PocketMine-MP php"); + + await php_download(); + + // Update server Version + UpdateServerVersion(version) + // Callback + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } + } else throw Error("Pocketmine not suported") + } + + // Spigot + else if (CurrentPlatform === "spigot") { + if (valid_platform.java) { + if (version === "latest") version = Servers.latest.spigot; + if (!(force_install === true) && version === ServerVersion.spigot) { + console.warn("Jumping, installed version") + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true) + } else { + const SpigotURL = Servers.spigot[version].url; + if (Servers.spigot[version].data) console.log(`Server data publish: ${Servers.spigot[version].data}`); + writeFileSync(join(bds_dir_spigot, "spigot.jar"), Buffer.from((await (await fetch(SpigotURL)).arrayBuffer())), "binary"); + console.log("Success when downloading and saving Spigot"); + UpdateServerVersion(version); + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } + } else throw Error("Java is not supported or required software is not installed") + } + + // dragonfly + else if (CurrentPlatform === "dragonfly") { + if (valid_platform.dragonfly) { + console.info("Dragonfly does not support versions"); + execSync("git clone https://github.com/df-mc/dragonfly ./", { + cwd: bds_dir_dragonfly + }); + if (typeof callback === "function") await callback(undefined, true); + promise_resolve(true); + } else throw Error("Dragonfly not suported") + } + + // Unidentified platform + else throw Error("Bds maneger Config file error") + } catch (err) { + if (typeof callback === "function") await callback(err, false); + return promise_reject(err); + } + }); +} async function php_download() { - const bds_dir_pocketmine = GetServerPaths("pocketmine"), - PHPBin = (await (await fetch(Extra.download.php)).json()); + const bds_dir_pocketmine = GetServerPaths("pocketmine"); + const PHPBin = (await (await fetch(Extra.download.php)).json()); const phpFolder = resolve(bds_dir_pocketmine, "bin"); const phpExtensiosnsDir = resolve(bds_dir_pocketmine, "bin/php7/lib/php/extensions"); @@ -18,7 +160,6 @@ async function php_download() { let urlPHPBin = PHPBin[process.platform] if (!(urlPHPBin)) throw new Error("unsupported system") urlPHPBin = urlPHPBin[bds.arch] - // Remove Old php Binary if it exists if (existsSync(phpFolder)) { @@ -34,7 +175,7 @@ async function php_download() { zipExtractBin.extractAllTo(bds_dir_pocketmine, false) console.log("Successfully extracting the binaries") - let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf-8"); + let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8"); if (!(existsSync(phpExtensiosnsDir))) return true; const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => { @@ -48,124 +189,4 @@ async function php_download() { writeFileSync(join(phpFolder, "php7", "bin", "php.ini"), phpConfigInit); } return true; -} - -module.exports = async function (version, force_install, callback) { - try { - const bds_dir_bedrock = GetServerPaths("bedrock"), - bds_dir_java = GetServerPaths("java"), - bds_dir_pocketmine = GetServerPaths("pocketmine"), - bds_dir_jsprismarine = GetServerPaths("jsprismarine"); - const Servers = (await (await fetch(Extra.download.servers)).json()); - const ServerVersion = GetServerVersion() - const CurrentPlatform = GetPlatform() - if (force_install === true) { - ServerVersion.java = "latest"; - ServerVersion.bedrock = "latest" - ServerVersion.pocketmine = "latest" - } - if (!(version) || version === true || version === "true" || version === "latest") version = Servers.latest[CurrentPlatform] - var url; - - console.log(`Installing version ${version}`); - // Bedrock Installer Script - if (CurrentPlatform === "bedrock") { - if (valid_platform.bedrock === true){ - if (version === "latest") version = Servers.latest.bedrock - if (ServerVersion.bedrock === version) { - console.warn("Jumping, installed version") - if (typeof callback === "function") await callback(undefined, true); - return true - } else { - if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`) - url = Servers.bedrock[version][bds.arch][process.platform] - var server_configs, permissions, whitelist; - if (existsSync(join(bds_dir_bedrock, "server.properties"))) server_configs = readFileSync(join(bds_dir_bedrock, "server.properties"), "utf8"); - if (existsSync(join(bds_dir_bedrock, "permissions.json"))) permissions = readFileSync(join(bds_dir_bedrock, "permissions.json"), "utf8"); - if (existsSync(join(bds_dir_bedrock, "whitelist.json"))) whitelist = readFileSync(join(bds_dir_bedrock, "whitelist.json"), "utf8"); - - // Download and Add to Adm_Zip - const zip = new AdmZip(Buffer.from((await (await fetch(url)).arrayBuffer()))) - console.log("Download Sucess") - - zip.extractAllTo(bds_dir_bedrock, true) - console.log("Extract Sucess") - if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs); - if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions) - if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist) - UpdateServerVersion(version) - if (typeof callback === "function") await callback(undefined, true); - return true - } - } else throw Error("Bedrock Not suported") - } - // java Installer Script - else if (CurrentPlatform === "java") { - if (valid_platform.java === true){ - if (version === "latest") version = Servers.latest.java - if (version === ServerVersion.java) { - console.warn("Jumping, installed version") - if (typeof callback === "function") await callback(undefined, true); - return true - } else { - url = Servers.java[version].url - console.log(`Server data publish: ${Servers.java[version].data}`) - - writeFileSync(join(bds_dir_java, "MinecraftServerJava.jar"), Buffer.from((await (await fetch(url)).arrayBuffer())), "binary") - console.log("Success when downloading and saving Minecraft Server java"); - UpdateServerVersion(version); - if (typeof callback === "function") await callback(undefined, true); - return true - } - } else throw Error("Java is not supported or required software is not installed") - } - // Pocketmine-MP Installer Script - else if (CurrentPlatform === "pocketmine") { - if (valid_platform.pocketmine === true) { - if (version === "latest") version = Servers.latest.pocketmine - if (version === ServerVersion.pocketmine) { - console.warn("Jumping, installed version") - if (typeof callback === "function") await callback(undefined, true); - return true - } else { - const PocketMineJson = Servers.pocketmine[version] - console.log(`Server data publish: ${PocketMineJson.data}`); - - writeFileSync(join(bds_dir_pocketmine, "PocketMine-MP.phar"), Buffer.from((await (await fetch(PocketMineJson.url)).arrayBuffer())), "binary") - console.log("Success downloading and saving PocketMine-MP php"); - - await php_download(); - - // Update server Version - UpdateServerVersion(version) - // Callback - if (typeof callback === "function") await callback(undefined, true); - return true - } - } else throw Error("Pocketmine not suported") - } - - // JSPrismarine - else if (CurrentPlatform === "jsprismarine") { - if (valid_platform.jsprismarine === true) { - console.log("Downloading the JSPrismarine repository."); - const commit_sha = GitClone("https://github.com/JSPrismarine/JSPrismarine.git", bds_dir_jsprismarine, 1); - for (let command of ["npm install", "npx -y lerna bootstrap", "npm run build"]) console.log(execSync(command, {cwd: bds_dir_jsprismarine}).toString("ascii")); - console.log(commit_sha); - UpdateServerVersion(commit_sha, "jsprismarine") - if (typeof callback === "function") await callback(undefined, true); - return true - } else throw Error("jsprismarine not suported") - } - - // dragonfly - else if (CurrentPlatform === "dragonfly") { - throw "Bds maneger Config file error"; - } - // Unidentified platform - else throw Error("Bds maneger Config file error") - } catch (err) { - if (typeof callback === "function") await callback(err, false); - return err; - } -} +} \ No newline at end of file diff --git a/src/CheckKill.js b/src/CheckKill.js index b7a577b..50315db 100644 --- a/src/CheckKill.js +++ b/src/CheckKill.js @@ -56,7 +56,6 @@ function Detect(){ if (/MinecraftServerJava.jar/.test(check.command)) return true; if (/bedrock_server/.test(check.command)) return true; if (/PocketMine-MP.phar/.test(check.command)) return true; - if (/packages\/server\/dist\/Server.js/.test(check.command)) return true; } return false } @@ -77,10 +76,6 @@ function Kill(){ console.log("Killing Pocketmine-MP"); killWithPid(check.pid); } - if (/packages\/server\/dist\/Server.js/.test(check.command)) { - console.log("Killing JSPrismarine"); - killWithPid(check.pid) - } } return true } diff --git a/src/rest/routes/bds.js b/src/rest/routes/bds.js index ad4ff91..fdb6ced 100644 --- a/src/rest/routes/bds.js +++ b/src/rest/routes/bds.js @@ -73,7 +73,6 @@ app.get("/info", ({ res }) => { const config = bds.get_config(); var info = { server: { - platform: GetPlatform(), world_name: config.world, running: bds.detect(), port: config.portv4, @@ -85,12 +84,13 @@ app.get("/info", ({ res }) => { arch: bds.arch, system: process.platform, Kernel: GetKernel(), + QEMU_STATIC: commandExist("qemu-x86_64-static") || commandExist("qemu-x86_64"), 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: { + platform: GetPlatform(), version: bds.package_json.version, server_versions: GetServerVersion(), } -- 2.47.2 From a101d89a10b03e05d2a2e6fd33defe720bf1cc69 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Mon, 16 Aug 2021 00:21:10 -0300 Subject: [PATCH 11/11] Change package version --- .github/ChangeVersion.js | 6 ++++++ .github/workflows/main.yml | 15 ++++----------- .github/workflows/package_test.yml | 14 +++----------- 3 files changed, 13 insertions(+), 22 deletions(-) create mode 100644 .github/ChangeVersion.js diff --git a/.github/ChangeVersion.js b/.github/ChangeVersion.js new file mode 100644 index 0000000..411ccb9 --- /dev/null +++ b/.github/ChangeVersion.js @@ -0,0 +1,6 @@ +const fs = require('fs'); +const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8')); +const run_ID = process.env.RunID || "1111111111111111111111111111111111111"; +Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`; +fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_JSon, null, 2)); +console.log(Package_JSon.version); diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 99da2ac..8fc847d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -20,16 +20,9 @@ jobs: registry-url: https://registry.npmjs.org/ - name: Edit Version - uses: actions/github-script@v4 - id: set-result - with: - script: | - const fs = require('fs'); - const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8')); - const run_ID = "${{ github.run_id }}"; - Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`; - fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_Json, null, 2)); - result-encoding: string + env: + RunID: ${{ github.run_id }} + run: node .github/ChangeVersion.js - name: Install Packages run: npm install @@ -95,4 +88,4 @@ jobs: tags: | bdsmaneger/base:main bdsmaneger/node_image:main - platforms: ${{ env.DOCKER_ARCH }} \ No newline at end of file + platforms: ${{ env.DOCKER_ARCH }} diff --git a/.github/workflows/package_test.yml b/.github/workflows/package_test.yml index f4e7851..f0c049e 100644 --- a/.github/workflows/package_test.yml +++ b/.github/workflows/package_test.yml @@ -16,17 +16,9 @@ jobs: node-version: ${{ matrix.node-version }} - name: Edit Version - uses: actions/github-script@v4 - with: - script: | - const fs = require('fs'); - const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8')); - const run_ID = "${{ github.run_id }}"; - Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`; - fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_Json, null, 2)); - console.log(Package_JSon.version); - return Package_JSon.version; - result-encoding: string + env: + RunID: ${{ github.run_id }} + run: node .github/ChangeVersion.js - name: Install node depedencies run: npm install -d --no-save -- 2.47.2