Remove fist API Routes and Modifications to CLI #239

Merged
Sirherobrine23 merged 5 commits from API-And-CLI into main 2021-11-16 02:40:41 +00:00
28 changed files with 2274 additions and 2874 deletions

View File

@ -30,10 +30,3 @@ describe("Small functions", () => {
done();
});
});
describe("Slow Functions", function () {
it ("Download Server", async function () {
this.timeout(60 * 1000);
await BdsCore.download_server();
});
});

38
.vscode/launch.json vendored
View File

@ -1,24 +1,18 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "API",
"program": "${workspaceFolder}/bin/bds_maneger.js",
"args": ["-sk"]
},
{
"type": "node",
"request": "launch",
"name": "Start Telegram bot dev",
"program": "${workspaceFolder}/bin/telegram_bot.js"
},
{
"type": "node",
"request": "launch",
"name": "Docker Build and Run",
"program": "${workspaceFolder}/.Build/DockerImage.js",
}
]
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Start Index",
"program": "${workspaceFolder}/index.js"
},
{
"type": "pwa-node",
"request": "launch",
"name": "API",
"program": "${workspaceFolder}/bin/bds_maneger.js",
"args": ["-sk"]
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"files.eol": "\n"
}

View File

@ -1,142 +1,135 @@
{
"docs_base": "https://docs.bdsmaneger.com/docs/Bds Maneger core",
"docs": {
"url": "https://docs.bdsmaneger.com",
"main": "Bds Maneger core",
"rest_api": "docs/Bds Maneger core/REST API/"
"temp_host": {
"url": "http://hosts.bdsmaneger.com:3020"
},
"Fetchs": {
"php": "https://raw.githubusercontent.com/The-Bds-Maneger/Php_Static_Binary/main/binarys.json"
},
"IgnoreLog": {
"bedrock": [
{
"value": "Running AutoCompaction",
"regex": true
}
],
"java": [],
"pocketmine": [],
"spigot": [],
"dragonfly": []
},
"StartedServer": {
"bedrock": {
"value": "Server started",
"regex": true
},
"temp_host": {
"url": "http://hosts.bdsmaneger.com:3020"
"java": {
"value": null,
"regex": false
},
"Fetchs": {
"php": "https://raw.githubusercontent.com/The-Bds-Maneger/Php_Static_Binary/main/binarys.json",
"servers": "https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Server.json"
"pocketmine": {
"value": null,
"regex": false
},
"IgnoreLog": {
"bedrock": [
{
"value": "Running AutoCompaction",
"regex": true
}
],
"java": [],
"pocketmine": [],
"spigot": [],
"dragonfly": []
"spigot": {
"value": null,
"regex": false
},
"StartedServer": {
"bedrock": {
"value": "Server started",
"regex": true
},
"java": {
"value": null,
"regex": false
},
"pocketmine": {
"value": null,
"regex": false
},
"spigot": {
"value": null,
"regex": false
},
"dragonfly": {
"value": null,
"regex": false
}
"dragonfly": {
"value": null,
"regex": false
}
},
"Servers": {
"bedrock": {
"stop": {
"value": "stop",
"type": "command"
},
"op": {
"value": "op \"{{}}\"",
"type": "command"
},
"deop": "op \"{{Player}}\"",
"ban": "tp \"{{Player}}\" ~ ~99999 ~",
"kick": "kick \"{{Player}}\" \"{{Text}}\"",
"tp": "tp \"{{Player}}\" {{X}} {{Y}} {{X}}",
"say": "say {{Text}}"
},
"Servers": {
"bedrock": {
"stop": {
"value": "stop",
"type": "command"
},
"op": {
"value": "op \"{{}}\"",
"type": "command"
},
"deop": "op \"{{Player}}\"",
"ban": "tp \"{{Player}}\" ~ ~99999 ~",
"kick": "kick \"{{Player}}\" \"{{Text}}\"",
"tp": "tp \"{{Player}}\" {{X}} {{Y}} {{X}}",
"say": "say {{Text}}"
},
"java": {
"stop": "stop",
"op": "op {{Player}}",
"deop": "op {{Player}}",
"ban": "ban {{Player}}",
"kick": "kick {{Player}} {{Text}}",
"tp": "tp {{Player}} {{X}} {{Y}} {{X}}",
"say": "say {{Text}}"
},
"pocketmine": {
"stop": {
"value": "stop",
"type": "command"
},
"op": {
"value": "op {{Player}}",
"type": "command"
},
"deop": {
"value": "deop {{Player}}",
"type": "command"
},
"ban": {
"value": "ban {{Player}}",
"type": "command"
},
"kick": {
"value": "kick {{Player}}",
"type": "command"
},
"tp": {
"value": "tp {{Player}} {{X}} {{Y}} {{X}}",
"type": "command"
},
"say": {
"value": "say {{Text}}",
"type": "command"
}
},
"dragonfly": {
"stop": {
"value": "SIGNKILL",
"type": "process"
},
"op": {
"value": null,
"type": null
},
"deop": {
"value": null,
"type": null
},
"ban": {
"value": null,
"type": null
},
"kick": {
"value": null,
"type": null
},
"tp": {
"value": null,
"type": null
},
"say": {
"value": null,
"type": null
}
}
"java": {
"stop": "stop",
"op": "op {{Player}}",
"deop": "op {{Player}}",
"ban": "ban {{Player}}",
"kick": "kick {{Player}} {{Text}}",
"tp": "tp {{Player}} {{X}} {{Y}} {{X}}",
"say": "say {{Text}}"
},
"contributors": [
{
"name": "Matheus Sampaio Queiroga",
"email": "srherobrine20@gmail.com",
"url": "https://sirherobrine23.org/?from=the-bds-maneger-project"
}
]
"pocketmine": {
"stop": {
"value": "stop",
"type": "command"
},
"op": {
"value": "op {{Player}}",
"type": "command"
},
"deop": {
"value": "deop {{Player}}",
"type": "command"
},
"ban": {
"value": "ban {{Player}}",
"type": "command"
},
"kick": {
"value": "kick {{Player}}",
"type": "command"
},
"tp": {
"value": "tp {{Player}} {{X}} {{Y}} {{X}}",
"type": "command"
},
"say": {
"value": "say {{Text}}",
"type": "command"
}
},
"dragonfly": {
"stop": {
"value": "SIGNKILL",
"type": "process"
},
"op": {
"value": null,
"type": null
},
"deop": {
"value": null,
"type": null
},
"ban": {
"value": null,
"type": null
},
"kick": {
"value": null,
"type": null
},
"tp": {
"value": null,
"type": null
},
"say": {
"value": null,
"type": null
}
}
},
"contributors": [
{
"name": "Matheus Sampaio Queiroga",
"email": "srherobrine20@gmail.com",
"url": "https://sirherobrine23.org/?from=the-bds-maneger-project"
}
]
}

View File

@ -31,11 +31,7 @@ We have a separate repository for all Bds Maneger Project documentation, [link h
All options can be found in the bds maneger core documentation.
`npx --package=@the-bds-maneger/core@latest bds_maneger -sk`
### Telegram Bot
`npx --package=@the-bds-maneger/core@latest bds_telegram`
`npx @the-bds-maneger/core@latest -sk`
## Install Bds Maneger Core globally

94
bin/bds_maneger.js → bin/BdsManeger.js Executable file → Normal file
View File

@ -1,6 +1,9 @@
#!/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;
// Internal Modules
const fs = require("fs");
const path = require("path");
// External Modules
const cli_color = require("cli-color");
@ -14,10 +17,37 @@ const BdsCore = require("../index");
const BdsNetwork = require("../src/BdsNetwork");
const commandExits = require("../lib/commandExist");
const readline = require("readline");
// const BdsMenus = require("./bds_maneger/menus");
const { PlatformVersionsV2 } = require("../src/BdsServersDownload");
const { GetPlatform } = require("../lib/BdsSettings");
// Load Bds Maneger CLI Plugins
const MoreHelp = [];
const BeforeRun = [];
fs.readdirSync(path.join(__dirname, "plugins")).map(file => path.resolve(__dirname, "plugins", file)).filter(Mod => fs.lstatSync(Mod).isFile() && Mod.endsWith(".js")).forEach(Plugin => {
try {
const __module = require(Plugin);
(__module.Args || []).forEach(PluginArg => {
["h", "help", "i", "info", "d", "download", "s", "start", "k", "kill", "get_domain", "p", "platform", "n", "no-api"].forEach(Arg => {
if (PluginArg.arg === Arg) {
console.log(cli_color.redBright(`${path.basename(Plugin).replace(/\.js$/gi, "")}:`, "Conflicted with Bds Maneger CLI argument"));
process.exit(12);
}
});
BeforeRun.forEach(Arg => {
if (PluginArg.arg === Arg) {
console.log(cli_color.redBright(`${path.basename(Plugin).replace(/\.js$/gi, "")}:`, "Conflicted with another plugin argument"));
process.exit(13);
}
});
BeforeRun.push(PluginArg);
});
MoreHelp.push(cli_color.redBright(`Plugin: ${path.basename(Plugin).replace(/\.js$/gi, "")} - ${__module.description}`), "", ...(__module.help || []), "");
} catch (err) {
console.log(cli_color.redBright(`Error loading plugin: ${Plugin}`));
console.log(cli_color.redBright(err));
}
});
async function DownloadServer() {
const ora = (await import("ora")).default;
const PlatformVersion = await PlatformVersionsV2()
@ -64,27 +94,33 @@ async function help() {
const help = [
`Bds Maneger CLI version: ${cli_color.magentaBright(BdsCore.package_json.version)}`,
`System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(BdsCore.arch)}`,
"**************************************************************",
"* Usage: bds-maneger-cli [options]",
"*",
"* Options:",
"* -h, --help Print this help",
"* -i, --info Print info about Bds Maneger Core and Platforms",
"* -d, --download Download a server",
"* -s, --start Start a server",
"* --get_domain Get temporary public domain to connect in to server or API",
"* -p, --platform Change the platform",
"* -n, --no-api Don't start the Bds Maneger API Rest",
"*",
"* Examples:",
"* bds-maneger-cli -d",
"* bds-maneger-cli -s",
"* bds-maneger-cli -p bedrock",
"* bds-maneger-cli -i",
"* bds-maneger-cli -h",
"**************************************************************"
"",
" Usage: bds-maneger-cli [options]",
"",
" Options:",
" -h, --help Print this help",
" -i, --info Print info about Bds Maneger Core and Platforms",
" -d, --download Download a server",
" -s, --start Start a server",
" -k, --kill Kill Server if running",
" --get_domain Get temporary public domain to connect in to server or API",
" -p, --platform Change the platform",
" -n, --no-api Don't start the Bds Maneger API Rest",
"",
...MoreHelp,
"",
" Examples:",
" bds-maneger-cli -d",
" bds-maneger-cli -s",
" bds-maneger-cli -sk",
" bds-maneger-cli -k",
" bds-maneger-cli -p bedrock",
" bds-maneger-cli -i",
" bds-maneger-cli -h",
""
];
return 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"))));
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"))));
return process.exit(0);
}
// Async functiona
@ -136,13 +172,19 @@ async function Runner() {
}
}
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}`));
// Load Plugins
for (let Plugin of BeforeRun) {
if (!(ProcessArgs[Plugin.arg])) Plugin.main(ProcessArgs[Plugin.arg], ProcessArgs).catch(err => console.log("Plugin Crash:", "\n\n", err));
}
const BdsManegerServer = BdsCore.start();
BdsManegerServer.log(data => console.log(cli_color.blueBright(data.replace(/\n$/gi, ""))));
BdsManegerServer.exit(code => {
console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsManegerServer.uptime}`));
process.exit(code);
});
if (!(ProcessArgs["no-api"])) BdsCore.api();
readline
const __readline = readline.createInterface({input: process.stdin, output: process.stdout});
__readline.on("line", data => BdsManegerServer.command(data));
}
Runner();

View File

@ -1,85 +0,0 @@
// 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;

View File

@ -1,215 +0,0 @@
#!/usr/bin/env node
const readline = require("readline");
const cli_color = require("cli-color");
const BdsConfigAndInfo = require("../BdsManegerInfo.json");
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;
// Bds Maneger ArgV
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");
const commandExits = require("../lib/commandExist");
const download = require("../src/BdsServersDownload");
// Options
const
server = (argv.p || argv.platform),
version = (argv.v || argv.version),
SystemCheck = (argv.S || argv.system_info),
bds_version = (argv.d || argv.download),
start = (argv.s || argv.server_version),
help = (argv.h || argv.help),
kill = (argv.k || argv.kill);
// --------------------------
const Versions = GetServerVersion();
// Bds kill
if (kill) bds.kill();
// Set Bds Platform
if (server) {
console.log(cli_color.yellow(`Set Platform: ${server}`));
UpdatePlatform(server);
}
// Start Server
async function StartServer(){
const Servers = (await (await fetch(BdsConfigAndInfo.Fetchs.servers)).json());
// Check Server Update
if (Versions[GetPlatform()] !== null) {
if (Versions[GetPlatform()] !== Servers.latest[GetPlatform()]) {
const message = [
`Hello, I have a little warning, There is a new version of ${GetPlatform()}, going from version ${GetServerVersion[GetPlatform()]} to ${Servers.latest[GetPlatform()]}`,
"And we strongly recommend keeping the servers up to date, to maintain compatibility between game versions.",
`At any time you can update using the options -p ${GetPlatform()} -d "${Servers.latest[GetPlatform()]}"`
]
console.log(cli_color.yellow(message.join("\n")));
}
} else if (Versions[GetPlatform()] === null) {
console.log(cli_color.red("Install Server"));
process.exit(1)
}
try {
console.log(cli_color.yellow("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(data => process.stdout.write(cli_color.cyan(data)));
bds_server.exit(function (code){
if (code === 3221225781 && process.platform === "win32") {
console.log(cli_color.red("Open the url: https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll"));
return open("https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll");
}
console.log(cli_color.red(`"leaving the server, status code: ${code}"`));
process.exit(code);
});
// CLI Commands
const rl = readline.createInterface({input: process.stdin,output: process.stdout});
rl.on("line", (input) => {
// Stop
if (input.trim() === "@stop") {
rl.close();
bds_server.stop()
}
// Server input
else bds_server.command(input);
});
rl.on("close", ()=>{
console.log(cli_color.redBright("stopping server"));
bds_server.stop();
})
bds_server.exit(function(c){
if (c !== 0) rl.close();
})
bds.api();
} catch (err) {
console.log(cli_color.redBright(`Bds Maneger Start Server Error: \n******\n${err}`));
process.exit(2)
}
}
(async () => {
// Bds Maneger CLI Help
if (help) {
let help = [
"usage: bds_maneger [options]",
"",
"options:",
" -s --start Start Server",
" -k --kill Detect and kill bds servers",
" -p --platform Select server platform",
" -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.",
" -v --version Print the version and exit."
]
console.log(cli_color.yellow(help.join("\n")));
process.exit();
}
// Get Bds Core Version
if (version) {
const Info = [
`Bds Maneger Core version: ${bds.package_json.version}`,
"",
"****************** Bds Maneger Core contributors ******************",
"",
]
for (let contri of bds.extra_json.contributors) {
Info.push(`********* ${contri.name} *********`)
if (contri.email) Info.push(`* ${contri.email}`)
if (contri.url) Info.push(`* ${contri.url}`)
Info.push("*")
Info.push("*********")
}
console.log(Info.join("\n"));
process.exit();
}
if (SystemCheck) {
const { valid_platform } = await SystemInfo();
var checkothearch = "";
if (process.platform === "linux" && bds.arch !== "x64"){checkothearch = `qemu-x86_64-static is installed to emulate an x64 system: ${commandExits("qemu-x86_64-static")}\n`}
if (process.platform === "android" && bds.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(bds.package_json.version)}`,
`System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(bds.arch)}`,
checkothearch,
"**************************************************************",
"* Bds Maneger dirs:",
`* - Config: ${cli_color.yellowBright(bds_dir)}`,
`* - Players File: ${cli_color.yellowBright(GetPaths("player"))}`,
"*",
"* Bds Servers dirs:",
`* - Bedrock Server: ${cli_color.yellowBright(GetServerPaths("bedrock"))}`,
`* - Pocketmine-MP Server: ${cli_color.yellowBright(GetServerPaths("pocketmine"))}`,
`* - Dragonfly: ${cli_color.yellowBright(GetServerPaths("dragonfly"))}`,
`* - Java Server: ${cli_color.yellowBright(GetServerPaths("java"))}`,
`* - Spigot Server: ${cli_color.yellowBright(GetServerPaths("spigot"))}`,
"*",
"**************************************************************",
"* 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"))
));
process.exit(0)
}
// Download server
if (bds_version){
(async () => {
try {
if (argv.interactive) {
const LoadVersion = (await (await fetch(BdsConfigAndInfo.Fetchs.servers)).json())[GetPlatform()]
const Version = Object.getOwnPropertyNames(LoadVersion)
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(`${cli_color.red("Option")} ${cli_color.green("Version")}`);
for (let option in Version) console.log(`${cli_color.red(parseInt(option) + 1)}: ${cli_color.green(Version[option])}`);
StartQuestion(readline.createInterface({input: process.stdin,output: process.stdout}));
}
else bds.download(bds_version, true, function(){
if (start) StartServer();
})
} catch (error) {console.error(error);process.exit(165);}
})();
}
// Start server
if (start && !(server || version || SystemCheck || bds_version || help)) StartServer();
})()

314
bin/plugins/TelegramBot.js Normal file
View File

@ -0,0 +1,314 @@
const fs = require("fs");
const { Telegraf, Markup } = require("telegraf");
const bds = require("../../index");
const { GetPlatform, GetPaths, GetTelegramToken, UpdateTelegramToken } = require("../../lib/BdsSettings");
const { GetKernel, arch, system } = require("../../lib/BdsSystemInfo");
const { Detect } = require("../../src/CheckKill");
const { CheckTelegramUser } = require("../../src/UsersAndtokenChecks");
const BdsInfo = require("../../BdsManegerInfo.json");
// Bot Start And Help messages
const HelpAndStart = [
"Hello, welcome to Bds Maneger Telegram Bot",
"",
"We are changing some things but everything is working!!",
"Options:",
" /start or /help: This message!",
" /basic",
" start, stop, backup",
" /live_log",
" enabler, disabler",
" /live_log",
" /download",
" Version",
" ",
];
// Set Telegram Bot
const bot = new Telegraf(GetTelegramToken());
// Start and Help Command
bot.start((ctx)=>ctx.reply(HelpAndStart.join("\n")));
bot.help((ctx)=>ctx.reply(HelpAndStart.join("\n")));
// User
bot.command("player", ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const Server = global.ServerExec;
const CtxOption = ctx.message.text.replace("/player", "").trim();
const CtxContext = CtxOption.replace(/^kick|^deop|^ban|^op/, "").trim();
if (CtxOption) {
const Players = CtxContext.split(/, |,/gi).filter(a => a.trim());
console.log(Players);
if (/kick/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.kick(Player);
ctx.reply(`${Player} was kicked`);
});
} else ctx.reply("and the Players?")
}
else if (/deop/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.deop(Player);
ctx.reply(`${Player} was deopped`);
});
} else ctx.reply("and the Players?")
}
else if (/ban/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.ban(Player);
ctx.reply(`${Player} was banned`);
});
} else ctx.reply("and the Players?")
}
else if (/op/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.op(Player);
ctx.reply(`${Player} was opped`);
});
} else ctx.reply("and the Players?")
}
else if (/list/.test(CtxOption)){
const Player_Json_path = GetPaths("player");
let Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[GetPlatform()];
const new_players = {};
Players_Json.forEach(Player => {
console.log(Player);
if (new_players[Player.Player]) {
new_players[Player.Player].push([`Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n"));
} else {
new_players[Player.Player] = [
[`Player: ${Player.Player}`, `Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n")
]
}
});
console.log(new_players);
Object.getOwnPropertyNames(new_players).forEach(Player_Array => {
let Length = Math.abs(new_players[Player_Array].length - 5);
let Player = new_players[Player_Array].slice(0, Length).join("\n")
ctx.reply(Player);
});
}
else ctx.reply("Invalid option")
} else {
const ReplyOption = Markup.keyboard([
"/player kick",
"/player deop",
"/player ban",
"/player op",
"/player list",
]).oneTime().resize();
ctx.reply("Player Options:", ReplyOption);
}
});
// Basic server
bot.command("basic", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/basic", "").trim();
if (text) {
// Start Server
if (/start/.test(text)) {
if (Detect()) ctx.reply("Stop Server");
else {
try {
const Server = bds.start();
Server.log(function (data){
for (let stx of global.LiveLog) stx.reply(data);
});
global.ServerExec = Server;
return ctx.reply("Server Started")
} catch (err) {
console.log(err)
ctx.reply("We couldn't start the server")
ctx.reply(err.toString());
}
}
}
// Stop Server
else if (/stop/.test(text)) {
if (Detect()) {
try {
bds.stop()
ctx.reply("Stopping your server")
} catch (err) {
ctx.reply("We had an error for your server");
ctx.reply(err.toString());
}
} else ctx.reply("Your server is stopped")
}
// Backup
else if (/backup/.test(text)) {
const Backup = bds.backup();
ctx.replyWithDocument({
source: Backup.Buffer,
filename: Backup.file_name,
})
}
// Invalid option
else return ctx.reply("Invalid option, they are just: start, stop")
} else {
await ctx.deleteMessage();
const Options = Markup.keyboard([
"/basic start",
"/basic stop",
"/basic backup",
]).oneTime().resize();
ctx.reply("Basic Options", Options);
}
});
// Select Platform
bot.command("platform", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/platform", "").trim();
if (text) {
try {
bds.BdsSettigs.UpdatePlatform(text);
return ctx.reply(`Platform update to ${text}`)
} catch (err) {
ctx.reply("We were unable to change the platform")
return ctx.reply(err.toString())
}
} else {
await ctx.deleteMessage();
const Keyboard = Markup.keyboard([
"/platform bedrock",
"/platform java",
"/platform pocketmine",
"/platform jsprismarine"
]).oneTime().resize();
ctx.reply("Select Platform", Keyboard)
}
});
// Download Server
bot.command("download", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const version = ctx.message.text.replace(/\/download|[a-zA-Z]/gi, "").trim();
if (version) {
await bds.download(version, true);
ctx.reply(`Sucess install ${GetPlatform()} with version ${version}`);
} else {
await ctx.deleteMessage();
const KeyboardVersion = Markup.keyboard(Object.getOwnPropertyNames((await (await fetch(BdsInfo.Fetchs.servers)).json())[GetPlatform()]).map(version => {
return {
text: `/download ${version}`
}
})).oneTime().resize();
ctx.reply("Select Version to Install", KeyboardVersion);
}
});
// Command
bot.command("command", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/command", "").trim();
if (!(Detect())) return ctx.reply("Your server is stopped");
if (text) {
try {
global.ServerExec.command(text);
} catch (err) {
ctx.reply("We couldn't execute the command");
ctx.reply(`${err}`);
}
} else {
await ctx.deleteMessage();
return ctx.reply("/command <command>");
}
});
// Send Info
bot.command("info", ctx => {
const config = bds.get_config();
const InfoRes = [
`Bds Maneger core version: ${bds.package_json.version}`,
`Kernel: ${GetKernel()}`,
`Arch: ${arch}`,
`System: ${system}`,
`Platform: ${GetPlatform()}`,
`World_name: ${config.world}`,
`Running: ${bds.detect()}`,
`Port_V4: ${config.portv4}`,
`Port_V6: ${config.portv6}`,
`Max_players: ${config.players}`,
`Whitelist: ${config.whitelist}`,
]
ctx.reply(InfoRes.join("\n\n"));
});
// Live Log User
global.LiveLog = [];
bot.command("live_log", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const option = ctx.message.text.replace("/live_log", "").trim();
if (option) {
if (/enable/.test(option)) {
global.LiveLog.push(ctx);
return ctx.reply("Sucess");
} else if (/disable/.test(option)) {
// ctx.from.id
for (let ctx_Logs in global.LiveLog) {
if (global.LiveLog[ctx_Logs].from.id === ctx.from.id) {
delete global.LiveLog[ctx_Logs];
global.LiveLog = global.LiveLog.filter(a=>a);
return ctx.reply("Ok");
}
}
return ctx.reply("You are not in the list");
}
}
await ctx.deleteMessage();
const ReplyOption = Markup.keyboard([
"/live_log enable",
"/live_log disable",
]).oneTime().resize();
ctx.reply("Enable/Disabled?", ReplyOption);
});
// text
bot.on("text", ctx => {
console.log(ctx.message.text);
if (!(/\/.*/gi.test(ctx.message.text))) global.ServerExec.command(`say ${ctx.message.text}`)
});
// catch
bot.catch(console.log);
module.exports.description = "Start Bot of Telegram";
module.exports.Args = [
{
arg: "t",
main: async () => bot.launch()
},
{
arg: "telegram",
main: async () => bot.launch()
},
{
arg: "register_telegram_token",
main: async (Token = "") => {
if (!(Token && typeof Token === "string")) throw new Error("Token is not a string");
return UpdateTelegramToken(Token);
}
}
];
module.exports.help = [
" -t, --telegram Start Telegram Bot"
];

View File

@ -1,297 +0,0 @@
#!/usr/bin/env node
const fs = require("fs");
const { Telegraf, Markup } = require("telegraf");
const bds = require("../index");
const { GetPlatform, GetPaths, GetTelegramToken } = require("../lib/BdsSettings");
const { GetKernel, arch, system } = require("../lib/BdsSystemInfo");
const { Detect } = require("../src/CheckKill");
const { CheckTelegramUser } = require("../src/UsersAndtokenChecks");
const BdsInfo = require("../BdsManegerInfo.json");
// Bot Start And Help messages
const HelpAndStart = [
"Hello, welcome to Bds Maneger Telegram Bot",
"",
"We are changing some things but everything is working!!",
"Options:",
" /start or /help: This message!",
" /basic",
" start, stop, backup",
" /live_log",
" enabler, disabler",
" /live_log",
" /download",
" Version",
" ",
];
// Set Telegram Bot
const bot = new Telegraf(GetTelegramToken());
// Start and Help Command
bot.start((ctx)=>ctx.reply(HelpAndStart.join("\n")));
bot.help((ctx)=>ctx.reply(HelpAndStart.join("\n")));
// User
bot.command("player", ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const Server = global.ServerExec;
const CtxOption = ctx.message.text.replace("/player", "").trim();
const CtxContext = CtxOption.replace(/^kick|^deop|^ban|^op/, "").trim();
if (CtxOption) {
const Players = CtxContext.split(/, |,/gi).filter(a => a.trim());
console.log(Players);
if (/kick/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.kick(Player);
ctx.reply(`${Player} was kicked`);
});
} else ctx.reply("and the Players?")
}
else if (/deop/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.deop(Player);
ctx.reply(`${Player} was deopped`);
});
} else ctx.reply("and the Players?")
}
else if (/ban/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.ban(Player);
ctx.reply(`${Player} was banned`);
});
} else ctx.reply("and the Players?")
}
else if (/op/.test(CtxOption)){
if (Players.length >= 1) {
Players.forEach(Player => {
Server.op(Player);
ctx.reply(`${Player} was opped`);
});
} else ctx.reply("and the Players?")
}
else if (/list/.test(CtxOption)){
const Player_Json_path = GetPaths("player");
let Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[GetPlatform()];
const new_players = {};
Players_Json.forEach(Player => {
console.log(Player);
if (new_players[Player.Player]) {
new_players[Player.Player].push([`Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n"));
} else {
new_players[Player.Player] = [
[`Player: ${Player.Player}`, `Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n")
]
}
});
console.log(new_players);
Object.getOwnPropertyNames(new_players).forEach(Player_Array => {
let Length = Math.abs(new_players[Player_Array].length - 5);
let Player = new_players[Player_Array].slice(0, Length).join("\n")
ctx.reply(Player);
});
}
else ctx.reply("Invalid option")
} else {
const ReplyOption = Markup.keyboard([
"/player kick",
"/player deop",
"/player ban",
"/player op",
"/player list",
]).oneTime().resize();
ctx.reply("Player Options:", ReplyOption);
}
});
// Basic server
bot.command("basic", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/basic", "").trim();
if (text) {
// Start Server
if (/start/.test(text)) {
if (Detect()) ctx.reply("Stop Server");
else {
try {
const Server = bds.start();
Server.log(function (data){
for (let stx of global.LiveLog) stx.reply(data);
});
global.ServerExec = Server;
return ctx.reply("Server Started")
} catch (err) {
console.log(err)
ctx.reply("We couldn't start the server")
ctx.reply(err.toString());
}
}
}
// Stop Server
else if (/stop/.test(text)) {
if (Detect()) {
try {
bds.stop()
ctx.reply("Stopping your server")
} catch (err) {
ctx.reply("We had an error for your server");
ctx.reply(err.toString());
}
} else ctx.reply("Your server is stopped")
}
// Backup
else if (/backup/.test(text)) {
const Backup = bds.backup();
ctx.replyWithDocument({
source: Backup.Buffer,
filename: Backup.file_name,
})
}
// Invalid option
else return ctx.reply("Invalid option, they are just: start, stop")
} else {
await ctx.deleteMessage();
const Options = Markup.keyboard([
"/basic start",
"/basic stop",
"/basic backup",
]).oneTime().resize();
ctx.reply("Basic Options", Options);
}
});
// Select Platform
bot.command("platform", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/platform", "").trim();
if (text) {
try {
bds.BdsSettigs.UpdatePlatform(text);
return ctx.reply(`Platform update to ${text}`)
} catch (err) {
ctx.reply("We were unable to change the platform")
return ctx.reply(err.toString())
}
} else {
await ctx.deleteMessage();
const Keyboard = Markup.keyboard([
"/platform bedrock",
"/platform java",
"/platform pocketmine",
"/platform jsprismarine"
]).oneTime().resize();
ctx.reply("Select Platform", Keyboard)
}
});
// Download Server
bot.command("download", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const version = ctx.message.text.replace(/\/download|[a-zA-Z]/gi, "").trim();
if (version) {
await bds.download(version, true);
ctx.reply(`Sucess install ${GetPlatform()} with version ${version}`);
} else {
await ctx.deleteMessage();
const KeyboardVersion = Markup.keyboard(Object.getOwnPropertyNames((await (await fetch(BdsInfo.Fetchs.servers)).json())[GetPlatform()]).map(version => {
return {
text: `/download ${version}`
}
})).oneTime().resize();
ctx.reply("Select Version to Install", KeyboardVersion);
}
});
// Command
bot.command("command", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const text = ctx.message.text.replace("/command", "").trim();
if (!(Detect())) return ctx.reply("Your server is stopped");
if (text) {
try {
global.ServerExec.command(text);
} catch (err) {
ctx.reply("We couldn't execute the command");
ctx.reply(`${err}`);
}
} else {
await ctx.deleteMessage();
return ctx.reply("/command <command>");
}
});
// Send Info
bot.command("info", ctx => {
const config = bds.get_config();
const InfoRes = [
`Bds Maneger core version: ${bds.package_json.version}`,
`Kernel: ${GetKernel()}`,
`Arch: ${arch}`,
`System: ${system}`,
`Platform: ${GetPlatform()}`,
`World_name: ${config.world}`,
`Running: ${bds.detect()}`,
`Port_V4: ${config.portv4}`,
`Port_V6: ${config.portv6}`,
`Max_players: ${config.players}`,
`Whitelist: ${config.whitelist}`,
]
ctx.reply(InfoRes.join("\n\n"));
});
// Live Log User
global.LiveLog = [];
bot.command("live_log", async ctx => {
// Check admin Username
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
const option = ctx.message.text.replace("/live_log", "").trim();
if (option) {
if (/enable/.test(option)) {
global.LiveLog.push(ctx);
return ctx.reply("Sucess");
} else if (/disable/.test(option)) {
// ctx.from.id
for (let ctx_Logs in global.LiveLog) {
if (global.LiveLog[ctx_Logs].from.id === ctx.from.id) {
delete global.LiveLog[ctx_Logs];
global.LiveLog = global.LiveLog.filter(a=>a);
return ctx.reply("Ok");
}
}
return ctx.reply("You are not in the list");
}
}
await ctx.deleteMessage();
const ReplyOption = Markup.keyboard([
"/live_log enable",
"/live_log disable",
]).oneTime().resize();
ctx.reply("Enable/Disabled?", ReplyOption);
});
// text
bot.on("text", ctx => {
console.log(ctx.message.text);
if (!(/\/.*/gi.test(ctx.message.text))) global.ServerExec.command(`say ${ctx.message.text}`)
});
// catch
bot.catch(console.log);
// End And Lauch
bot.launch();
console.log("Telegram was started");

View File

@ -2,7 +2,7 @@
const path = require("path")
const fs = require("fs");
const { randomUUID } = require("crypto");
const { bds_dir } = require("./lib/BdsSettings");
const BdsSettings = require("./lib/BdsSettings");
// Bds Maneger Core Package JSON File
module.exports.package_path = path.resolve(__dirname, "package.json");
@ -15,11 +15,10 @@ const { arch } = require("./lib/BdsSystemInfo");
module.exports.arch = arch
// Core Settings
const { GetJsonConfig, UpdatePlatform, UpdateTelegramToken } = require("./lib/BdsSettings");
module.exports.getBdsConfig = GetJsonConfig;
module.exports.change_platform = UpdatePlatform;
module.exports.platform_update = UpdatePlatform;
module.exports.telegram_token_save = UpdateTelegramToken;
module.exports.getBdsConfig = BdsSettings.GetJsonConfig;
module.exports.change_platform = BdsSettings.UpdatePlatform;
module.exports.platform_update = BdsSettings.UpdatePlatform;
module.exports.telegram_token_save = BdsSettings.UpdateTelegramToken;
// Platforms Checkers
const { CheckSystemAsync, GetKernel } = require("./lib/BdsSystemInfo");
@ -32,12 +31,12 @@ module.exports.internal_ip = BdsNetwork.LocalInterfaces;
module.exports.external_ip = BdsNetwork.GetExternalPublicAddress;
// Bds Maneger Core API
const BdsManegerAPI = require("./src/api/api");
const BdsManegerAPI = require("./src/api");
module.exports.api = BdsManegerAPI;
module.exports.BdsManegerAPI = BdsManegerAPI;
// Bds Maneger Core API token Register
const path_tokens = path.join(bds_dir, "bds_tokens.json");
const path_tokens = path.join(BdsSettings.bds_dir, "bds_tokens.json");
function token_register(Admin_Scoper = ["web_admin", "admin"]) {
Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper));
let tokens = [];
@ -110,3 +109,5 @@ module.exports.detect = Detect;
module.exports.bds_detect = Detect;
module.exports.detect_server = Detect;
module.exports.kill = Kill;
setInterval(() => {} , 1000);

View File

@ -1,8 +1,7 @@
// Load Fetch.js
const fetchS = (...args) => import("node-fetch").then(mod => mod.default(...args));
// Set global fetch
if (typeof fetch === "undefined") global.fetch = fetchS;
if (typeof fetch === "undefined") {
global.fetch = (...args) => import("node-fetch").then(mod => mod.default(...args));
import("node-fetch").then(mod => global.fetch = mod.default);
}
// Request Json
const ReqJson = async (url = "", options) => await (await fetch(url, options)).json()

118
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@the-bds-maneger/core",
"version": "1.14.1",
"version": "1.15.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@the-bds-maneger/core",
"version": "1.14.1",
"version": "1.15.0",
"license": "AGPL-3.0-or-later",
"os": [
"linux",
@ -34,24 +34,20 @@
"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"
},
"bin": {
"bds_maneger": "bin/bds_maneger.js",
"bds_telegram": "bin/telegram_bot.js"
"bds_maneger": "bin/BdsManeger.js"
},
"devDependencies": {
"@actions/core": "^1.5.0",
"chai": "^4.3.4",
"eslint": "^8.0.0",
"mocha": "^9.1.3",
"nodemon": "^2.0.12",
"os-tmpdir": "^2.0.0"
"nodemon": "^2.0.12"
},
"engines": {
"node": ">=15.6.0"
@ -1291,14 +1287,6 @@
"integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==",
"dev": true
},
"node_modules/define-lazy-prop": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",
"engines": {
"node": ">=8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@ -2651,20 +2639,6 @@
"is-ci": "bin.js"
}
},
"node_modules/is-docker": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
"bin": {
"is-docker": "cli.js"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@ -2802,17 +2776,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-wsl": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
"dependencies": {
"is-docker": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/is-yarn-global": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz",
@ -4537,22 +4500,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/open": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz",
"integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==",
"dependencies": {
"define-lazy-prop": "^2.0.0",
"is-docker": "^2.1.1",
"is-wsl": "^2.2.0"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/opossum": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/opossum/-/opossum-5.0.1.tgz",
@ -4654,16 +4601,6 @@
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/os-tmpdir": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-2.0.0.tgz",
"integrity": "sha512-wZojVQP1fR3zW/Z9YLGJz4etXiu5d2tm4D6R4w2FTx1BAx9F1T+tEBb4+0deWQoskF1xe9zgBr/9mYwE+KY3xw==",
"deprecated": "This is not needed anymore. `require('os').tmpdir()` in Node.js 4 and up is good.",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/p-cancelable": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz",
@ -5232,14 +5169,6 @@
"node": ">= 0.8.0"
}
},
"node_modules/serverline": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/serverline/-/serverline-1.5.0.tgz",
"integrity": "sha512-QzNBH8omGchv+L5n/irZEeU2IGK3r8EMRh3EKRIlbfTklf9PtNRiRbWcYr8kqdNeWdc5M5jS13VtspDKgFXFFg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/setprototypeof": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
@ -6933,11 +6862,6 @@
"integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==",
"dev": true
},
"define-lazy-prop": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@ -7961,11 +7885,6 @@
"ci-info": "^2.0.0"
}
},
"is-docker": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="
},
"is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@ -8052,14 +7971,6 @@
"resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.1.0.tgz",
"integrity": "sha512-lDcxivp8TJpLG75/DpatAqNzOpDPSpED8XNtrpBHTdQ2InQ1PbW78jhwSxyxhhu+xbVSast2X38bwj8atwoUQA=="
},
"is-wsl": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
"requires": {
"is-docker": "^2.0.0"
}
},
"is-yarn-global": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz",
@ -9601,16 +9512,6 @@
"mimic-fn": "^2.1.0"
}
},
"open": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz",
"integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==",
"requires": {
"define-lazy-prop": "^2.0.0",
"is-docker": "^2.1.1",
"is-wsl": "^2.2.0"
}
},
"opossum": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/opossum/-/opossum-5.0.1.tgz",
@ -9678,12 +9579,6 @@
}
}
},
"os-tmpdir": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-2.0.0.tgz",
"integrity": "sha512-wZojVQP1fR3zW/Z9YLGJz4etXiu5d2tm4D6R4w2FTx1BAx9F1T+tEBb4+0deWQoskF1xe9zgBr/9mYwE+KY3xw==",
"dev": true
},
"p-cancelable": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz",
@ -10121,11 +10016,6 @@
"send": "0.17.1"
}
},
"serverline": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/serverline/-/serverline-1.5.0.tgz",
"integrity": "sha512-QzNBH8omGchv+L5n/irZEeU2IGK3r8EMRh3EKRIlbfTklf9PtNRiRbWcYr8kqdNeWdc5M5jS13VtspDKgFXFFg=="
},
"setprototypeof": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",

View File

@ -3,7 +3,7 @@
"publishConfig": {
"access": "public"
},
"version": "1.14.1",
"version": "1.15.0",
"description": "Scripts to manage minecraft server's",
"private": false,
"main": "index.js",
@ -11,7 +11,7 @@
"start": "node bin/bds_maneger.js -s",
"start:telegram": "node bin/telegram_bot.js -e js",
"stop": "node -p 'console.log(require(\"./\").kill());'",
"test": "mocha .test/*.js",
"test": "mocha --exit .test/*.js",
"ci": "node .Build/test/ci.js",
"eslint": "eslint --debug .",
"eslint:fix": "eslint --debug --fix .",
@ -20,8 +20,7 @@
"remove_dev_versions": "node .Build/RemoveVersions.js"
},
"bin": {
"bds_maneger": "bin/bds_maneger.js",
"bds_telegram": "bin/telegram_bot.js"
"bds_maneger": "bin/BdsManeger.js"
},
"repository": {
"type": "git",
@ -72,11 +71,9 @@
"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": {
@ -84,7 +81,6 @@
"chai": "^4.3.4",
"eslint": "^8.0.0",
"mocha": "^9.1.3",
"nodemon": "^2.0.12",
"os-tmpdir": "^2.0.0"
"nodemon": "^2.0.12"
}
}

View File

@ -4,77 +4,77 @@ const AdmZip = require("adm-zip");
const { GetServerPaths, GetPaths, bds_dir } = require("../lib/BdsSettings");
function Backup() {
const zip = new AdmZip();
console.info("Starting Bds Core Backup Along with the server maps, please wait");
// Names And Path"s
const Paths = {
bedrock: GetServerPaths("bedrock"),
java: GetServerPaths("java"),
pocketmine: GetServerPaths("pocketmine"),
spigot: GetServerPaths("spigot"),
dragonfly: GetServerPaths("dragonfly"),
const zip = new AdmZip();
console.info("Starting Bds Core Backup Along with the server maps, please wait");
// Names And Path"s
const Paths = {
bedrock: GetServerPaths("bedrock"),
java: GetServerPaths("java"),
pocketmine: GetServerPaths("pocketmine"),
spigot: GetServerPaths("spigot"),
dragonfly: GetServerPaths("dragonfly"),
}
const CurrentDate = new Date();
const ZipName = `Bds_Maneger_Core_Backups_${CurrentDate.getDate()}-${CurrentDate.getMonth()}-${CurrentDate.getFullYear()}.zip`
const PathBackup = join(GetPaths("backups"), ZipName);
// Bedrock
if (fs.readdirSync(Paths.bedrock).filter(a=>/worlds/.test(a)).length >= 1) {
zip.addLocalFolder(join(Paths.bedrock, "worlds"), join("Servers", "Bedrock", "worlds"));
for (let index of ["server.properties", "permissions.json", "whitelist.json"]) {if (fs.existsSync(join(Paths.bedrock, index))) zip.addLocalFile(join(Paths.bedrock, index), join("Servers", "Bedrock"));}
} else console.info("Skipping the bedrock as it was not installed");
// Java
if (fs.existsSync(join(Paths.java, "MinecraftServerJava.jar"))) {
for (let index of fs.readdirSync(Paths.java).filter(value => !/banned-ips.json|banned-players.json|eula.txt|logs|ops.json|server.jar|MinecraftServerJava.jar|server.properties|usercache.json|whitelist.json/.test(value))) zip.addLocalFolder(join(Paths.java, index), join("Servers", "Java", index));
for (let index of ["banned-ips.json", "banned-players.json", "ops.json", "server.properties", "whitelist.json"]) {if (fs.existsSync(join(Paths.java, index))) zip.addLocalFile(join(Paths.java, index), join("Servers", "Java"))}
} else console.info("Skipping the java as it was not installed");
// PocketMine
if (fs.existsSync(join(Paths.pocketmine, "PocketMine-MP.phar"))) {
if (fs.existsSync(join(Paths.pocketmine, "worlds"))) zip.addLocalFolder(join(Paths.pocketmine, "worlds"), join("Servers", "pocketmine", "worlds"));
for (let index of ["pocketmine.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine");
} else console.info("Skipping the pocketmine as it was not installed");
// Spigot
if (fs.existsSync(join(Paths.spigot, "spigot.jar"))) {
if (fs.existsSync(join(Paths.spigot, "worlds"))) zip.addLocalFolder(join(Paths.spigot, "worlds"), join("Servers", "spigot", "worlds"));
for (let index of ["spigot.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.spigot, index))) zip.addLocalFile(join(Paths.spigot, index), "spigot");
} else console.info("Skipping the spigot as it was not installed");
// Dragonfly
if (fs.existsSync(join(Paths.dragonfly, "config.toml"))) {
for (let index of fs.readdirSync(Paths.dragonfly).map(value => join(Paths.dragonfly, value))) {
if (fs.lstatSync(index).isDirectory()) zip.addLocalFolder(index, join("Servers", "dragonfly"));
else if (fs.lstatSync(index).isFile()) zip.addLocalFile(index, join("Servers", "dragonfly"));
}
const CurrentDate = new Date();
const ZipName = `Bds_Maneger_Core_Backups_${CurrentDate.getDate()}-${CurrentDate.getMonth()}-${CurrentDate.getFullYear()}.zip`
const PathBackup = join(GetPaths("backups"), ZipName);
} else console.info("Skipping the dragonfly as it was not installed");
// Bedrock
if (fs.readdirSync(Paths.bedrock).filter(a=>/worlds/.test(a)).length >= 1) {
zip.addLocalFolder(join(Paths.bedrock, "worlds"), join("Servers", "Bedrock", "worlds"));
for (let index of ["server.properties", "permissions.json", "whitelist.json"]) {if (fs.existsSync(join(Paths.bedrock, index))) zip.addLocalFile(join(Paths.bedrock, index), join("Servers", "Bedrock"));}
} else console.info("Skipping the bedrock as it was not installed");
// The Bds Maneger Core Backup
for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (fs.existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index));
// Java
if (fs.existsSync(join(Paths.java, "MinecraftServerJava.jar"))) {
for (let index of fs.readdirSync(Paths.java).filter(value => !/banned-ips.json|banned-players.json|eula.txt|logs|ops.json|server.jar|MinecraftServerJava.jar|server.properties|usercache.json|whitelist.json/.test(value))) zip.addLocalFolder(join(Paths.java, index), join("Servers", "Java", index));
for (let index of ["banned-ips.json", "banned-players.json", "ops.json", "server.properties", "whitelist.json"]) {if (fs.existsSync(join(Paths.java, index))) zip.addLocalFile(join(Paths.java, index), join("Servers", "Java"))}
} else console.info("Skipping the java as it was not installed");
// PocketMine
if (fs.existsSync(join(Paths.pocketmine, "PocketMine-MP.phar"))) {
if (fs.existsSync(join(Paths.pocketmine, "worlds"))) zip.addLocalFolder(join(Paths.pocketmine, "worlds"), join("Servers", "pocketmine", "worlds"));
for (let index of ["pocketmine.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine");
} else console.info("Skipping the pocketmine as it was not installed");
// Spigot
if (fs.existsSync(join(Paths.spigot, "spigot.jar"))) {
if (fs.existsSync(join(Paths.spigot, "worlds"))) zip.addLocalFolder(join(Paths.spigot, "worlds"), join("Servers", "spigot", "worlds"));
for (let index of ["spigot.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.spigot, index))) zip.addLocalFile(join(Paths.spigot, index), "spigot");
} else console.info("Skipping the spigot as it was not installed");
// Dragonfly
if (fs.existsSync(join(Paths.dragonfly, "config.toml"))) {
for (let index of fs.readdirSync(Paths.dragonfly).map(value => join(Paths.dragonfly, value))) {
if (fs.lstatSync(index).isDirectory()) zip.addLocalFolder(index, join("Servers", "dragonfly"));
else if (fs.lstatSync(index).isFile()) zip.addLocalFile(index, join("Servers", "dragonfly"));
}
} else console.info("Skipping the dragonfly as it was not installed");
// The Bds Maneger Core Backup
for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (fs.existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index));
for (let index of Object.getOwnPropertyNames(GetPaths("all")).filter(path => !/servers|backups/.test(path)).map(name => GetPaths(name))) {
if (fs.existsSync(index)) {
const _S = fs.statSync(resolve(index));
if (_S.isFile() || _S.isSymbolicLink()) zip.addLocalFile(index, "/BdsManegerCore"); else zip.addLocalFolder(index, join("/BdsManegerCore", index.replace(bds_dir, "")));
}
for (let index of Object.getOwnPropertyNames(GetPaths("all")).filter(path => !/servers|backups/.test(path)).map(name => GetPaths(name))) {
if (fs.existsSync(index)) {
const _S = fs.statSync(resolve(index));
if (_S.isFile() || _S.isSymbolicLink()) zip.addLocalFile(index, "/BdsManegerCore"); else zip.addLocalFolder(index, join("/BdsManegerCore", index.replace(bds_dir, "")));
}
}
zip.addZipComment("Settings and World Backups, by The Bds Maneger Project©");
zip.addZipComment("Settings and World Backups, by The Bds Maneger Project©");
// Zip Buffer
const ZipBuffer = zip.toBuffer();
fs.writeFileSync(PathBackup, ZipBuffer, "binary");
console.log("Backup Complete");
return {
file_path: PathBackup,
Buffer: ZipBuffer,
file_name: ZipName,
}
// Zip Buffer
const ZipBuffer = zip.toBuffer();
fs.writeFileSync(PathBackup, ZipBuffer, "binary");
console.log("Backup Complete");
return {
file_path: PathBackup,
Buffer: ZipBuffer,
file_name: ZipName,
}
}
module.exports = {
World_BAckup: Backup,
Backup: Backup,
Cloud_backup: Backup
World_BAckup: Backup,
Backup: Backup,
Cloud_backup: Backup
}

View File

@ -15,430 +15,430 @@ const { Backup } = require("./BdsBackup");
global.BdsExecs = {};
function start() {
if (BdsDetect()) throw new Error("You already have a server running");
const CurrentBdsPlatform = GetPlatform();
const SetupCommands = {
command: String,
args: [],
cwd: String,
env: {
...process.env
},
if (BdsDetect()) throw new Error("You already have a server running");
const CurrentBdsPlatform = GetPlatform();
const SetupCommands = {
command: String,
args: [],
cwd: String,
env: {
...process.env
},
}
// Minecraft Bedrock Oficial
if (CurrentBdsPlatform === "bedrock"){
// Check Darwin Platform
if (process.platform === "darwin") throw new Error("Use a imagem Docker");
// Windows Platform
else if (process.platform === "win32") {
SetupCommands.command = "bedrock_server.exe";
SetupCommands.cwd = GetServerPaths("bedrock")
}
// Minecraft Bedrock Oficial
if (CurrentBdsPlatform === "bedrock"){
// Check Darwin Platform
if (process.platform === "darwin") throw new Error("Use a imagem Docker");
// Linux Platform
else if (process.platform === "linux"){
// Set Executable file
try {child_process.execSync("chmod 777 bedrock_server", {cwd: GetServerPaths("bedrock")});} catch (error) {console.log(error);}
// Windows Platform
else if (process.platform === "win32") {
SetupCommands.command = "bedrock_server.exe";
SetupCommands.cwd = GetServerPaths("bedrock")
}
// Set Env and Cwd
SetupCommands.cwd = GetServerPaths("bedrock");
SetupCommands.env.LD_LIBRARY_PATH = GetServerPaths("bedrock");
// Linux Platform
else if (process.platform === "linux"){
// Set Executable file
try {child_process.execSync("chmod 777 bedrock_server", {cwd: GetServerPaths("bedrock")});} catch (error) {console.log(error);}
// In case the cpu is different from x64, the command will use qemu static to run the server
if (process.arch !== "x64") {
if (!(commandExists("qemu-x86_64-static"))) throw new Error("Install qemu static")
SetupCommands.command = "qemu-x86_64-static"
SetupCommands.args.push("./bedrock_server");
} else SetupCommands.command = "./bedrock_server";
} else throw new Error("your system does not support Minecraft Bedrock (yet)")
}
// Set Env and Cwd
SetupCommands.cwd = GetServerPaths("bedrock");
SetupCommands.env.LD_LIBRARY_PATH = GetServerPaths("bedrock");
// Minecraft Java Oficial
else if (CurrentBdsPlatform === "java") {
const JavaConfig = GetServerSettings("java")
// In case the cpu is different from x64, the command will use qemu static to run the server
if (process.arch !== "x64") {
if (!(commandExists("qemu-x86_64-static"))) throw new Error("Install qemu static")
SetupCommands.command = "qemu-x86_64-static"
SetupCommands.args.push("./bedrock_server");
} else SetupCommands.command = "./bedrock_server";
} else throw new Error("your system does not support Minecraft Bedrock (yet)")
// Checking if java is installed on the device
if (commandExists("java")) {
SetupCommands.cwd = GetServerPaths("java");
SetupCommands.command = "java";
SetupCommands.args.push("-jar", `-Xms${JavaConfig.ram_mb}M`, `-Xmx${JavaConfig.ram_mb}M`, "MinecraftServerJava.jar", "nogui");
} else {require("open")(bds.package_json.docs_base + "Java-Download#windows"); throw new Error(`Open: ${bds.package_json.docs_base + "Java-Download#windows"}`)}
}
// Spigot
else if (CurrentBdsPlatform === "spigot") {
const JavaConfig = GetServerSettings("java")
// Checking if java is installed on the device
if (commandExists("java")) {
SetupCommands.cwd = GetServerPaths("spigot");
SetupCommands.command = "java";
SetupCommands.args.push("-jar", `-Xms${JavaConfig.ram_mb}M`, `-Xmx${JavaConfig.ram_mb}M`, "spigot.jar", "nogui");
} else {require("open")(bds.package_json.docs_base + "Java-Download#windows"); throw new Error(`Open: ${bds.package_json.docs_base + "Java-Download#windows"}`)}
}
// Dragonfly
else if (CurrentBdsPlatform === "dragonfly") {
SetupCommands.cwd = GetServerPaths("dragonfly");
if (process.platform === "win32") {
SetupCommands.command = "Dragonfly.exe";
} else {
SetupCommands.command = "./Dragonfly";
child_process.execFileSync("chmod", ["a+x", SetupCommands.command], {cwd: SetupCommands.cwd});
}
}
// Minecraft Java Oficial
else if (CurrentBdsPlatform === "java") {
const JavaConfig = GetServerSettings("java")
// Minecraft Bedrock (Pocketmine-MP)
else if (CurrentBdsPlatform === "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");
}
// Checking if java is installed on the device
if (commandExists("java")) {
SetupCommands.cwd = GetServerPaths("java");
SetupCommands.command = "java";
SetupCommands.args.push("-jar", `-Xms${JavaConfig.ram_mb}M`, `-Xmx${JavaConfig.ram_mb}M`, "MinecraftServerJava.jar", "nogui");
} else {require("open")(bds.package_json.docs_base + "Java-Download#windows"); throw new Error(`Open: ${bds.package_json.docs_base + "Java-Download#windows"}`)}
}
// Show Error platform
else throw Error("Bds Config Error")
// Spigot
else if (CurrentBdsPlatform === "spigot") {
const JavaConfig = GetServerSettings("java")
// Checking if java is installed on the device
if (commandExists("java")) {
SetupCommands.cwd = GetServerPaths("spigot");
SetupCommands.command = "java";
SetupCommands.args.push("-jar", `-Xms${JavaConfig.ram_mb}M`, `-Xmx${JavaConfig.ram_mb}M`, "spigot.jar", "nogui");
} else {require("open")(bds.package_json.docs_base + "Java-Download#windows"); throw new Error(`Open: ${bds.package_json.docs_base + "Java-Download#windows"}`)}
}
// Setup commands
const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, {
cwd: SetupCommands.cwd,
env: SetupCommands.env
});
// Dragonfly
else if (CurrentBdsPlatform === "dragonfly") {
SetupCommands.cwd = GetServerPaths("dragonfly");
if (process.platform === "win32") {
SetupCommands.command = "Dragonfly.exe";
} else {
SetupCommands.command = "./Dragonfly";
child_process.execFileSync("chmod", ["a+x", SetupCommands.command], {cwd: SetupCommands.cwd});
}
}
// 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");
const LogSaveFunction = data => {
fs.appendFileSync(LogFile, data);
fs.appendFileSync(LatestLog_Path, data);
return data;
}
fs.writeFileSync(LatestLog_Path, "");
// Minecraft Bedrock (Pocketmine-MP)
else if (CurrentBdsPlatform === "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");
}
// Player JSON File
ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON));
ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON));
// Show Error platform
else throw Error("Bds Config Error")
// Log File
ServerExec.stdout.on("data", LogSaveFunction);
ServerExec.stderr.on("data", LogSaveFunction);
// Setup commands
const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, {
cwd: SetupCommands.cwd,
env: SetupCommands.env
// Global and Run
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 log = function (logCallback){
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){
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);
};
const command = function (command = "list") {
ServerExec.stdin.write(`${command}\n`);
return command;
};
const stop = function (){
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "dragonfly") {
ServerExec.kill("SIGKILL");
return "process";
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write("stop\n");
return "stop";
} else throw new Error("Bds Core Bad Config Error");
};
const op = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`op "${player}"\n`);
return "op";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else throw new Error("Bds Core Bad Config Error");
};
const deop = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`deop "${player}"\n`);
return "deop";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else throw new Error("Bds Core Bad Config Error");
};
const ban = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`kick "${player}"\n`);
return "kick";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else throw new Error("Bds Core Bad Config Error");
};
const kick = function (player = "Steve", text = "you got kicked") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`kick "${player}" ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else throw new Error("Bds Core Bad Config Error");
};
const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else throw new Error("Bds Core Bad Config Error");
};
function say(text = ""){
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else throw new Error("Bds Core Bad Config Error");
}
// 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");
const LogSaveFunction = data => {
fs.appendFileSync(LogFile, data);
fs.appendFileSync(LatestLog_Path, data);
return data;
}
fs.writeFileSync(LatestLog_Path, "");
// Mount commands to Return
const returnFuntion = {
uuid: randomUUID(),
pid: ServerExec.pid,
uptime: 0,
StartTime: (new Date()),
command, log, exit, on, stop, op, deop, ban, kick, tp, say
}
// Player JSON File
ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON));
ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON));
// Uptime Server
const OnStop = setInterval(() => returnFuntion.uptime = (new Date().getTime() - returnFuntion.StartTime.getTime()) / 1000, 1000);
ServerExec.on("exit", () => {
delete global.BdsExecs[returnFuntion.uuid]
clearInterval(OnStop);
});
// Log File
ServerExec.stdout.on("data", LogSaveFunction);
ServerExec.stderr.on("data", LogSaveFunction);
// Global and Run
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 log = function (logCallback){
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){
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);
};
const command = function (command = "list") {
ServerExec.stdin.write(`${command}\n`);
return command;
};
const stop = function (){
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "dragonfly") {
ServerExec.kill("SIGKILL");
return "process";
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write("stop\n");
return "stop";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write("stop\n");
return "stop";
} else throw new Error("Bds Core Bad Config Error");
};
const op = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`op "${player}"\n`);
return "op";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`op ${player}\n`);
return "op";
} else throw new Error("Bds Core Bad Config Error");
};
const deop = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`deop "${player}"\n`);
return "deop";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`deop ${player}\n`);
return "deop";
} else throw new Error("Bds Core Bad Config Error");
};
const ban = function (player = "Steve") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`kick "${player}"\n`);
return "kick";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`ban ${player}\n`);
return "ban";
} else throw new Error("Bds Core Bad Config Error");
};
const kick = function (player = "Steve", text = "you got kicked") {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`kick "${player}" ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`kick ${player} ${text}\n`);
return "kick";
} else throw new Error("Bds Core Bad Config Error");
};
const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) {
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`);
return "tp";
} else throw new Error("Bds Core Bad Config Error");
};
function say(text = ""){
if (CurrentBdsPlatform === "bedrock") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "dragonfly") {
throw new Error("Dragonfly does not support commands");
} else if (CurrentBdsPlatform === "java") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "pocketmine") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else if (CurrentBdsPlatform === "spigot") {
ServerExec.stdin.write(`say ${text}\n`);
return "say";
} else throw new Error("Bds Core Bad Config Error");
}
// Mount commands to Return
const returnFuntion = {
uuid: randomUUID(),
pid: ServerExec.pid,
uptime: 0,
StartTime: (new Date()),
command, log, exit, on, stop, op, deop, ban, kick, tp, say
}
// Uptime Server
const OnStop = setInterval(() => returnFuntion.uptime = (new Date().getTime() - returnFuntion.StartTime.getTime()) / 1000, 1000);
ServerExec.on("exit", () => {
delete global.BdsExecs[returnFuntion.uuid]
clearInterval(OnStop);
});
// Return
global.BdsExecs[returnFuntion.uuid] = returnFuntion;
module.exports.BdsRun = returnFuntion;
return returnFuntion;
// Return
global.BdsExecs[returnFuntion.uuid] = returnFuntion;
module.exports.BdsRun = returnFuntion;
return returnFuntion;
}
function Player_Json(data = "aaaaaa\n\n\naa", callback = () => {}){
const Current_platorm = GetPlatform();
// Bedrock
if (Current_platorm === "bedrock") {
// "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840",
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
const BedrockMap = data.split(/\n|\r/gi).map(line => {
if (line.includes("connected") || line.includes("disconnected")) {
let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi);
const Current_platorm = GetPlatform();
// Bedrock
if (Current_platorm === "bedrock") {
// "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840",
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
const BedrockMap = data.split(/\n|\r/gi).map(line => {
if (line.includes("connected") || line.includes("disconnected")) {
let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi);
// player
let Player = line.trim().replace(/\[.+\]\s+Player/gi, "").trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a);
// player
let Player = line.trim().replace(/\[.+\]\s+Player/gi, "").trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a);
//
let Actions = null;
if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect";
else if (/^connected/.test(SplitLine[0].trim())) Actions = "connect";
//
let Actions = null;
if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect";
else if (/^connected/.test(SplitLine[0].trim())) Actions = "connect";
// Object Map
const ObjectReturn = {
Player: Player[0],
Action: Actions,
xuid: Player[1] || null,
Date: new Date(),
}
// Object Map
const ObjectReturn = {
Player: Player[0],
Action: Actions,
xuid: Player[1] || null,
Date: new Date(),
}
// Return
return ObjectReturn
} else return false;
}).filter(a=>a);
callback(BedrockMap);
}
// Java and Pocketmine-MP
else if (Current_platorm === "java" || Current_platorm === "pocketmine") {
const JavaMap = data.split(/\n|\r/gi).map(line => {
if (line.trim().includes("joined the game") || line.includes("left the game")) {
line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim();
let Actions = null;
if (/joined/.test(line)) Actions = "connect";
else if (/left/.test(line)) Actions = "disconnect";
// Return
return ObjectReturn
} else return false;
}).filter(a=>a);
callback(BedrockMap);
}
// Java and Pocketmine-MP
else if (Current_platorm === "java" || Current_platorm === "pocketmine") {
const JavaMap = data.split(/\n|\r/gi).map(line => {
if (line.trim().includes("joined the game") || line.includes("left the game")) {
line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim();
let Actions = null;
if (/joined/.test(line)) Actions = "connect";
else if (/left/.test(line)) Actions = "disconnect";
// Player Object
const JavaObject = {
Player: line.replace(/joined the game|left the game/gi, "").trim(),
Action: Actions,
Date: new Date(),
}
// Player Object
const JavaObject = {
Player: line.replace(/joined the game|left the game/gi, "").trim(),
Action: Actions,
Date: new Date(),
}
// Return JSON
return JavaObject
} else return false;
}).filter(a=>a);
callback(JavaMap);
}
// Return JSON
return JavaObject
} else return false;
}).filter(a=>a);
callback(JavaMap);
}
}
const UpdateUserJSON = function (New_Object = []){
const Player_Json_path = GetPaths("player");
const Current_platorm = GetPlatform();
let Players_Json = {
bedrock: [],
java: [],
pocketmine: [],
jsprismarine: [],
}
if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"));
const Player_Json_path = GetPaths("player");
const Current_platorm = GetPlatform();
let Players_Json = {
bedrock: [],
java: [],
pocketmine: [],
jsprismarine: [],
}
if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"));
// Array
Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object)
// Array
Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object)
fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2));
return Players_Json
fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2));
return Players_Json
}
// Search player in JSON
function Player_Search(player = "dontSteve") {
const Player_Json_path = GetPaths("player"), Current_platorm = GetPlatform();
const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[Current_platorm]
for (let Player of Players_Json) {
if (Player.Player === player.trim()) return Player;
}
return {};
const Player_Json_path = GetPaths("player"), Current_platorm = GetPlatform();
const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[Current_platorm]
for (let Player of Players_Json) {
if (Player.Player === player.trim()) return Player;
}
return {};
}
function GetSessions(){
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
if (ArraySessions.length === 0) throw "Start Server";
if (ArraySessions.length >= 2) throw "Select a session manually:" + ArraySessions.join(", ")
return global.BdsExecs[0]
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
if (ArraySessions.length === 0) throw "Start Server";
if (ArraySessions.length >= 2) throw "Select a session manually:" + ArraySessions.join(", ")
return global.BdsExecs[0]
}
function BdsCommand(command = "list", SessionID = null) {
if (!(command)) return false;
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.command(command);
return true
} catch (error) {
return false
}
if (!(command)) return false;
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.command(command);
return true
} catch (error) {
return false
}
}
function stop(SessionID = null) {
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.stop()
return true
} catch (error) {
return false
}
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.stop()
return true
} catch (error) {
return false
}
}
const Cloud_Backup = {
Azure: require("./clouds/Azure").Uploadbackups,
Driver: require("./clouds/GoogleDriver").Uploadbackups,
Oracle: require("./clouds/OracleCI").Uploadbackups,
Azure: require("./clouds/Azure").Uploadbackups,
Driver: require("./clouds/GoogleDriver").Uploadbackups,
Oracle: require("./clouds/OracleCI").Uploadbackups,
}
const CurrentBackups = GetCronBackup().map(Crron => {
return {
CronFunction: new CronJob(Crron.cron, async () => {
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
// Azure
if (Crron.Azure) Cloud_Backup.Azure(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Azure Backup Disabled");
return {
CronFunction: new CronJob(Crron.cron, async () => {
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
// Azure
if (Crron.Azure) Cloud_Backup.Azure(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Azure Backup Disabled");
// Google Driver
if (Crron.Driver) Cloud_Backup.Driver(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Google Driver Backup Disabled");
// Google Driver
if (Crron.Driver) Cloud_Backup.Driver(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Google Driver Backup Disabled");
// Oracle Bucket
if (Crron.Oracle) Cloud_Backup.Oracle(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Oracle Bucket Backup Disabled");
})
}
// Oracle Bucket
if (Crron.Oracle) Cloud_Backup.Oracle(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Oracle Bucket Backup Disabled");
})
}
});
module.exports = {
start,
BdsCommand,
stop,
GetSessions,
CronBackups: CurrentBackups,
Player_Search,
start,
BdsCommand,
stop,
GetSessions,
CronBackups: CurrentBackups,
Player_Search,
}

View File

@ -6,41 +6,41 @@ function LocalInterfaces() {
const interfaces = os.networkInterfaces();
const localInterfaces = [];
for (const name of Object.getOwnPropertyNames(interfaces)) {
const Inter = {
interfaceName: name,
mac: "",
v4: {
addresses: "",
netmask: "",
cidr: ""
},
v6: {
addresses: "",
netmask: "",
cidr: ""
},
const Inter = {
interfaceName: name,
mac: "",
v4: {
addresses: "",
netmask: "",
cidr: ""
},
v6: {
addresses: "",
netmask: "",
cidr: ""
},
}
for (let iface of interfaces[name]) {
if (!Inter.mac && iface.mac) Inter.mac = iface.mac;
if (iface.family === "IPv4") {
Inter.v4.addresses = iface.address;
Inter.v4.netmask = iface.netmask;
Inter.v4.cidr = iface.cidr;
} else if (iface.family === "IPv6") {
Inter.v6.addresses = iface.address;
Inter.v6.netmask = iface.netmask;
Inter.v6.cidr = iface.cidr;
}
for (let iface of interfaces[name]) {
if (!Inter.mac && iface.mac) Inter.mac = iface.mac;
if (iface.family === "IPv4") {
Inter.v4.addresses = iface.address;
Inter.v4.netmask = iface.netmask;
Inter.v4.cidr = iface.cidr;
} else if (iface.family === "IPv6") {
Inter.v6.addresses = iface.address;
Inter.v6.netmask = iface.netmask;
Inter.v6.cidr = iface.cidr;
}
}
if (!(interfaces[name][0].internal)) localInterfaces.push(Inter);
}
if (!(interfaces[name][0].internal)) localInterfaces.push(Inter);
}
return localInterfaces;
}
async function GetExternalPublicAddress() {
const ExternlIPs = {
ipv4: null,
ipv6: null
ipv4: null,
ipv6: null
}
ExternlIPs["ipv4"] = (await Request.TEXT("https://api.ipify.org")).replace("\n", "")
ExternlIPs["ipv6"] = (await Request.TEXT("https://api64.ipify.org/")).replace("\n", "")
@ -49,49 +49,49 @@ async function GetExternalPublicAddress() {
}
Request.TEXT("https://api.ipify.org").then(external_ipv4 => {
Request.TEXT("https://api64.ipify.org/").then(external_ipv6 => {
const externalIP = {
ipv4: external_ipv4.replace("\n", ""),
ipv6: external_ipv6.replace("\n", "")
}
Request.TEXT("https://api64.ipify.org/").then(external_ipv6 => {
const externalIP = {
ipv4: external_ipv4.replace("\n", ""),
ipv6: external_ipv6.replace("\n", "")
}
module.exports.externalIP = externalIP;
module.exports.ip = externalIP;
});
module.exports.externalIP = externalIP;
module.exports.ip = externalIP;
});
});
// Internal ip user
const interfaces = os.networkInterfaces();
const internal_ip = [];
for (let inter of Object.getOwnPropertyNames(interfaces).map(index => interfaces[index])){
for (let ind in inter){
if (inter[ind].address.includes("::")) internal_ip.push(`[${inter[ind].address}]`)
else internal_ip.push(inter[ind].address)
}
for (let ind in inter){
if (inter[ind].address.includes("::")) internal_ip.push(`[${inter[ind].address}]`)
else internal_ip.push(inter[ind].address)
}
}
// Network Interfaces
const Interfaces = Object.getOwnPropertyNames(interfaces).map(inter => {
inter = interfaces[inter]
if (inter[0].mac !== "00:00:00:00:00:00") {
try {
return {
MAC: inter[0].mac,
Interna_IP: {
ipv4: inter[0].address,
ipv6: inter[1].address,
}
}
} catch (err) {
return {
MAC: inter[0].mac,
Interna_IP: {
ipv4: inter[0].address,
ipv6: null,
}
}
inter = interfaces[inter]
if (inter[0].mac !== "00:00:00:00:00:00") {
try {
return {
MAC: inter[0].mac,
Interna_IP: {
ipv4: inter[0].address,
ipv6: inter[1].address,
}
}
} catch (err) {
return {
MAC: inter[0].mac,
Interna_IP: {
ipv4: inter[0].address,
ipv6: null,
}
}
}
}
}).filter(a=>a);
async function GetHost() {
@ -99,24 +99,24 @@ async function GetHost() {
const ExternalAddress = (await GetExternalPublicAddress()).ipv4;
const RequestUpstream = await fetch(`https://upstream.bdsmaneger.com/v1/public_domain?MacAddress=${JSON.stringify(MacAddr)}&ExternalAdress=${ExternalAddress}`, {mode: "cors"});
if (!RequestUpstream.ok) {
throw {
Backend: await RequestUpstream.json()
}
throw {
Backend: await RequestUpstream.json()
}
}
const HostInfo = await RequestUpstream.json();
const _toReturn = {
host: "",
UpstreamID: "",
delete_host: async () => {
const RequestDeleteHost = await fetch("https://upstream.bdsmaneger.com/v1/public_domain", {
method: "DELETE",
mode: "cors",
body: JSON.stringify({
UUID: HostInfo.ID
})
});
return await RequestDeleteHost.json();
}
host: "",
UpstreamID: "",
delete_host: async () => {
const RequestDeleteHost = await fetch("https://upstream.bdsmaneger.com/v1/public_domain", {
method: "DELETE",
mode: "cors",
body: JSON.stringify({
UUID: HostInfo.ID
})
});
return await RequestDeleteHost.json();
}
}
_toReturn["host"] = HostInfo.host.host
_toReturn["UpstreamID"] = HostInfo.ID
@ -124,10 +124,10 @@ async function GetHost() {
}
module.exports = {
internal_ip,
Interfaces,
LocalInterfaces,
GetExternalPublicAddress,
host: null,
GetHost
internal_ip,
Interfaces,
LocalInterfaces,
GetExternalPublicAddress,
host: null,
GetHost
}

View File

@ -10,243 +10,243 @@ const Request = require("../lib/Requests");
// Get Platform Object Versions
async function PlatformVersionsV2(SelectPlatform = "") {
const CurrentPlatform = SelectPlatform || GetPlatform();
let ResToRetuen = {
latest: "",
versions: {
"123.123.123": {
data: `${new Date()}`,
url: "",
linux: {
aarch64: "",
armv7: "",
x64: "",
i386: ""
},
win32: {
aarch64: "",
x64: "",
i386: ""
},
darwin: {
aarch64: "",
x64: ""
},
android: {
aarch64: "",
x64: ""
}
}
const CurrentPlatform = SelectPlatform || GetPlatform();
let ResToRetuen = {
latest: "",
versions: {
"123.123.123": {
data: `${new Date()}`,
url: "",
linux: {
aarch64: "",
armv7: "",
x64: "",
i386: ""
},
win32: {
aarch64: "",
x64: "",
i386: ""
},
darwin: {
aarch64: "",
x64: ""
},
android: {
aarch64: "",
x64: ""
}
}
}
ResToRetuen = await Request.json(`https://raw.githubusercontent.com/The-Bds-Maneger/ServerVersions/main/${CurrentPlatform}/server.json`);
return ResToRetuen;
}
ResToRetuen = await Request.json(`https://raw.githubusercontent.com/The-Bds-Maneger/ServerVersions/main/${CurrentPlatform}/server.json`);
return ResToRetuen;
}
// Php download and install
async function php_download() {
const bds_dir_pocketmine = GetServerPaths("pocketmine");
const PHPBin = (await (await fetch(Extra.Fetchs.php)).json());
const phpFolder = resolve(bds_dir_pocketmine, "bin");
const phpExtensiosnsDir = resolve(bds_dir_pocketmine, "bin/php7/lib/php/extensions");
const bds_dir_pocketmine = GetServerPaths("pocketmine");
const PHPBin = (await (await fetch(Extra.Fetchs.php)).json());
const phpFolder = resolve(bds_dir_pocketmine, "bin");
const phpExtensiosnsDir = resolve(bds_dir_pocketmine, "bin/php7/lib/php/extensions");
// Check Php Binary
let urlPHPBin = PHPBin[process.platform]
if (!(urlPHPBin)) throw new Error("unsupported system")
urlPHPBin = urlPHPBin[bds.arch];
if (!(urlPHPBin)) throw new Error("unsupported arch")
// Check Php Binary
let urlPHPBin = PHPBin[process.platform]
if (!(urlPHPBin)) throw new Error("unsupported system")
urlPHPBin = urlPHPBin[bds.arch];
if (!(urlPHPBin)) throw new Error("unsupported arch")
// Remove Old php Binary if it exists
if (existsSync(phpFolder)) {
rmSync(phpFolder, { recursive: true });
}
const ZipBuffer = Buffer.from((await (await fetch(urlPHPBin)).arrayBuffer()));
const zipExtractBin = new AdmZip(ZipBuffer);
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
// Remove Old php Binary if it exists
if (existsSync(phpFolder)) {
rmSync(phpFolder, { recursive: true });
}
const ZipBuffer = Buffer.from((await (await fetch(urlPHPBin)).arrayBuffer()));
const zipExtractBin = new AdmZip(ZipBuffer);
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
if (process.platform === "win32") return resolve();
if (process.platform === "win32") return resolve();
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8");
if (!(existsSync(phpExtensiosnsDir))) return true;
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8");
if (!(existsSync(phpExtensiosnsDir))) return true;
const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => {
if (!(FileFolder.includes("debug-zts"))) return false;
return resolve(phpExtensiosnsDir, FileFolder);
}).filter(a=>a);
const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => {
if (!(FileFolder.includes("debug-zts"))) return false;
return resolve(phpExtensiosnsDir, FileFolder);
}).filter(a=>a);
if (phpConfigInit.includes("extension_dir")) console.log("Skipping php.ini configuration");
else {
phpConfigInit = (`extension_dir="${phpExtensiosns.join()}"\n${phpConfigInit}`);
writeFileSync(join(phpFolder, "php7", "bin", "php.ini"), phpConfigInit);
}
return true;
if (phpConfigInit.includes("extension_dir")) console.log("Skipping php.ini configuration");
else {
phpConfigInit = (`extension_dir="${phpExtensiosns.join()}"\n${phpConfigInit}`);
writeFileSync(join(phpFolder, "php7", "bin", "php.ini"), phpConfigInit);
}
return true;
}
// New Download Method
async function BdsDownloadV2(version = "latest") {
const CurrentPlatform = GetPlatform();
const { valid_platform, require_qemu } = await (require("../lib/BdsSystemInfo")).CheckSystemAsync();
const LocalServersVersions = bds.BdsSettigs.GetServerVersion();
const { ServersPaths } = bds.BdsSettigs;
const CurrentPlatform = GetPlatform();
const { valid_platform, require_qemu } = await (require("../lib/BdsSystemInfo")).CheckSystemAsync();
const LocalServersVersions = bds.BdsSettigs.GetServerVersion();
const { ServersPaths } = bds.BdsSettigs;
const ReturnObject = {
version,
platform: CurrentPlatform,
url: "",
data: new Date(),
skip: false
}
const ReturnObject = {
version,
platform: CurrentPlatform,
url: "",
data: new Date(),
skip: false
}
// Bedrock
if (CurrentPlatform === "bedrock") {
const BedrockVersions = await PlatformVersionsV2("bedrock");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = BedrockVersions.latest;
if (valid_platform.bedrock) {
if (LocalServersVersions.bedrock !== version) {
// Add info to ReturnObject
if (require_qemu) ReturnObject.url = BedrockVersions.versions[version][process.platform]["x64"]; else ReturnObject.url = BedrockVersions.versions[version][process.platform][bds.arch];
ReturnObject.data = BedrockVersions.versions[version].data ? new Date(BedrockVersions.versions[version].data) : null;
// Bedrock
if (CurrentPlatform === "bedrock") {
const BedrockVersions = await PlatformVersionsV2("bedrock");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = BedrockVersions.latest;
if (valid_platform.bedrock) {
if (LocalServersVersions.bedrock !== version) {
// Add info to ReturnObject
if (require_qemu) ReturnObject.url = BedrockVersions.versions[version][process.platform]["x64"]; else ReturnObject.url = BedrockVersions.versions[version][process.platform][bds.arch];
ReturnObject.data = BedrockVersions.versions[version].data ? new Date(BedrockVersions.versions[version].data) : null;
// Download and Add buffer to AdmZip
const BedrockZip = new AdmZip(await Request.buffer(ReturnObject.url));
// 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");
// 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") {
const JavaVersions = await PlatformVersionsV2("java");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = JavaVersions.latest;
if (valid_platform.java) {
if (LocalServersVersions.java !== version) {
// Add info to ReturnObject
ReturnObject.url = JavaVersions.versions[version].url;
ReturnObject.data = JavaVersions.versions[version].data;
// Java
else if (CurrentPlatform === "java") {
const JavaVersions = await PlatformVersionsV2("java");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = JavaVersions.latest;
if (valid_platform.java) {
if (LocalServersVersions.java !== version) {
// Add info to ReturnObject
ReturnObject.url = JavaVersions.versions[version].url;
ReturnObject.data = JavaVersions.versions[version].data;
// Download and write java file
const JavaBufferJar = await Request.buffer(ReturnObject.url);
fs.writeFileSync(path.join(ServersPaths.java, "MinecraftServerJava.jar"), JavaBufferJar, "binary");
// 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");
// 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");
}
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Java not suported");
}
}
// Spigot
else if (CurrentPlatform === "spigot") {
const SpigotVersions = await PlatformVersionsV2("spigot");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = SpigotVersions.latest;
if (valid_platform.spigot) {
if (LocalServersVersions.spigot !== version) {
// Add info to ReturnObject
ReturnObject.url = SpigotVersions.versions[version].url;
ReturnObject.data = SpigotVersions.versions[version].data;
// Spigot
else if (CurrentPlatform === "spigot") {
const SpigotVersions = await PlatformVersionsV2("spigot");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = SpigotVersions.latest;
if (valid_platform.spigot) {
if (LocalServersVersions.spigot !== version) {
// Add info to ReturnObject
ReturnObject.url = SpigotVersions.versions[version].url;
ReturnObject.data = SpigotVersions.versions[version].data;
// Download and write java file
fs.writeFileSync(path.join(ServersPaths.spigot, "spigot.jar"), await Request.buffer(ReturnObject.url), "binary");
// 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");
}
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Spigot not suported");
}
}
// Dragonfly
else if (CurrentPlatform === "dragonfly") {
const DragonflyVersions = await PlatformVersionsV2("dragonfly");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = DragonflyVersions.latest;
if (valid_platform.dragonfly) {
if (LocalServersVersions.dragonfly !== version) {
// Add info to ReturnObject
ReturnObject.url = DragonflyVersions.versions[version][process.platform][bds.arch]
ReturnObject.data = DragonflyVersions.versions[version].data;
// Dragonfly
else if (CurrentPlatform === "dragonfly") {
const DragonflyVersions = await PlatformVersionsV2("dragonfly");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = DragonflyVersions.latest;
if (valid_platform.dragonfly) {
if (LocalServersVersions.dragonfly !== version) {
// Add info to ReturnObject
ReturnObject.url = DragonflyVersions.versions[version][process.platform][bds.arch]
ReturnObject.data = DragonflyVersions.versions[version].data;
// Download
let DgBin = path.join(ServersPaths.dragonfly, "Dragonfly");
if (process.platform === "win32") DgBin += ".exe";
fs.writeFileSync(DgBin, await Request.buffer(ReturnObject.url), "binary");
// Download
let DgBin = path.join(ServersPaths.dragonfly, "Dragonfly");
if (process.platform === "win32") DgBin += ".exe";
fs.writeFileSync(DgBin, await Request.buffer(ReturnObject.url), "binary");
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Dragonfly not suported");
}
// Update Server Version
bds.BdsSettigs.UpdateServerVersion(version, CurrentPlatform);
} else {
ReturnObject.skip = true;
}
} else {
throw Error("Dragonfly not suported");
}
}
// Pocketmine-MP
else if (CurrentPlatform === "pocketmine") {
const PocketmineVersions = await PlatformVersionsV2("pocketmine");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = PocketmineVersions.latest;
if (valid_platform.pocketmine) {
if (LocalServersVersions.pocketmine !== version) {
// Add info to ReturnObject
ReturnObject.url = PocketmineVersions.versions[version].url;
ReturnObject.data = PocketmineVersions.versions[version].data;
// Pocketmine-MP
else if (CurrentPlatform === "pocketmine") {
const PocketmineVersions = await PlatformVersionsV2("pocketmine");
if (typeof version === "boolean" || /true|false|null|undefined|latest/.test(`${version}`.toLocaleLowerCase())) version = PocketmineVersions.latest;
if (valid_platform.pocketmine) {
if (LocalServersVersions.pocketmine !== version) {
// Add info to ReturnObject
ReturnObject.url = PocketmineVersions.versions[version].url;
ReturnObject.data = PocketmineVersions.versions[version].data;
// Download PHP Bin
await php_download();
// 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");
// 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");
}
// 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");
// if the platform does not exist
else throw Error("No Valid Platform");
// Return info download
return ReturnObject;
// Return info download
return ReturnObject;
}
// Export

View File

@ -1,97 +1,97 @@
const { execSync } = require("child_process");
function getProcess(){
let MountProcess = [];
if (process.platform === "win32") {
MountProcess = execSync("wmic path win32_process get Processid,Commandline,WorkingSetSize", {maxBuffer: Infinity}).toString().split(/\n/gi).filter(a => a.trim()).map(Line => {
try {
Line = Line.split(/\r/gi).filter(a => a).join("").trim();
const line_split = Line.split(/\s+/gi);
let MountProcess = [];
if (process.platform === "win32") {
MountProcess = execSync("wmic path win32_process get Processid,Commandline,WorkingSetSize", {maxBuffer: Infinity}).toString().split(/\n/gi).filter(a => a.trim()).map(Line => {
try {
Line = Line.split(/\r/gi).filter(a => a).join("").trim();
const line_split = Line.split(/\s+/gi);
// Ignore empty lines
if (line_split.length <= 2) return false
// Ignore empty lines
if (line_split.length <= 2) return false
let pid = line_split[Math.abs(line_split.length - 2)].toString();
let mem = line_split[Math.abs(line_split.length - 1)].toString();
let command = Line.slice(0, - Math.abs(pid.length)).trim().slice(0, - Math.abs(mem.length)).trim();
pid = parseInt(pid);
mem = parseInt(mem);
if (command && pid && mem) return {
command,
pid,
mem,
}; else return false
} catch (err) {
console.log(err);
return false
}
}).filter(a => a);
} else {
MountProcess = execSync("ps -aux").toString("utf8").split("\n").filter(d=>{return !(/USER\s+/.test(d) || d === "")}).map(_line => _line.split(/\s+/)).map(_line =>{
return {
command: (function(){
var command = _line[10];
const argvLenght = (_line.length - 11);
for (let index = 0; index < argvLenght; index++) {
command += ` ${_line[11 + index]}`;
}
return command;
})(),
pid: parseInt(_line[1]),
mem: _line[3],
}
})
}
return MountProcess;
let pid = line_split[Math.abs(line_split.length - 2)].toString();
let mem = line_split[Math.abs(line_split.length - 1)].toString();
let command = Line.slice(0, - Math.abs(pid.length)).trim().slice(0, - Math.abs(mem.length)).trim();
pid = parseInt(pid);
mem = parseInt(mem);
if (command && pid && mem) return {
command,
pid,
mem,
}; else return false
} catch (err) {
console.log(err);
return false
}
}).filter(a => a);
} else {
MountProcess = execSync("ps -aux").toString("utf8").split("\n").filter(d=>{return !(/USER\s+/.test(d) || d === "")}).map(_line => _line.split(/\s+/)).map(_line =>{
return {
command: (function(){
var command = _line[10];
const argvLenght = (_line.length - 11);
for (let index = 0; index < argvLenght; index++) {
command += ` ${_line[11 + index]}`;
}
return command;
})(),
pid: parseInt(_line[1]),
mem: _line[3],
}
})
}
return MountProcess;
}
function killWithPid(pid = 1){
if (process.platform === "win32") return execSync(`taskkill /PID ${pid} /F`).toString("utf8");
else return execSync(`kill -9 ${pid}`).toString("utf8")
if (process.platform === "win32") return execSync(`taskkill /PID ${pid} /F`).toString("utf8");
else return execSync(`kill -9 ${pid}`).toString("utf8")
}
function Detect(){
const CurrentProcess = getProcess();
for (let check of CurrentProcess) {
if (/MinecraftServerJava.jar/.test(check.command)) return true;
if (/spigot.jar/.test(check.command)) return true;
if (/bedrock_server/.test(check.command)) return true;
if (/PocketMine-MP.phar/.test(check.command)) return true;
if (/Dragonfly/.test(check.command)) return true;
}
return false
const CurrentProcess = getProcess();
for (let check of CurrentProcess) {
if (/MinecraftServerJava.jar/.test(check.command)) return true;
if (/spigot.jar/.test(check.command)) return true;
if (/bedrock_server/.test(check.command)) return true;
if (/PocketMine-MP.phar/.test(check.command)) return true;
if (/Dragonfly/.test(check.command)) return true;
}
return false
}
function Kill(){
if (!(Detect())) return false
const CurrentProcess = getProcess();
for (let check of CurrentProcess) {
if (/MinecraftServerJava.jar/.test(check.command)) {
console.log("Killing Minecraft Server Java");
killWithPid(check.pid);
}
if (/spigot.jar/.test(check.command)) {
console.log("Killing Spigot");
killWithPid(check.pid);
}
if (/bedrock_server/.test(check.command)) {
console.log("Killing Minecraft Bedrock Server");
killWithPid(check.pid);
}
if (/PocketMine-MP.phar/.test(check.command)) {
console.log("Killing Pocketmine-MP");
killWithPid(check.pid);
}
if (/Dragonfly/.test(check.command)) {
console.log("Killing Dragonfly");
killWithPid(check.pid);
}
if (!(Detect())) return false
const CurrentProcess = getProcess();
for (let check of CurrentProcess) {
if (/MinecraftServerJava.jar/.test(check.command)) {
console.log("Killing Minecraft Server Java");
killWithPid(check.pid);
}
return true
if (/spigot.jar/.test(check.command)) {
console.log("Killing Spigot");
killWithPid(check.pid);
}
if (/bedrock_server/.test(check.command)) {
console.log("Killing Minecraft Bedrock Server");
killWithPid(check.pid);
}
if (/PocketMine-MP.phar/.test(check.command)) {
console.log("Killing Pocketmine-MP");
killWithPid(check.pid);
}
if (/Dragonfly/.test(check.command)) {
console.log("Killing Dragonfly");
killWithPid(check.pid);
}
}
return true
}
module.exports = {
getProcess,
Detect,
Kill
getProcess,
Detect,
Kill
}

View File

@ -4,183 +4,183 @@ const { GetPlatform, GetPaths } = require("../lib/BdsSettings");
const fs = require("fs");
function MytypeKill(player) {
console.warn(`Player ${player} tried to connect to the server`)
let removeUser = `tp "${player}" ~ 128 ~`
console.log(removeUser);
var RemoveUser = setInterval(() => {
bds.command(removeUser);
bds_server_string.stdout.on("data", (data) => {
if (data.includes("disconnected:")) {
if (data.includes(player)) clearInterval(RemoveUser);
}
})
console.warn(`Player ${player} tried to connect to the server`)
let removeUser = `tp "${player}" ~ 128 ~`
console.log(removeUser);
var RemoveUser = setInterval(() => {
bds.command(removeUser);
bds_server_string.stdout.on("data", (data) => {
if (data.includes("disconnected:")) {
if (data.includes(player)) clearInterval(RemoveUser);
}
})
}, 6 * 1000);
return RemoveUser;
}, 6 * 1000);
return RemoveUser;
}
function Bedrock(data){
const file_users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(file_users);
const CurrentData = new Date();
for (let line of data.split(/\r?\n/g)) {
if (line.includes("connected:")) {
line = line.replace("[INFO] Player ", "").trim()
let GetSatatus = line.trim().split(/\s+/g)[0];
const GetUser = [];
for (let index of line.trim().replace("connected:", "").replace("dis", "").trim().split(", xuid:")) if (index !== "") GetUser.push(index.trim());
// -------------------------------------------------
var username = GetUser[0];
console.log(GetUser);
// User Connected
if (GetSatatus === "connected:") {
if (CheckBan(username)) MytypeKill(username)
else if (users.bedrock[username] === undefined) {
var xuid = GetUser[1];
users.bedrock[username] = {
date: CurrentData,
connected: true,
xboxID: xuid,
update: [
{
date: CurrentData,
connected: true,
}
]
}
} else {
users.bedrock[username].connected = true
users.bedrock[username].date = CurrentData
users.bedrock[username].update.push({
date: CurrentData,
connected: true,
})
}
}
// User Disconnected
else if (GetSatatus === "disconnected:") {
if (!(CheckBan(username))){
users.bedrock[username].connected = false
users.bedrock[username].date = CurrentData
users.bedrock[username].update.push({
date: CurrentData,
connected: false,
})
}
}
const file_users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(file_users);
const CurrentData = new Date();
for (let line of data.split(/\r?\n/g)) {
if (line.includes("connected:")) {
line = line.replace("[INFO] Player ", "").trim()
let GetSatatus = line.trim().split(/\s+/g)[0];
const GetUser = [];
for (let index of line.trim().replace("connected:", "").replace("dis", "").trim().split(", xuid:")) if (index !== "") GetUser.push(index.trim());
// -------------------------------------------------
var username = GetUser[0];
console.log(GetUser);
// User Connected
if (GetSatatus === "connected:") {
if (CheckBan(username)) MytypeKill(username)
else if (users.bedrock[username] === undefined) {
var xuid = GetUser[1];
users.bedrock[username] = {
date: CurrentData,
connected: true,
xboxID: xuid,
update: [
{
date: CurrentData,
connected: true,
}
]
}
} else {
users.bedrock[username].connected = true
users.bedrock[username].date = CurrentData
users.bedrock[username].update.push({
date: CurrentData,
connected: true,
})
}
}
// User Disconnected
else if (GetSatatus === "disconnected:") {
if (!(CheckBan(username))){
users.bedrock[username].connected = false
users.bedrock[username].date = CurrentData
users.bedrock[username].update.push({
date: CurrentData,
connected: false,
})
}
}
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
if (users.bedrock[username]) return true
else return false
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
if (users.bedrock[username]) return true
else return false
}
function Pocketmine(data){
const UTF8Users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(UTF8Users);
const CurrentData = new Date();
const UTF8Users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(UTF8Users);
const CurrentData = new Date();
// Init
for (let line of data.split(/\r?\n/g)) {
line = line.replace(/\[[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\] \[Server thread\/INFO\]: /, "").trim();
const currenttosave = {
username: line.replace("joined the game", "").replace("left the game", "").trim(),
join: line.includes("joined"),
left: line.includes("left")
}
if (currenttosave.join){
const username = currenttosave.username;
if (users.pocketmine[username]) {
users.pocketmine[username].connected = true
users.pocketmine[username].date = CurrentData
users.pocketmine[username].update.push({
date: CurrentData,
connected: true,
})
} else {
users.pocketmine[username] = {
connected: true,
date: CurrentData,
update: [
{
date: CurrentData,
connected: true,
}
]
}
}
}
else if (currenttosave.left){
const username = currenttosave.username;
if (users.pocketmine[username]) {
users.pocketmine[username].connected = false
users.pocketmine[username].date = CurrentData
users.pocketmine[username].update.push({
date: CurrentData,
connected: false,
})
}
}
// Init
for (let line of data.split(/\r?\n/g)) {
line = line.replace(/\[[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\] \[Server thread\/INFO\]: /, "").trim();
const currenttosave = {
username: line.replace("joined the game", "").replace("left the game", "").trim(),
join: line.includes("joined"),
left: line.includes("left")
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
return users
if (currenttosave.join){
const username = currenttosave.username;
if (users.pocketmine[username]) {
users.pocketmine[username].connected = true
users.pocketmine[username].date = CurrentData
users.pocketmine[username].update.push({
date: CurrentData,
connected: true,
})
} else {
users.pocketmine[username] = {
connected: true,
date: CurrentData,
update: [
{
date: CurrentData,
connected: true,
}
]
}
}
}
else if (currenttosave.left){
const username = currenttosave.username;
if (users.pocketmine[username]) {
users.pocketmine[username].connected = false
users.pocketmine[username].date = CurrentData
users.pocketmine[username].update.push({
date: CurrentData,
connected: false,
})
}
}
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
return users
}
function java(data){
const UTF8Users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(UTF8Users);
const CurrentData = new Date();
const UTF8Users = fs.readFileSync(GetPaths("player"), "utf8");
const users = JSON.parse(UTF8Users);
const CurrentData = new Date();
// Init
for (let line of data.split(/\r?\n/g)) {
line = line.replace(/\[[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\] \[Server thread\/INFO\]:/, "").trim();
const currenttosave = {
username: line.replace("joined the game", "").replace("left the game", "").trim(),
join: line.includes("joined the"),
left: line.includes("left the")
}
if (currenttosave.join){
const username = currenttosave.username;
if (users.java[username]) {
users.java[username].connected = true
users.java[username].date = CurrentData
users.java[username].update.push({
date: CurrentData,
connected: true,
})
} else {
users.java[username] = {
connected: true,
date: CurrentData,
update: [
{
date: CurrentData,
connected: true,
}
]
}
}
}
else if (currenttosave.left){
const username = currenttosave.username;
if (users.java[username]) {
users.java[username].connected = false
users.java[username].date = CurrentData
users.java[username].update.push({
date: CurrentData,
connected: false,
})
}
}
// Init
for (let line of data.split(/\r?\n/g)) {
line = line.replace(/\[[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\] \[Server thread\/INFO\]:/, "").trim();
const currenttosave = {
username: line.replace("joined the game", "").replace("left the game", "").trim(),
join: line.includes("joined the"),
left: line.includes("left the")
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
return users
if (currenttosave.join){
const username = currenttosave.username;
if (users.java[username]) {
users.java[username].connected = true
users.java[username].date = CurrentData
users.java[username].update.push({
date: CurrentData,
connected: true,
})
} else {
users.java[username] = {
connected: true,
date: CurrentData,
update: [
{
date: CurrentData,
connected: true,
}
]
}
}
}
else if (currenttosave.left){
const username = currenttosave.username;
if (users.java[username]) {
users.java[username].connected = false
users.java[username].date = CurrentData
users.java[username].update.push({
date: CurrentData,
connected: false,
})
}
}
}
fs.writeFileSync(GetPaths("player"), JSON.stringify(users, null, 2))
return users
}
module.exports = function (data){
if (GetPlatform() === "bedrock") return Bedrock(data);
else if (GetPlatform() === "java") return java(data);
else if (GetPlatform() === "pocketmine") return Pocketmine(data);
else if (GetPlatform() === "jsprismarine") return false
else throw new Error("Plafotform Error !!")
if (GetPlatform() === "bedrock") return Bedrock(data);
else if (GetPlatform() === "java") return java(data);
else if (GetPlatform() === "pocketmine") return Pocketmine(data);
else if (GetPlatform() === "jsprismarine") return false
else throw new Error("Plafotform Error !!")
};

View File

@ -6,342 +6,342 @@ const { GetServerPaths, GetPlatform } = require("../lib/BdsSettings");
const TOML = require("@iarna/toml");
const ConfigFilePath = {
bedrock: path.join(GetServerPaths("bedrock"), "server.properties"),
java: path.join(GetServerPaths("java"), "server.properties"),
pocketmine: path.join(GetServerPaths("pocketmine"), "server.properties"),
dragonfly: path.join(GetServerPaths("dragonfly"), "config.toml"),
bedrock: path.join(GetServerPaths("bedrock"), "server.properties"),
java: path.join(GetServerPaths("java"), "server.properties"),
pocketmine: path.join(GetServerPaths("pocketmine"), "server.properties"),
dragonfly: path.join(GetServerPaths("dragonfly"), "config.toml"),
}
// Set Config
function bds_config(NewConfig = {world: "Bds Maneger", description: "The Bds Maneger", gamemode: "creative", difficulty: "normal", players: 10, commands: true, account: true, whitelist: true, port: 19132, portv6: 19133, seed: ""}){
const BdsPlatform = GetPlatform();
const JsonConfig = {
world: "Bds Maneger",
description: "The Bds Maneger",
gamemode: "creative",
difficulty: "normal",
players: 10,
commands: true,
account: true,
whitelist: false,
port: 19132,
portv6: 19133,
seed: ""
};
const BdsPlatform = GetPlatform();
const JsonConfig = {
world: "Bds Maneger",
description: "The Bds Maneger",
gamemode: "creative",
difficulty: "normal",
players: 10,
commands: true,
account: true,
whitelist: false,
port: 19132,
portv6: 19133,
seed: ""
};
// Strings
if (typeof NewConfig.world === "string" && NewConfig.world) JsonConfig.world = NewConfig.world
if (typeof NewConfig.description === "string" && NewConfig.description) JsonConfig.description = NewConfig.description
if (typeof NewConfig.gamemode === "string" && NewConfig.gamemode) JsonConfig.gamemode = NewConfig.gamemode
if (typeof NewConfig.difficulty === "string" && NewConfig.difficulty) JsonConfig.difficulty = NewConfig.difficulty
if ((typeof NewConfig.seed === "string" || typeof NewConfig.seed === "number") && NewConfig.seed) JsonConfig.seed = NewConfig.seed
// Strings
if (typeof NewConfig.world === "string" && NewConfig.world) JsonConfig.world = NewConfig.world
if (typeof NewConfig.description === "string" && NewConfig.description) JsonConfig.description = NewConfig.description
if (typeof NewConfig.gamemode === "string" && NewConfig.gamemode) JsonConfig.gamemode = NewConfig.gamemode
if (typeof NewConfig.difficulty === "string" && NewConfig.difficulty) JsonConfig.difficulty = NewConfig.difficulty
if ((typeof NewConfig.seed === "string" || typeof NewConfig.seed === "number") && NewConfig.seed) JsonConfig.seed = NewConfig.seed
// Booleans
if (typeof NewConfig.commands === "boolean" && (NewConfig.commands || NewConfig.commands === false)) JsonConfig.commands = NewConfig.commands
if (typeof NewConfig.account === "boolean" && (NewConfig.account || NewConfig.account === false)) JsonConfig.account = NewConfig.account
if (typeof NewConfig.whitelist === "boolean" && (NewConfig.whitelist || NewConfig.whitelist === false)) JsonConfig.whitelist = NewConfig.whitelist
// Booleans
if (typeof NewConfig.commands === "boolean" && (NewConfig.commands || NewConfig.commands === false)) JsonConfig.commands = NewConfig.commands
if (typeof NewConfig.account === "boolean" && (NewConfig.account || NewConfig.account === false)) JsonConfig.account = NewConfig.account
if (typeof NewConfig.whitelist === "boolean" && (NewConfig.whitelist || NewConfig.whitelist === false)) JsonConfig.whitelist = NewConfig.whitelist
// Numbers
if (typeof NewConfig.port === "number" && NewConfig.port) JsonConfig.port = NewConfig.port
if (typeof NewConfig.players === "number" && NewConfig.players) JsonConfig.players = NewConfig.players
if (typeof NewConfig.portv6 === "number" && NewConfig.portv6) JsonConfig.portv6 = NewConfig.portv6
// Numbers
if (typeof NewConfig.port === "number" && NewConfig.port) JsonConfig.port = NewConfig.port
if (typeof NewConfig.players === "number" && NewConfig.players) JsonConfig.players = NewConfig.players
if (typeof NewConfig.portv6 === "number" && NewConfig.portv6) JsonConfig.portv6 = NewConfig.portv6
const Config = [];
if (BdsPlatform === "bedrock") {
const bedrockCPUThread = BdsInfo.GetCpuCoreCount();
var tickDistance; if (!(bedrockCPUThread % 2)) tickDistance = bedrockCPUThread; else tickDistance = 1;
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
`level-name=${JsonConfig.world}`,
`server-name=${JsonConfig.description}`,
`gamemode=${JsonConfig.gamemode}`,
`difficulty=${JsonConfig.difficulty}`,
`allow-cheats=${JsonConfig.commands}`,
`max-players=${JsonConfig.players}`,
`online-mode=${JsonConfig.account}`,
`white-list=${JsonConfig.whitelist}`,
`server-port=${JsonConfig.port}`,
`server-portv6=${JsonConfig.portv6}`,
`tick-distance=${tickDistance}`,
`max-threads=${bedrockCPUThread}`,
`level-seed=${JsonConfig.seed}`,
"default-player-permission-level=member",
"view-distance=32",
"player-idle-timeout=0",
"texturepack-required=true",
"content-log-file-enabled=false",
"compression-threshold=1",
"server-authoritative-movement=server-auth",
"player-movement-score-threshold=20",
"player-movement-distance-threshold=0.3",
"player-movement-duration-threshold-in-ms=500",
"correct-player-movement=false",
"server-authoritative-block-breaking=false",
);
} else if (BdsPlatform === "java") {
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
`level-name=${JsonConfig.world}`,
`motd=${JsonConfig.description}`,
`gamemode=${JsonConfig.gamemode}`,
`enable-command-block=${JsonConfig.commands}`,
`difficulty=${JsonConfig.difficulty}`,
`max-players=${JsonConfig.players}`,
`online-mode=${JsonConfig.account}`,
`server-port=${JsonConfig.port}`,
`hardcore=${JsonConfig}`,
`white-list=${JsonConfig}`,
`level-seed=${JsonConfig.seed}`,
"enable-rcon=false",
"query.port=65551",
"enable-jmx-monitoring=false",
"rcon.port=25575",
"enable-query=true",
"generator-settings=",
"pvp=true",
"generate-structures=true",
"network-compression-threshold=256",
"max-tick-time=60000",
"use-native-transport=true",
"enable-status=true",
"allow-flight=false",
"broadcast-rcon-to-ops=true",
"view-distance=32",
"max-build-height=256",
"server-ip=",
"allow-nether=true",
"sync-chunk-writes=true",
"op-permission-level=4",
"prevent-proxy-connections=false",
"resource-pack=",
"entity-broadcast-range-percentage=100",
"rcon.password=25as65d3",
"player-idle-timeout=0",
"force-gamemode=false",
"rate-limit=0",
"broadcast-console-to-ops=true",
"spawn-npcs=true",
"spawn-animals=true",
"snooper-enabled=true",
"function-permission-level=2",
"level-type=default",
"text-filtering-config=",
"spawn-monsters=true",
"enforce-whitelist=false",
"resource-pack-sha1=",
"spawn-protection=16",
"max-world-size=29999984",
);
} else if (BdsPlatform === "dragonfly") {
Config.push(
"",
"[Network]",
` Address = ":${JsonConfig.port}"`,
"",
"[Players]",
" Folder = \"players\"",
" MaxCount = 0",
" MaximumChunkRadius = 32",
" SaveData = true",
"",
"[Resources]",
" Folder = \"resources\"",
"",
"[Server]",
" AuthEnabled = true",
" JoinMessage = \"%v has joined the game\"",
` Name = "${JsonConfig.description}"`,
" QuitMessage = \"%v has left the game\"",
" ShutdownMessage = \"Server closed.\"",
"",
"[World]",
" Folder = \"world\"",
` Name = "${JsonConfig.world}"`,
" SimulationDistance = 8",
""
);
} else if (BdsPlatform === "pocketmine") {
// Whitelist
if (JsonConfig.whitelist === true) JsonConfig.whitelist = "on";
else JsonConfig.whitelist = "off";
const Config = [];
if (BdsPlatform === "bedrock") {
const bedrockCPUThread = BdsInfo.GetCpuCoreCount();
var tickDistance; if (!(bedrockCPUThread % 2)) tickDistance = bedrockCPUThread; else tickDistance = 1;
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
`level-name=${JsonConfig.world}`,
`server-name=${JsonConfig.description}`,
`gamemode=${JsonConfig.gamemode}`,
`difficulty=${JsonConfig.difficulty}`,
`allow-cheats=${JsonConfig.commands}`,
`max-players=${JsonConfig.players}`,
`online-mode=${JsonConfig.account}`,
`white-list=${JsonConfig.whitelist}`,
`server-port=${JsonConfig.port}`,
`server-portv6=${JsonConfig.portv6}`,
`tick-distance=${tickDistance}`,
`max-threads=${bedrockCPUThread}`,
`level-seed=${JsonConfig.seed}`,
"default-player-permission-level=member",
"view-distance=32",
"player-idle-timeout=0",
"texturepack-required=true",
"content-log-file-enabled=false",
"compression-threshold=1",
"server-authoritative-movement=server-auth",
"player-movement-score-threshold=20",
"player-movement-distance-threshold=0.3",
"player-movement-duration-threshold-in-ms=500",
"correct-player-movement=false",
"server-authoritative-block-breaking=false",
);
} else if (BdsPlatform === "java") {
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
`level-name=${JsonConfig.world}`,
`motd=${JsonConfig.description}`,
`gamemode=${JsonConfig.gamemode}`,
`enable-command-block=${JsonConfig.commands}`,
`difficulty=${JsonConfig.difficulty}`,
`max-players=${JsonConfig.players}`,
`online-mode=${JsonConfig.account}`,
`server-port=${JsonConfig.port}`,
`hardcore=${JsonConfig}`,
`white-list=${JsonConfig}`,
`level-seed=${JsonConfig.seed}`,
"enable-rcon=false",
"query.port=65551",
"enable-jmx-monitoring=false",
"rcon.port=25575",
"enable-query=true",
"generator-settings=",
"pvp=true",
"generate-structures=true",
"network-compression-threshold=256",
"max-tick-time=60000",
"use-native-transport=true",
"enable-status=true",
"allow-flight=false",
"broadcast-rcon-to-ops=true",
"view-distance=32",
"max-build-height=256",
"server-ip=",
"allow-nether=true",
"sync-chunk-writes=true",
"op-permission-level=4",
"prevent-proxy-connections=false",
"resource-pack=",
"entity-broadcast-range-percentage=100",
"rcon.password=25as65d3",
"player-idle-timeout=0",
"force-gamemode=false",
"rate-limit=0",
"broadcast-console-to-ops=true",
"spawn-npcs=true",
"spawn-animals=true",
"snooper-enabled=true",
"function-permission-level=2",
"level-type=default",
"text-filtering-config=",
"spawn-monsters=true",
"enforce-whitelist=false",
"resource-pack-sha1=",
"spawn-protection=16",
"max-world-size=29999984",
);
} else if (BdsPlatform === "dragonfly") {
Config.push(
"",
"[Network]",
` Address = ":${JsonConfig.port}"`,
"",
"[Players]",
" Folder = \"players\"",
" MaxCount = 0",
" MaximumChunkRadius = 32",
" SaveData = true",
"",
"[Resources]",
" Folder = \"resources\"",
"",
"[Server]",
" AuthEnabled = true",
" JoinMessage = \"%v has joined the game\"",
` Name = "${JsonConfig.description}"`,
" QuitMessage = \"%v has left the game\"",
" ShutdownMessage = \"Server closed.\"",
"",
"[World]",
" Folder = \"world\"",
` Name = "${JsonConfig.world}"`,
" SimulationDistance = 8",
""
);
} else if (BdsPlatform === "pocketmine") {
// Whitelist
if (JsonConfig.whitelist === true) JsonConfig.whitelist = "on";
else JsonConfig.whitelist = "off";
// difficulty
if (JsonConfig.difficulty === "easy") JsonConfig.difficulty = 0;
else if (JsonConfig.difficulty === "peaceful") JsonConfig.difficulty = 1;
else if (JsonConfig.difficulty === "normal") JsonConfig.difficulty = 2;
else if (JsonConfig.difficulty === "hard") JsonConfig.difficulty = 3;
else throw new Error("Difficulty error");
// difficulty
if (JsonConfig.difficulty === "easy") JsonConfig.difficulty = 0;
else if (JsonConfig.difficulty === "peaceful") JsonConfig.difficulty = 1;
else if (JsonConfig.difficulty === "normal") JsonConfig.difficulty = 2;
else if (JsonConfig.difficulty === "hard") JsonConfig.difficulty = 3;
else throw new Error("Difficulty error");
// Required Accoutn
if (JsonConfig.account === true) JsonConfig.account = "on";
else JsonConfig.account = "off";
// Required Accoutn
if (JsonConfig.account === true) JsonConfig.account = "on";
else JsonConfig.account = "off";
// Config
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
"language=eng",
`level-name=${JsonConfig.world}`,
`motd=${JsonConfig.description}`,
`server-port=${JsonConfig.port}`,
`white-list=${JsonConfig.whitelist}`,
`max-players=${JsonConfig.players}`,
`gamemode=${JsonConfig.gamemode}`,
`difficulty=${JsonConfig.difficulty}`,
`xbox-auth=${JsonConfig.account}`,
`level-seed=${JsonConfig.seed}`,
"view-distance=32",
"hardcore=0",
"announce-player-achievements=on",
"spawn-protection=16",
"force-gamemode=off",
"pvp=on",
"generator-settings=",
"level-type=DEFAULT",
"enable-query=on",
"enable-rcon=off",
"rcon.password=F/deZ5kefY",
"auto-save=on",
);
}
fs.writeFileSync(ConfigFilePath[BdsPlatform], Config.join("\n"))
return Config.join("\n");
// Config
Config.push(
"# By The Bds Maneger project",
`# Date: ${Date.now()}`,
"",
"language=eng",
`level-name=${JsonConfig.world}`,
`motd=${JsonConfig.description}`,
`server-port=${JsonConfig.port}`,
`white-list=${JsonConfig.whitelist}`,
`max-players=${JsonConfig.players}`,
`gamemode=${JsonConfig.gamemode}`,
`difficulty=${JsonConfig.difficulty}`,
`xbox-auth=${JsonConfig.account}`,
`level-seed=${JsonConfig.seed}`,
"view-distance=32",
"hardcore=0",
"announce-player-achievements=on",
"spawn-protection=16",
"force-gamemode=off",
"pvp=on",
"generator-settings=",
"level-type=DEFAULT",
"enable-query=on",
"enable-rcon=off",
"rcon.password=F/deZ5kefY",
"auto-save=on",
);
}
fs.writeFileSync(ConfigFilePath[BdsPlatform], Config.join("\n"))
return Config.join("\n");
}
// Get Config
function bds_get_config(){
const BdsPlatform = GetPlatform();
var config;
const JsonConfig = {
world: "",
description: "",
gamemode: "",
difficulty: "",
players: "",
whitelist: null,
portv4: 0,
portv6: 0,
};
const BdsPlatform = GetPlatform();
var config;
const JsonConfig = {
world: "",
description: "",
gamemode: "",
difficulty: "",
players: "",
whitelist: null,
portv4: 0,
portv6: 0,
};
if (BdsPlatform === "bedrock") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(ConfigFilePath["bedrock"], "utf8"));
if (BdsPlatform === "bedrock") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(ConfigFilePath["bedrock"], "utf8"));
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["server-name"];
JsonConfig.gamemode = config["gamemode"];
JsonConfig.difficulty = config["difficulty"];
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true");
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["server-name"];
JsonConfig.gamemode = config["gamemode"];
JsonConfig.difficulty = config["difficulty"];
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-portv6"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = (config["allow-cheats"] === "true");
// JsonConfig.worldtype = "default";
}
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-portv6"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = (config["allow-cheats"] === "true");
// JsonConfig.worldtype = "default";
}
else if (BdsPlatform === "java") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["java"], "server.properties"), "utf8"));
}
else if (BdsPlatform === "java") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["java"], "server.properties"), "utf8"));
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["motd"];
JsonConfig.gamemode = config["gamemode"];
JsonConfig.difficulty = config["difficulty"];
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true");
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["motd"];
JsonConfig.gamemode = config["gamemode"];
JsonConfig.difficulty = config["difficulty"];
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = (config["enable-command-block"] === "true");
// JsonConfig.worldtype = config["level-type"];
}
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = (config["enable-command-block"] === "true");
// JsonConfig.worldtype = config["level-type"];
}
else if (BdsPlatform === "pocketmine") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["pocketmine"], "server.properties"), "utf8"));
}
else if (BdsPlatform === "pocketmine") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["pocketmine"], "server.properties"), "utf8"));
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["motd"];
JsonConfig.gamemode = (()=>{let test = parseInt(config["gamemode"]);if (test === 0) return "survival";else if (test === 1) return "creative";else return undefined;})();
JsonConfig.difficulty = (()=>{let test = parseInt(config["difficulty"]);if (test === 0) return "easy";else if (test === 1) return "peaceful";else if (test === 2) return "normal";else if (test === 3) return "hard";else return undefined;})();
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["xbox-auth"] === "on");
JsonConfig.whitelist = (config["white-list"] === "true");
// Players
JsonConfig.world = config["level-name"];
JsonConfig.description = config["motd"];
JsonConfig.gamemode = (()=>{let test = parseInt(config["gamemode"]);if (test === 0) return "survival";else if (test === 1) return "creative";else return undefined;})();
JsonConfig.difficulty = (()=>{let test = parseInt(config["difficulty"]);if (test === 0) return "easy";else if (test === 1) return "peaceful";else if (test === 2) return "normal";else if (test === 3) return "hard";else return undefined;})();
JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["xbox-auth"] === "on");
JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = false;
// JsonConfig.worldtype = config["level-type"];
}
} else if (BdsPlatform === "dragonfly") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
const ConfigFile = TOML.parse(fs.readFileSync(ConfigFilePath[BdsPlatform], "utf8"));
JsonConfig.world = ConfigFile.World.Name;
JsonConfig.description = ConfigFile.Server.Name;
JsonConfig.gamemode = "creative";
JsonConfig.difficulty = null;
JsonConfig.players = parseInt(ConfigFile.Players.MaxCount || 0);
JsonConfig.account = false;
JsonConfig.whitelist = null;
JsonConfig.portv4 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.portv6 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.seed = null;
JsonConfig.commands = false;
}
} else throw new Error("Platform no exists, check config file");
return JsonConfig;
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"];
JsonConfig.commands = false;
// JsonConfig.worldtype = config["level-type"];
}
} else if (BdsPlatform === "dragonfly") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
const ConfigFile = TOML.parse(fs.readFileSync(ConfigFilePath[BdsPlatform], "utf8"));
JsonConfig.world = ConfigFile.World.Name;
JsonConfig.description = ConfigFile.Server.Name;
JsonConfig.gamemode = "creative";
JsonConfig.difficulty = null;
JsonConfig.players = parseInt(ConfigFile.Players.MaxCount || 0);
JsonConfig.account = false;
JsonConfig.whitelist = null;
JsonConfig.portv4 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.portv6 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.seed = null;
JsonConfig.commands = false;
}
} else throw new Error("Platform no exists, check config file");
return JsonConfig;
}
// Get Withelist
function bds_get_whitelist(){
const BdsPlatform = GetPlatform();
const ToReturn = [];
const BdsPlatform = GetPlatform();
const ToReturn = [];
// Bedrock
if (BdsPlatform === "bedrock") {
if (fs.existsSync(path.join(GetServerPaths("bedrock"), "whitelist.json"))) {
const LocalWhitelist = JSON.parse(fs.readFileSync(path.join(GetServerPaths("bedrock"), "whitelist.json"), "utf8"));
for (let i = 0; i < LocalWhitelist.length; i++) {
const Player = LocalWhitelist[i];
ToReturn.push({
name: Player.name,
// permissons: Player.permission,
});
}
}
// Bedrock
if (BdsPlatform === "bedrock") {
if (fs.existsSync(path.join(GetServerPaths("bedrock"), "whitelist.json"))) {
const LocalWhitelist = JSON.parse(fs.readFileSync(path.join(GetServerPaths("bedrock"), "whitelist.json"), "utf8"));
for (let i = 0; i < LocalWhitelist.length; i++) {
const Player = LocalWhitelist[i];
ToReturn.push({
name: Player.name,
// permissons: Player.permission,
});
}
}
}
// Pocketmine
else if (BdsPlatform === "pocketmine") {
throw new Error("Not implemented yet");
}
// Pocketmine
else if (BdsPlatform === "pocketmine") {
throw new Error("Not implemented yet");
}
// Java and Spigot
else if (BdsPlatform === "java" || BdsPlatform === "spigot") {
throw new Error("Not implemented yet");
}
// Java and Spigot
else if (BdsPlatform === "java" || BdsPlatform === "spigot") {
throw new Error("Not implemented yet");
}
// If not exists Platform return throw
else throw new Error("Platform no exists, check config file");
// If not exists Platform return throw
else throw new Error("Platform no exists, check config file");
return ToReturn;
return ToReturn;
}
// Export modules

View File

@ -3,41 +3,41 @@ const { existsSync, readFileSync } = require("fs")
const { join } = require("path")
function CheckTelegramUser(admin_name){
for(let admin_check of GetTelegramAdmins()){
if (admin_name === admin_check || admin_check === "all_users") return true;
}
return false
for(let admin_check of GetTelegramAdmins()){
if (admin_name === admin_check || admin_check === "all_users") return true;
}
return false
}
function CheckPlayer(player = "null"){
const json = require(GetPaths("player"))[GetPlatform()];
if (json[player]) return true; else return false
const json = require(GetPaths("player"))[GetPlatform()];
if (json[player]) return true; else return false
}
function token_verify(token){
const path_tokens = join(bds_dir, "bds_tokens.json");
if (existsSync(path_tokens)) var tokens = JSON.parse(readFileSync(path_tokens, "utf8")); else return false
for (let token_verify of tokens) {
const element = token_verify.token
if (element === token) return true
}
return false
const path_tokens = join(bds_dir, "bds_tokens.json");
if (existsSync(path_tokens)) var tokens = JSON.parse(readFileSync(path_tokens, "utf8")); else return false
for (let token_verify of tokens) {
const element = token_verify.token
if (element === token) return true
}
return false
}
function CheckBan(player){
var players = GetServerBan();
for(let check_ in players){
const admin_check = players[check_]
if (player === admin_check.username) {
if (admin_check[GetPlatform()]) return true
}
var players = GetServerBan();
for(let check_ in players){
const admin_check = players[check_]
if (player === admin_check.username) {
if (admin_check[GetPlatform()]) return true
}
return false
}
return false
}
module.exports = {
CheckTelegramUser,
CheckPlayer,
CheckBan,
token_verify
CheckTelegramUser,
CheckPlayer,
CheckBan,
token_verify
}

435
src/api.js Normal file
View File

@ -0,0 +1,435 @@
// Node Modules
const os = require("os");
const fs = require("fs");
// Bds Maneger Core
const BdsManegerCore = require("../index");
const BdsSystemInfo = require("../lib/BdsSystemInfo");
const BdsChecks = require("./UsersAndtokenChecks");
const BdsSettings = require("../lib/BdsSettings");
// Init Express
const express = require("express");
const app = express();
// Express Middleware
const rateLimit = require("express-rate-limit");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
const pretty = require("express-prettify");
const cors = require("cors");
app.use(cors());
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */
app.use(bodyParser.urlencoded({ extended: true }));
app.use(rateLimit({windowMs: 15 * 60 * 1000, /* 15 minutes */ max: 100 /* limit each IP to 100 requests per windowMs*/ }));
app.use(pretty({always: true, spaces: 2}));
app.use(fileUpload({limits: { fileSize: 512 * 1024 }}));
app.use(require("request-ip").mw());
// Routes
app.all(["/v2", "/v2/*"], ({res}) => res.status(401).json({
Error: "v2 route moved to root routes"
}));
// ? /bds/
app.get(["/bds/info", "/bds", "/"], ({res}) => {
try {
const BdsConfig = BdsManegerCore.getBdsConfig();
const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
const Info = {
core: {
version: BdsManegerCore.package_json.version,
Total_dependencies: Object.keys(BdsManegerCore.package_json.dependencies).length + Object.keys(BdsManegerCore.package_json.devDependencies).length,
},
server: {
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
versions: BdsConfig.server.versions,
players: {
online: Online.length,
offline: Offline.length,
}
},
host: {
System: process.platform,
Arch: BdsManegerCore.arch,
Kernel: BdsSystemInfo.GetKernel(),
Cpu_Model: (os.cpus()[0] || {}).model || null,
IsDocker: false,
IsNpx: false,
IsCLI: false,
}
}
if (process.env.BDS_DOCKER_IMAGE) Info.host.IsDocker = true;
if (process.env.npm_lifecycle_event === "npx") Info.host.IsNpx = true;
if (process.env.IS_BDS_CLI) Info.host.IsCLI = true;
res.json(Info);
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
// Server Info
app.get("/bds/info/server", ({res}) => {
let ServerRunner = require("./BdsManegerServer").BdsRun;
if (!ServerRunner)ServerRunner = {};
try {
const BdsConfig = BdsManegerCore.getBdsConfig();
const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
const Info = {
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
Platform: BdsSettings.GetPlatform(),
players: {
online: Online.length,
offline: Offline.length,
},
Config: BdsManegerCore.get_config(),
Process: {
PID: ServerRunner.pid || 0,
Uptime: ServerRunner.uptime || 0,
StartTime: ServerRunner.StartTime || NaN,
}
}
res.json(Info);
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
// Whitelist
app.get("/bds/info/server/whitelist", (req, res) => {
const ServerConfig = BdsManegerCore.get_config();
if (ServerConfig.whitelist) {
const { Token = null , Action = null } = req.query;
const WgiteList = BdsSettings.get_whitelist();
if (Action) {
if (Action === "add") {
if (WgiteList.findIndex(WL => WL.Token === Token) === -1) {
WgiteList.push({
Token: Token,
Time: Date.now()
});
fs.writeFileSync(BdsManegerCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
res.json({
success: true,
message: "Whitelist Added"
});
} else {
res.json({
success: false,
message: "Whitelist Already Exist"
});
}
} else if (Action === "remove") {
if (WgiteList.findIndex(WL => WL.Token === Token) !== -1) {
WgiteList.splice(WgiteList.findIndex(WL => WL.Token === Token), 1);
fs.writeFileSync(BdsManegerCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
res.json({
success: true,
message: "Whitelist Removed"
});
} else {
res.json({
success: false,
message: "Whitelist Not Found"
});
}
} else {
res.json({
success: false,
message: "Invalid Action"
});
}
} else {
res.json(WgiteList)
}
} else {
res.status(400).json({
error: "Whitelist Not Enabled"
});
}
});
// Download Server
app.get("/bds/download_server", (req, res) => {
const { Token = null, Version = "latest" } = req.query;
// Check is Token is String
if (!Token) return res.status(400).json({
error: "Bad Request",
message: "Token is required"
});
// Check Token
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
error: "Bad Request",
message: "Token is invalid"
});
// Download Server
BdsManegerCore.download(Version, true).then(() => {
res.json({
message: "Server Downloaded"
});
}).catch(error => {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
});
});
// Update/Set Server Settings
app.post("/bds/save_settings", (req, res) => {
const { Token = null,
WorldName = "Bds Maneger",
ServerDescription = "The Bds Maneger",
DefaultGamemode = "creative",
ServerDifficulty = "normal",
MaxPlayer = "10",
WorldSeed = "",
AllowCommands = "true",
RequireLogin = "true",
EnableWhitelist = "false",
port_v4 = "19132",
port_v6 = "19133",
} = req.body;
// Check is Token is String
if (!Token) return res.status(400).json({
error: "Bad Request",
message: "Token is required"
});
// Check Token
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
error: "Bad Request",
message: "Token is invalid"
});
// Save Settings
try {
BdsManegerCore.set_config({
world: WorldName,
description: ServerDescription,
gamemode: DefaultGamemode,
difficulty: ServerDifficulty,
players: parseInt(MaxPlayer) || 10,
commands: AllowCommands === "true",
account: RequireLogin === "true",
whitelist: EnableWhitelist === "true",
port: parseInt(port_v4) || 19132,
portv6: parseInt(port_v6) || 19133,
seed: WorldSeed || "",
});
res.json({
message: "Settings Saved",
Config: {
world: WorldName,
description: ServerDescription,
gamemode: DefaultGamemode,
difficulty: ServerDifficulty,
seed: WorldSeed || "",
players: parseInt(MaxPlayer) || 10,
commands: AllowCommands === "true",
account: RequireLogin === "true",
whitelist: EnableWhitelist === "true",
port: parseInt(port_v4) || 19132,
portv6: parseInt(port_v6) || 19133,
}
});
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
// Bds Maneger Bridge Communication
app.get("/bds/bridge", (req, res) => {
const ServerHost = require("./BdsNetwork").host || req.headers.host.replace(/^(.*?):\d+$/, (match, p1) => p1) || require("./BdsNetwork").externalIP.ipv4;
const ServerConfig = BdsManegerCore.get_config();
res.json({
host: ServerHost,
port: ServerConfig.portv4,
});
});
// ? /player
const GetPlayerJson = (Platform = BdsManegerCore.getBdsConfig().server.platform) => ([...{...JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))}[Platform]]);
app.get("/players", (req, res) => {
const { Platform = BdsSettings.GetPlatform(), Player = null, Action = null } = req.query;
let PlayerList = GetPlayerJson(Platform);
if (Player) PlayerList = PlayerList.filter(PLS => PLS.Player === Player);
if (Action) PlayerList = PlayerList.filter(PLS => PLS.Action === Action);
if (Player || Action) {
if (PlayerList.length > 0) res.json(PlayerList);
else res.status(404).json({
Error: "Player not found",
querys: req.query
});
return;
}
res.json(PlayerList);
return;
});
// Players Actions in Backside Manager
// kick player
app.get("/players/kick", (req, res) => {
const { Token = null, Player = "Sirherobrine", Text = "You have been removed from the Server" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Kick player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.kick(Player, Text);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Ban player
app.get("/players/ban", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Ban player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.ban(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Op player
app.get("/players/op", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Op player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.op(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Deop player
app.get("/players/deop", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Deop player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.deop(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Say to Server
app.get("/players/say", (req, res) => {
const { Token = null, Text = "Hello Server" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Say to Server
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.say(Text);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Tp player
app.get("/players/tp", (req, res) => {
const { Token = null, Player = "Sirherobrine", X = 0, Y = 0, Z = 0 } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Tp player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.tp(Player, {
x: X,
y: Y,
z: Z
});
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Export API Routes
function API(port_api = 1932, callback = port => {console.log("Bds Maneger Core REST API, http port", port)}){
const MapRoutes = app._router.stack.map(d => {if (d.route) {if (d.route.path) return d.route.path;else return d.route.regexp.source;} else return null;}).filter(d => d);
app.all("*", (req, res) => {
return res.status(404).json({
error: "Not Found",
message: "The requested URL " + req.originalUrl || req.path + " was not found on this server.",
AvaibleRoutes: MapRoutes
});
});
const port = (port_api || 1932);
app.listen(port, () => {
if (typeof callback === "function") callback(port);
});
return port;
}
function MainAPI(apiConfig = {api_port: 1932}, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){
var port_rest = 1932;
if (typeof apiConfig === "object" && apiConfig.api_port !== undefined) port_rest = apiConfig.api_port;
else if (typeof apiConfig === "number") port_rest = apiConfig;
return API(port_rest, callback);
}
module.exports = MainAPI;
module.exports.api = API;
module.exports.BdsRoutes = app;

View File

@ -1,80 +0,0 @@
const { readFileSync, existsSync } = require("fs");
const { resolve } = require("path");
const express = require("express");
const cors = require("cors");
const rateLimit = require("express-rate-limit");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
const { GetPaths } = require("../../lib/BdsSettings")
const pretty = require("express-prettify");
const latest_log = resolve(GetPaths("log"), "latest.log")
const docs = require("../../BdsManegerInfo.json").docs;
const app = express();
// Enable if you"re behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set("trust proxy", 1);
app.use(cors());
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */
app.use(bodyParser.urlencoded({ extended: true }));
app.use(rateLimit({windowMs: 15 * 60 * 1000, /* 15 minutes */ max: 100 /* limit each IP to 100 requests per windowMs*/ }));
app.use(pretty({always: true, spaces: 2}));
app.use(fileUpload({limits: { fileSize: 512 * 1024 }}));
app.use(require("request-ip").mw());
// Bds route
app.use("/bds", require("./routes/bds"))
app.use("/players", require("./routes/players"))
app.post("/bds_command", ({res}) => res.redirect("/bds/command"))
app.get("/info", ({ res }) => res.redirect("bds/info"))
// Server Sevices
app.all("/service", ({res}) => res.redirect(`${docs.url}/${docs.rest_api}#disable-basic-services`));
app.get("/log", (req, res) => {
if (!(existsSync(latest_log))) return res.sendStatus(400);
let RequestConfig = {format: req.query.format, text: readFileSync(latest_log, "utf8").toString().split(/\r\n|\n/gi).filter(d => d).join("\n")};
if (RequestConfig.format === "html") {
var text = ""
for (let log of RequestConfig.text.split(/\r\n|\n/gi)) text += `<div class="BdsCoreLog"><p>${log}</p></div>`;
res.send(text);
} else res.json(RequestConfig.text.split(/\r\n|\n/gi));
});
// V2
const BdsV2 = require("./v2/routes/bds"), PlayerV2 = require("./v2/routes/player");
app.use("/v2", BdsV2);
app.get("/v2", (req, res) => res.redirect("/v2/info"));
app.all("/", ({res}) => res.redirect("/v2/info"));
app.all("/v2/bds/*", (req, res) => res.redirect(`/v2/${req.path.replace("/v2/bds/", "")}`));
app.use("/v2/players", PlayerV2);
// module exports
function api(port_api = 1932, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){
const port = (port_api || 1932);
const MapRoutes = app._router.stack.map(d => {if (d.route) {if (d.route.path) return d.route.path; else return d.route.regexp.source;} else return null;}).filter(d => d);
MapRoutes.push(...PlayerV2.APIPaths.map(Player => ("/v2/players"+ Player)));
MapRoutes.push(...BdsV2.APIPaths.map(Bds => ("/v2/bds"+ Bds)));
app.all("*", (req, res)=>{
res.status(404).json({
error: "Not Found",
message: "The requested URL " + req.originalUrl + " was not found on this server.",
AvaibleRoutes: MapRoutes,
MoreInfo: `${docs.url}/${docs.rest_api}`
});
});
app.listen(port)
if (typeof callback === "function") callback(port);
return port;
}
module.exports = function (apiConfig = {api_port: 1932}, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){
var port_rest = 1932;
if (typeof apiConfig === "object" && apiConfig.api_port !== undefined) port_rest = apiConfig.api_port;
else if (typeof apiConfig === "number") port_rest = apiConfig;
return api(port_rest, callback);
}
module.exports.api = api;
// Export Route
module.exports.BdsRoutes = app;

View File

@ -1,101 +0,0 @@
const express = require("express");
const app = express.Router();
const { GetKernel } = require("../../../lib/BdsSystemInfo");
const commandExist = require("../../../lib/commandExist");
const { GetPlatform, GetServerVersion, UpdatePlatform, bds_dir } = require("../../../lib/BdsSettings");
const admzip = require("adm-zip");
const bds = require("../../../index");
const { token_verify } = require("../../UsersAndtokenChecks");
// Backup
app.get("/backup", (req, res) => {
const { token } = req.query;
// Check Token
if (!(token_verify(token))) return res.status(401).send("Check your token");
// Return File
const backup = bds.backup()
return res.sendFile(backup.file_path)
});
// bds maneger
app.post("/download", (req, res) => {
const { token, version, platform } = req.body
if (!(token_verify(token))) return res.status(401).send("Check your token");
// Server Download
if (platform) UpdatePlatform(platform);
try {
bds.download(version, true, function(){
return res.json({
version: version,
platform: GetPlatform()
})
})
} catch (error) {
res.status(501).send("Unable to download server for current platform, more details will be in terminal log!")
}
});
app.post("/upload", (req, res) => {
const { token } = req.headers;
if (!(token_verify(token))) return res.status(401).send("Check your token");
if (!req.files || Object.keys(req.files).length === 0) return res.status(400).send("No files were uploaded.");
// Extract
for (let index of Object.getOwnPropertyNames(req.files)){
const fileWorld = req.files[index];
const unzip = new admzip(Buffer.from(fileWorld.data));
unzip.extractAllTo(bds_dir)
}
return res.send("Ok")
});
// Command
app.post("/command", (req, res) => {
const body = req.body;
var comand = body.command
const status = {
code: 401,
status: false
}
if (token_verify(body.token)) {
bds.command(comand)
status.code = 201
status.status = true
}
res.status(status.code).send(status)
});
// System and Server info
app.get("/info", ({ res }) => {
const config = bds.get_config();
var info = {
server: {
world_name: config.world,
running: bds.detect(),
port: config.portv4,
port6: config.portv6,
max_players: config.players,
whitelist: config.whitelist,
},
sys: {
arch: bds.arch,
system: process.platform,
Kernel: GetKernel(),
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"),
},
bds_maneger_core: {
platform: GetPlatform(),
version: bds.package_json.version,
server_versions: GetServerVersion(),
}
};
return res.send(info);
});
module.exports = app;

View File

@ -1,55 +0,0 @@
const express = require("express");
const app = express.Router();
const { GetPlatform, GetPaths } = require("../../../lib/BdsSettings")
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) => {
var { player, status, platform} = req.query;
const players_json = JSON.parse(readFileSync(GetPaths("player"), "utf8"))[(platform || GetPlatform())];
var response = {};
if (player) {
if (players_json[player]) response = players_json[player];
else response = {
date: null,
connected: null,
xboxID: null,
update: [{date: null, connected: null}]
}
return res.json(response);
} else if (status) {
status = (() => {if (status === "online" || status === "true") return true; else return false})()
for (let index of Object.getOwnPropertyNames(players_json)) if (players_json[index].connected === status) response[index] = players_json[index]
return res.json(response);
}
response = players_json
return res.json(response);
});
app.get("/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => {
const { TYPE, TOKEN, PLAYER } = req.params;
const { text } = req.query;
// Pre Check
if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters");
const bds = GetSessions()
// Post Check
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
app.all("/actions/*", ({ res }) => res.send(`${docs.url}/${docs.rest_api}#players-actions`))
app.all("/*", ({ res }) => res.send(`${docs.url}/${docs.rest_api}#players-actions`))
module.exports = app;

View File

@ -1,261 +0,0 @@
// Node Internal modules
const fs = require("fs");
const os = require("os");
// Bds Manager Core modules
const BdsCore = require("../../../../index");
const BdsSystemInfo = require("../../../../lib/BdsSystemInfo");
const BdsChecks = require("../../../UsersAndtokenChecks");
const BdsSettings = require("../../../../lib/BdsSettings");
// Express
const express = require("express");
const { get_whitelist } = require("../../../ServerSettings");
const app = express.Router();
// Routes
app.get("/info", ({res}) => {
try {
const BdsConfig = BdsCore.getBdsConfig();
const Players = JSON.parse(fs.readFileSync(BdsCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
const Info = {
core: {
version: BdsCore.package_json.version,
Total_dependencies: Object.keys(BdsCore.package_json.dependencies).length + Object.keys(BdsCore.package_json.devDependencies).length,
},
server: {
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
versions: BdsConfig.server.versions,
players: {
online: Online.length,
offline: Offline.length,
}
},
host: {
System: process.platform,
Arch: BdsCore.arch,
Kernel: BdsSystemInfo.GetKernel(),
Cpu_Model: (os.cpus()[0] || {}).model || null,
IsDocker: false,
IsNpx: false,
IsCLI: false,
}
}
if (process.env.BDS_DOCKER_IMAGE) Info.host.IsDocker = true;
if (process.env.npm_lifecycle_event === "npx") Info.host.IsNpx = true;
if (process.env.IS_BDS_CLI) Info.host.IsCLI = true;
res.json(Info);
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
// Server Info
app.get("/info/server", ({res}) => {
let ServerRunner = require("../../../BdsManegerServer").BdsRun;
if (!ServerRunner)ServerRunner = {};
try {
const BdsConfig = BdsCore.getBdsConfig();
const Players = JSON.parse(fs.readFileSync(BdsCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
const Info = {
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
Platform: BdsSettings.GetPlatform(),
players: {
online: Online.length,
offline: Offline.length,
},
Config: BdsCore.get_config(),
Process: {
PID: ServerRunner.pid || 0,
Uptime: ServerRunner.uptime || 0,
StartTime: ServerRunner.StartTime || NaN,
}
}
res.json(Info);
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
// Whitelist
app.get("/info/server/whitelist", (req, res) => {
const ServerConfig = BdsCore.get_config();
if (ServerConfig.whitelist) {
const { Token = null , Action = null } = req.query;
const WgiteList = get_whitelist();
if (Action) {
if (Action === "add") {
if (WgiteList.findIndex(WL => WL.Token === Token) === -1) {
WgiteList.push({
Token: Token,
Time: Date.now()
});
fs.writeFileSync(BdsCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
res.json({
success: true,
message: "Whitelist Added"
});
} else {
res.json({
success: false,
message: "Whitelist Already Exist"
});
}
} else if (Action === "remove") {
if (WgiteList.findIndex(WL => WL.Token === Token) !== -1) {
WgiteList.splice(WgiteList.findIndex(WL => WL.Token === Token), 1);
fs.writeFileSync(BdsCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
res.json({
success: true,
message: "Whitelist Removed"
});
} else {
res.json({
success: false,
message: "Whitelist Not Found"
});
}
} else {
res.json({
success: false,
message: "Invalid Action"
});
}
} else {
res.json(WgiteList)
}
} else {
res.status(400).json({
error: "Whitelist Not Enabled"
});
}
});
// Download Server
app.get("/download_server", (req, res) => {
const { Token = null, Version = "latest" } = req.query;
// Check is Token is String
if (!Token) return res.status(400).json({
error: "Bad Request",
message: "Token is required"
});
// Check Token
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
error: "Bad Request",
message: "Token is invalid"
});
// Download Server
BdsCore.download(Version, true).then(() => {
res.json({
message: "Server Downloaded"
});
}).catch(error => {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
});
});
// Update/Set Server Settings
app.post("/save_settings", (req, res) => {
const { Token = null,
WorldName = "Bds Maneger",
ServerDescription = "The Bds Maneger",
DefaultGamemode = "creative",
ServerDifficulty = "normal",
MaxPlayer = "10",
WorldSeed = "",
AllowCommands = "true",
RequireLogin = "true",
EnableWhitelist = "false",
port_v4 = "19132",
port_v6 = "19133",
} = req.body;
// Check is Token is String
if (!Token) return res.status(400).json({
error: "Bad Request",
message: "Token is required"
});
// Check Token
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
error: "Bad Request",
message: "Token is invalid"
});
// Save Settings
try {
BdsCore.set_config({
world: WorldName,
description: ServerDescription,
gamemode: DefaultGamemode,
difficulty: ServerDifficulty,
players: parseInt(MaxPlayer) || 10,
commands: AllowCommands === "true",
account: RequireLogin === "true",
whitelist: EnableWhitelist === "true",
port: parseInt(port_v4) || 19132,
portv6: parseInt(port_v6) || 19133,
seed: WorldSeed || "",
});
res.json({
message: "Settings Saved",
Config: {
world: WorldName,
description: ServerDescription,
gamemode: DefaultGamemode,
difficulty: ServerDifficulty,
seed: WorldSeed || "",
players: parseInt(MaxPlayer) || 10,
commands: AllowCommands === "true",
account: RequireLogin === "true",
whitelist: EnableWhitelist === "true",
port: parseInt(port_v4) || 19132,
portv6: parseInt(port_v6) || 19133,
}
});
} catch (error) {
res.status(500).json({
error: "Backend Error",
message: `${error}`
});
}
});
app.get("/save_settings", ({res}) => res.status(404).json({
error: "This route is POST, Error 404"
}));
// Bds Maneger Bridge Communication
app.get("/bridge", (req, res) => {
const ServerHost = require("../../../BdsNetwork").host || req.headers.host.replace(/^(.*?):\d+$/, (match, p1) => p1) || require("../../../BdsNetwork").externalIP.ipv4;
const ServerConfig = BdsCore.get_config();
res.json({
host: ServerHost,
port: ServerConfig.portv4,
});
});
// Exports the routes
module.exports = app;
module.exports.APIPaths = [...app.stack.map(d => {
if (d.route) {
if (d.route.path) return d.route.path;
else return d.route.regexp.source;
}
return null;
}).filter(d => d)];

View File

@ -1,162 +0,0 @@
// Node Internal modules
const fs = require("fs");
// Bds Manager Core modules
const BdsCore = require("../../../../index");
const BdsChecks = require("../../../UsersAndtokenChecks");
const BdsSettings = require("../../../../lib/BdsSettings");
// Express
const express = require("express");
const app = express.Router();
// Find Player
const GetPlayerJson = (Platform = BdsCore.getBdsConfig().server.platform) => ([...{...JSON.parse(fs.readFileSync(BdsCore.BdsSettigs.GetPaths("player"), "utf8"))}[Platform]]);
// Routes
app.get("/", (req, res) => {
const { Platform = BdsSettings.GetPlatform(), Player = null, Action = null } = req.query;
let PlayerList = GetPlayerJson(Platform);
if (Player) PlayerList = PlayerList.filter(PLS => PLS.Player === Player);
if (Action) PlayerList = PlayerList.filter(PLS => PLS.Action === Action);
if (Player || Action) {
if (PlayerList.length > 0) res.json(PlayerList);
else res.status(404).json({
Error: "Player not found",
querys: req.query
});
return;
}
res.json(PlayerList);
return;
});
// Players Actions in Backside Manager
// kick player
app.get("/kick", (req, res) => {
const { Token = null, Player = "Sirherobrine", Text = "You have been removed from the Server" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Kick player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.kick(Player, Text);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Ban player
app.get("/ban", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Ban player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.ban(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Op player
app.get("/op", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Op player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.op(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Deop player
app.get("/deop", (req, res) => {
const { Token = null, Player = "Sirherobrine" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Deop player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.deop(Player);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Say to Server
app.get("/say", (req, res) => {
const { Token = null, Text = "Hello Server" } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Say to Server
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.say(Text);
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Tp player
app.get("/tp", (req, res) => {
const { Token = null, Player = "Sirherobrine", X = 0, Y = 0, Z = 0 } = req.query;
if (!Token) return res.status(400).json({ error: "Token is required" });
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
// Tp player
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
try {
RunnerServer.tp(Player, {
x: X,
y: Y,
z: Z
});
res.json({ success: true });
} catch (error) {
res.status(400).json({
error: "Server nots Run",
text: `${error}`
});
}
});
// Export Routes
module.exports = app;
module.exports.APIPaths = [...app.stack.map(d => {
if (d.route) {
if (d.route.path) return d.route.path;
else return d.route.regexp.source;
}
return null;
}).filter(d => d)];