Add new Bds Maneger Core CLI #194

Merged
Sirherobrine23 merged 12 commits from CLI into main 2021-09-25 06:20:18 +00:00
11 changed files with 1376 additions and 114 deletions

6
.gitignore vendored
View File

@ -9,16 +9,10 @@ Test/
# Node
node_modules/
Bds_Maneger
.dccache
docs/
the-bds-maneger-core-*.tgz
# Bds Maneger Core Binaries
bds_maneger
BdsManager-bin*
Bds-Maneger-Core
# **
.husky
Servers

View File

@ -9,6 +9,7 @@ process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
const argv = require("minimist")(process.argv.slice(2));
if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true
// Bds Core Imports
const bds = require("../index");
const SystemInfo = require("../lib/BdsSystemInfo");
const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings");

86
bin/bds_maneger/menus.js Normal file
View File

@ -0,0 +1,86 @@
// Import Node Modules
const fs = require("fs");
// Import external modules
const inquirer = require("inquirer");
// Bds Core
const { getBdsConfig } = require("../../index");
const { GetPaths } = require("../../lib/BdsSettings");
const GetPlayers = (Platform = getBdsConfig().server.platform) => [...JSON.parse(fs.readFileSync(GetPaths("player"), "utf8"))[Platform]];
async function TpMenu() {
const { BdsRun } = require("../../src/BdsManegerServer");
const playerList = GetPlayers().map(player => player.Player && player.Action === "connect" ? player.Player : null).filter(a => a);
// Check if there are players online
if (playerList.length > 0) {
const Player = await inquirer.prompt([
{
type: "list",
name: "player",
message: "Select a player",
choices: playerList
}
]);
// Ask X, Y and Z Cordinates
const cords = await inquirer.prompt([
{
type: "input",
name: "x",
message: "X Cordinate",
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return "Please enter a number";
}
},
{
type: "input",
name: "y",
message: "Y Cordinate",
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return "Please enter a number";
}
},
{
type: "input",
name: "z",
message: "Z Cordinate",
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return "Please enter a number";
}
}
]);
return BdsRun.tp(Player.player, {
x: parseInt(cords.x),
y: parseInt(cords.y),
z: parseInt(cords.z)
});
} else throw new Error("No players online");
}
async function Command() {
const { BdsRun } = require("../../src/BdsManegerServer");
const Command = await inquirer.prompt([
{
type: "input",
name: "command",
message: "Enter a command"
}
]);
return BdsRun.command(Command.command);
}
module.exports.Command = Command;
module.exports.TpMenu = TpMenu;
TpMenu();

115
bin/bds_maneger_v2.js Normal file
View File

@ -0,0 +1,115 @@
#!/usr/bin/env node
if (process.platform === "win32") process.title = "Bds Maneger CLI"; else process.title = "Bds-Manger-CLI";
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
// External Modules
const cli_color = require("cli-color");
const serverline = require("serverline");
const inquirer = require("inquirer");
// Bin Args
const ProcessArgs = require("minimist")(process.argv.slice(2));
// Import Bds Core
const BdsCore = require("../index");
const BdsReq = require("../lib/Requests");
const BdsExtraInfo = require("../BdsManegerInfo.json");
const commandExits = require("../lib/commandExist")
// Async functiona
async function Runner() {
// ESM Modules
const ora = (await import("ora")).default;
// Update Bds Core Platform
if (ProcessArgs.platform || ProcessArgs.p) {
const UpdatePla = ora("Updating Bds Platform").start();
try {
BdsCore.platform_update(ProcessArgs.platform || ProcessArgs.p);
UpdatePla.succeed(`Now the platform is the ${ProcessArgs.platform || ProcessArgs.p}`);
} catch (error) {
UpdatePla.fail(`Unable to update platform to ${ProcessArgs.platform || ProcessArgs.p}`);
process.exit(1);
}
}
// Print Info about Bds Core and Platforms
if (ProcessArgs.info || ProcessArgs.i) {
const { valid_platform } = await (require("../lib/BdsSystemInfo"))();
var checkothearch = "";
if (process.platform === "linux" && BdsCore.arch !== "x64"){checkothearch = `qemu-x86_64-static is installed to emulate an x64 system: ${commandExits("qemu-x86_64-static")}\n`}
if (process.platform === "android" && BdsCore.arch !== "x64"){checkothearch = `qemu-x86_64 is installed to emulate an x64 system: ${commandExits("qemu-x86_64")}\n`}
const help = [
`Bds Maneger Core And Bds Maneger CLI version: ${cli_color.magentaBright(BdsCore.package_json.version)}`,
`System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(BdsCore.arch)}`,
checkothearch,
"**************************************************************",
"* Servers currently available:",
`* - Bedrock: ${valid_platform.bedrock}`,
`* - Pocketmine-MP: ${valid_platform.pocketmine}`,
`* - Dragonfly: ${valid_platform.dragonfly}`,
`* - Java: ${valid_platform.java}`,
`* - Spigot: ${valid_platform.java}`,
"*",
"**************************************************************"
];
console.log(cli_color.whiteBright(help.join("\n").replace(/true/gi, cli_color.greenBright("true")).replace(/false/gi, cli_color.redBright("false")).replace(/undefined/gi, cli_color.red("undefined"))));
// End
return;
}
// Download
if (ProcessArgs.download || ProcessArgs.d) {
const VersionList = Object.getOwnPropertyNames((await BdsReq.json(BdsExtraInfo.Fetchs.servers))[BdsCore.BdsSettigs.GetPlatform()]).map(version => ({
name: `${BdsCore.BdsSettigs.GetPlatform()}: v${version}`,
value: version,
}))
if ((ProcessArgs.download || ProcessArgs.d) === true || (ProcessArgs.download || ProcessArgs.d) === "latest") ProcessArgs.d = ProcessArgs.download = (await inquirer.prompt([
{
type: "list",
name: "download",
message: "Select the platform to download",
choices: VersionList
}
])).download;
const oraDownload = ora(`Downloading ${BdsCore.BdsSettigs.GetPlatform()} on version ${ProcessArgs.d || ProcessArgs.download}`).start();
try {
const DownloadInfo = await BdsCore.download.v2(ProcessArgs.d || ProcessArgs.download, true);
const DownloadSucess = ["Downloaded Successfully"];
if (DownloadInfo.version) DownloadSucess.push(`Version: ${DownloadInfo.version}`);
if (DownloadInfo.data) DownloadSucess.push(`Data: ${DownloadInfo.data}`);
if (DownloadInfo.platform) DownloadSucess.push(`Bds Core Platform: ${DownloadInfo.platform}`);
oraDownload.succeed(DownloadSucess.join(", "))
} catch (error) {
oraDownload.fail(error.message);
process.exit(1);
}
}
if (!(ProcessArgs.start || ProcessArgs.s)) return;
// Start
const BdsCoreStart = BdsCore.start();
BdsCoreStart.log(data => console.log(cli_color.blueBright(data.replace(/\n$/gi, ""))));
BdsCoreStart.exit(code => {
console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsCoreStart.uptime}`));
process.exit(code);
});
serverline.init();
serverline.setCompletion(["tp"]);
serverline.setPrompt("Command > ");
serverline.on("line", async function(line) {
if (/^@/.test(line)) {
console.log("🤪It's not working yet!");
// const command = (await inquirer.prompt([
// {
// type: "list",
// name: "command",
// message: "Select the command to run",
// choices: ["tp", "stop", "restart", "update", "info", "download"]
// }
// ])).command;
} else BdsCoreStart.command(line);
});
}
Runner();

View File

@ -5,7 +5,7 @@ const fs = require("fs");
const { randomUUID } = require("crypto");
const { bds_dir } = require("./lib/BdsSettings");
if (typeof fetch === "undefined") global.fetch = require("node-fetch");
require("./lib/Requests")
const bds_core_package = resolve(__dirname, "package.json")
module.exports.package_path = bds_core_package

View File

@ -1,7 +1,6 @@
const { join, resolve, basename } = require("path");
const { existsSync, writeFileSync, mkdirSync, readFileSync } = require("fs");
const { homedir } = require("os");
const BdsInfo = require("./BdsSystemInfo");
const yaml = require("js-yaml");
// PATHs
@ -9,19 +8,6 @@ const home = homedir();
const bds_dir = join(home, "bds_core");
if (!(existsSync(bds_dir))) mkdirSync(bds_dir, {recursive: true})
BdsInfo().then(validation => {
const { valid_platform } = validation;
// Set default platform for bds maneger
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 throw new Error("We cannot run any platforms on this system/device");
UpdatePlatform(default_platformConfig);
}).catch(err => {
console.log(err);
process.exit(1);
});
// Config Base to Bds Maneger Core and others Projects
var Config = {
@ -50,7 +36,6 @@ var Config = {
bedrock: null,
java: null,
pocketmine: null,
jsprismarine: null,
spigot: null,
},
Settings: {
@ -116,12 +101,12 @@ var Config = {
// Config
const ConfigPath = join(resolve(homedir(), "bds_core"), "BdsConfig.yaml")
function SaveConfig(){writeFileSync(ConfigPath, yaml.dump(Config));}
if (existsSync(ConfigPath)) Config = {
...Config,
...yaml.load(readFileSync(ConfigPath, "utf8"))
}; else writeFileSync(ConfigPath, yaml.dump(Config))
process.on("exit", () => SaveConfig())
const SaveConfig = () => writeFileSync(ConfigPath, yaml.dump(Config));
process.on("exit", () => SaveConfig());
if (existsSync(ConfigPath)) Config = yaml.load(readFileSync(ConfigPath, "utf8"));
else writeFileSync(ConfigPath, yaml.dump(Config))
// Paths
if (!(existsSync(Config.paths["backups"]))) mkdirSync(Config.paths["backups"], {recursive: true})
@ -155,6 +140,7 @@ function GetPaths(path = null){
function GetServerPaths(path = null){
if (!(path)) throw new Error("Set path to get");
if (!(ServersPaths[path])) throw new Error("Put a valid path: " + Object.getOwnPropertyNames(ServersPaths).join(", "));
if (path === "all") return ServersPaths
return ServersPaths[path]
}
@ -168,21 +154,20 @@ function UpdateServerVersion(version = null, platform = Config.server.platform){
}
// Update the entire Bds Manager Core platform
function UpdatePlatform(platform = Config.server.platform){
function UpdatePlatform(platform = "null"){
platform = platform.toLocaleLowerCase();
if (/bedrock/.test(platform)) {
Config.server.platform = "bedrock";
SaveConfig()
} else if (/java/.test(platform)) {
Config.server.platform = "java";
SaveConfig()
} else if (/pocketmine/.test(platform)) {
Config.server.platform = "pocketmine";
SaveConfig()
} else if (/spigot/.test(platform)) {
Config.server.platform = "spigot";
SaveConfig()
} else throw new Error("platform no Exists")
} else if (/dragonfly/.test(platform)) {
Config.server.platform = "dragonfly";
} else throw new Error("platform no exists");
SaveConfig();
return platform
}
@ -275,6 +260,7 @@ if (!(existsSync(GetPaths("player")))) {
module.exports = {
bds_dir: bds_dir,
ServersPaths: ServersPaths,
GetJsonConfig,
GetPaths,
GetServerPaths,

View File

@ -35,7 +35,7 @@ async function CheckSystemAsync() {
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'");
// console.warn("The Minecraft Bedrock Server is only being validated because you can use 'qemu-x86_64-static'");
valid_platform["bedrock"] = true
require_qemu = true
}

984
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -59,19 +59,23 @@
"express-prettify": "^0.1.1",
"express-rate-limit": "^5.2.3",
"googleapis": "^87.0.0",
"inquirer": "^8.1.5",
"js-yaml": "^4.1.0",
"minimist": "^1.2.5",
"node-cron": "^3.0.0",
"node-fetch": "^3.0.0",
"oci-sdk": "^2.0.0",
"open": "^8.0.0",
"ora": "^6.0.1",
"properties-to-json": "^0.2.1",
"request-ip": "^2.1.3",
"serverline": "^1.5.0",
"telegraf": "^4.0.0"
},
"devDependencies": {
"docker-run_build": "*",
"eslint": "^7.19.0",
"nodemon": "^2.0.12"
"nodemon": "^2.0.12",
"os-tmpdir": "^2.0.0"
}
}

View File

@ -72,6 +72,7 @@ function start() {
else if (GetPlatform() === "pocketmine") {
// Start PocketMine-MP
SetupCommands.command = path.join(path.resolve(GetServerPaths("pocketmine"), "bin", "php7", "bin"), "php");
if (process.platform === "win32") SetupCommands.command = path.join(path.resolve(GetServerPaths("pocketmine"), "bin/php"), "php.exe");
SetupCommands.args.push("./PocketMine-MP.phar");
SetupCommands.cwd = GetServerPaths("pocketmine");
}
@ -85,22 +86,6 @@ function start() {
env: SetupCommands.env
});
// Post Start
if (GetPlatform() === "java") {
const eula_file_path = path.join(GetServerPaths("java"), "eula.txt");
if (fs.existsSync(eula_file_path)) {
const eula_file = fs.readFileSync(eula_file_path, "utf8");
console.log(eula_file);
if (eula_file.includes("eula=false")) {
fs.writeFileSync(eula_file_path, eula_file.replace(/eula=false/gi, "eula=true"));
throw new Error("Restart application/CLI")
}
} else {
console.log("EULA file not found");
throw new Error("EULA file not found")
}
}
// Log file
const LogFile = path.join(GetPaths("log"), `${GetPlatform()}_${new Date().toString().replace(/:|\(|\)/g, "_")}_Bds_log.log`);
const LatestLog_Path = path.join(GetPaths("log"), "latest.log");

View File

@ -1,5 +1,9 @@
const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = require("fs");
const { join, resolve, basename } = require("path");
const child_process = require("child_process");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = fs;
const { join, resolve } = path;
var AdmZip = require("adm-zip");
const BdsInfo = require("../lib/BdsSystemInfo");
const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../lib/BdsSettings");
@ -23,14 +27,14 @@ module.exports = function (version = true, force_install = false, callback = (er
// JSON Configs and others
const ServerVersion = GetServerVersion();
const CurrentPlatform = GetPlatform();
if (typeof version === "boolean" || /true|latest/gi.test(version)) version = Servers.latest[CurrentPlatform]
if (typeof version === "boolean" || /true|latest/gi.test(`${version}`.toLocaleLowerCase())) version = Servers.latest[CurrentPlatform];
// Donwload
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") callback(undefined, true);
@ -190,8 +194,9 @@ module.exports = function (version = true, force_install = false, callback = (er
// Unidentified platform
else {
promise_reject(Error("Bds maneger Config file error"));
if (typeof callback === "function") callback(err);
const Err = Error("Bds maneger Config file error");
promise_reject(Err);
if (typeof callback === "function") callback(Err);
}
} catch (err) {
promise_reject(err);
@ -208,6 +213,180 @@ module.exports = function (version = true, force_install = false, callback = (er
});
}
// New Download Method
module.exports.v2 = async (version = true) => {
const CurrentPlatform = GetPlatform();
const valid_platform = (await BdsInfo()).valid_platform;
const LocalServersVersions = bds.BdsSettigs.GetServerVersion();
const { ServersPaths } = bds.BdsSettigs;
// Load Version List
const ServerDownloadJSON = await Request.json(Extra.Fetchs.servers);
// Check is latest version options or boolean
if (typeof version === "boolean" || /true|false|latest/.test(`${version}`.toLocaleLowerCase())) version = ServerDownloadJSON.latest[CurrentPlatform];
if (!version) throw Error("No version found");
const ReturnObject = {
version: version,
platform: CurrentPlatform,
url: "",
data: "",
skip: false
}
// Bedrock
if (CurrentPlatform === "bedrock") {
if (valid_platform.bedrock) {
if (LocalServersVersions.bedrock !== version) {
// Add info to ReturnObject
ReturnObject.url = ServerDownloadJSON.bedrock[version][bds.arch][process.platform];
ReturnObject.data = ServerDownloadJSON.bedrock[version].data;
// Download and Add buffer to AdmZip
const BedrockZip = new AdmZip(await Request.buffer(ReturnObject.url));
// Create Backup Bedrock Config
const BedrockConfigFiles = {
proprieties: "",
whitelist: "",
permissions: "",
}
// Get Bedrock Config Files
if (fs.existsSync(path.join(ServersPaths.bedrock, "bedrock_server.properties"))) BedrockConfigFiles.proprieties = fs.readFileSync(path.join(ServersPaths.bedrock, "bedrock_server.properties"), "utf8");
if (fs.existsSync(path.join(ServersPaths.bedrock, "whitelist.json"))) BedrockConfigFiles.whitelist = fs.readFileSync(path.join(ServersPaths.bedrock, "whitelist.json"), "utf8");
if (fs.existsSync(path.join(ServersPaths.bedrock, "permissions.json"))) BedrockConfigFiles.permissions = fs.readFileSync(path.join(ServersPaths.bedrock, "permissions.json"), "utf8");
// Extract to Bedrock Dir
BedrockZip.extractAllTo(ServersPaths.bedrock, true);
// Write Bedrock Config Files
if (BedrockConfigFiles.proprieties) fs.writeFileSync(path.join(ServersPaths.bedrock, "bedrock_server.properties"), BedrockConfigFiles.proprieties, "utf8");
if (BedrockConfigFiles.whitelist) fs.writeFileSync(path.join(ServersPaths.bedrock, "whitelist.json"), BedrockConfigFiles.whitelist, "utf8");
if (BedrockConfigFiles.permissions) fs.writeFileSync(path.join(ServersPaths.bedrock, "permissions.json"), BedrockConfigFiles.permissions, "utf8");
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Bedrock not suported");
}
}
// Java
else if (CurrentPlatform === "java") {
if (valid_platform.java) {
if (LocalServersVersions.java !== version) {
// Add info to ReturnObject
ReturnObject.url = ServerDownloadJSON.java[version].url;
ReturnObject.data = ServerDownloadJSON.java[version].data;
// Download and write java file
const JavaBufferJar = await Request.buffer(ReturnObject.url);
fs.writeFileSync(path.join(ServersPaths.java, "MinecraftServerJava.jar"), JavaBufferJar, "binary");
// Write EULA
fs.writeFileSync(path.join(ServersPaths.java, "eula.txt"), "eula=true");
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Java not suported");
}
}
// Spigot
else if (CurrentPlatform === "spigot") {
if (valid_platform.spigot) {
if (LocalServersVersions.spigot !== version) {
// Add info to ReturnObject
const FindedSpigot = ServerDownloadJSON.spigot.findOne(spigot => spigot.version === version);
ReturnObject.url = FindedSpigot.url;
ReturnObject.data = FindedSpigot.data;
// Download and write java file
fs.writeFileSync(path.join(ServersPaths.spigot, "spigot.jar"), await Request.buffer(ReturnObject.url), "binary");
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Spigot not suported");
}
}
// Dragonfly
else if (CurrentPlatform === "dragonfly") {
if (valid_platform.dragonfly) {
if (LocalServersVersions.dragonfly !== version) {
// Add info to ReturnObject
ReturnObject.url = "https://github.com/df-mc/dragonfly/tree/master";
ReturnObject.data = "";
// Build Dragonfly
const TmpDragonflyDir = path.join(os.tmpdir(), `dragonfly_${Math.random().toString(36).substring(7)}`);
child_process.execFileSync("git", ["clone", "https://github.com/df-mc/dragonfly", "--depth", "1", TmpDragonflyDir]);
let DragonflyPackageOut = path.join(ServersPaths.dragonfly, "DragonFly");
if (process.platform === "win32") DragonflyPackageOut += ".exe";
child_process.execFileSync("go", ["build", "-o", DragonflyPackageOut], {cwd: TmpDragonflyDir});
// move Dragonfly to ServersPaths
fs.renameSync(DragonflyPackageOut, path.join(ServersPaths.dragonfly, path.basename(DragonflyPackageOut)));
// Remove Build Dir
fs.rmSync(TmpDragonflyDir, {recursive: true, force: true});
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(Math.random().toString(), CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Dragonfly not suported");
}
}
// Pocketmine-MP
else if (CurrentPlatform === "pocketmine") {
if (valid_platform.pocketmine) {
if (LocalServersVersions.pocketmine !== version) {
// Add info to ReturnObject
ReturnObject.url = ServerDownloadJSON.pocketmine[version].url;
ReturnObject.data = ServerDownloadJSON.pocketmine[version].data;
// Download PHP Bin
await php_download();
// Download php file and save
const PocketmineBufferPhp = await Request.buffer(ReturnObject.url);
fs.writeFileSync(path.join(ServersPaths.pocketmine, "PocketMine-MP.phar"), PocketmineBufferPhp, "binary");
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Pocketmine-MP not suported");
}
}
// if the platform does not exist
else throw Error("No Valid Platform");
// Return info download
return ReturnObject;
}
// Php download and install
async function php_download() {
const bds_dir_pocketmine = GetServerPaths("pocketmine");
const PHPBin = (await (await fetch(Extra.Fetchs.php)).json());
@ -222,17 +401,13 @@ async function php_download() {
// Remove Old php Binary if it exists
if (existsSync(phpFolder)) {
console.log("Removing old PHP files.");
rmSync(phpFolder, { recursive: true });
}
console.log(`Downloading ${urlPHPBin}`);
const ZipBuffer = Buffer.from((await (await fetch(urlPHPBin)).arrayBuffer()));
console.log(`${basename(urlPHPBin)} downloaded`);
console.log(`Extracting ${basename(urlPHPBin)}`);
const zipExtractBin = new AdmZip(ZipBuffer);
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
console.log("Successfully extracting the binaries")
if (process.platform === "win32") return resolve();
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8");
if (!(existsSync(phpExtensiosnsDir))) return true;