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
26 changed files with 2265 additions and 2748 deletions
Showing only changes of commit 20c23071c4 - Show all commits

38
.vscode/launch.json vendored
View File

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

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", "temp_host": {
"docs": { "url": "http://hosts.bdsmaneger.com:3020"
"url": "https://docs.bdsmaneger.com", },
"main": "Bds Maneger core", "Fetchs": {
"rest_api": "docs/Bds Maneger core/REST API/" "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": { "java": {
"url": "http://hosts.bdsmaneger.com:3020" "value": null,
"regex": false
}, },
"Fetchs": { "pocketmine": {
"php": "https://raw.githubusercontent.com/The-Bds-Maneger/Php_Static_Binary/main/binarys.json", "value": null,
"servers": "https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Server.json" "regex": false
}, },
"IgnoreLog": { "spigot": {
"bedrock": [ "value": null,
{ "regex": false
"value": "Running AutoCompaction",
"regex": true
}
],
"java": [],
"pocketmine": [],
"spigot": [],
"dragonfly": []
}, },
"StartedServer": { "dragonfly": {
"bedrock": { "value": null,
"value": "Server started", "regex": false
"regex": true }
}, },
"java": { "Servers": {
"value": null, "bedrock": {
"regex": false "stop": {
}, "value": "stop",
"pocketmine": { "type": "command"
"value": null, },
"regex": false "op": {
}, "value": "op \"{{}}\"",
"spigot": { "type": "command"
"value": null, },
"regex": false "deop": "op \"{{Player}}\"",
}, "ban": "tp \"{{Player}}\" ~ ~99999 ~",
"dragonfly": { "kick": "kick \"{{Player}}\" \"{{Text}}\"",
"value": null, "tp": "tp \"{{Player}}\" {{X}} {{Y}} {{X}}",
"regex": false "say": "say {{Text}}"
}
}, },
"Servers": { "java": {
"bedrock": { "stop": "stop",
"stop": { "op": "op {{Player}}",
"value": "stop", "deop": "op {{Player}}",
"type": "command" "ban": "ban {{Player}}",
}, "kick": "kick {{Player}} {{Text}}",
"op": { "tp": "tp {{Player}} {{X}} {{Y}} {{X}}",
"value": "op \"{{}}\"", "say": "say {{Text}}"
"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
}
}
}, },
"contributors": [ "pocketmine": {
{ "stop": {
"name": "Matheus Sampaio Queiroga", "value": "stop",
"email": "srherobrine20@gmail.com", "type": "command"
"url": "https://sirherobrine23.org/?from=the-bds-maneger-project" },
} "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. All options can be found in the bds maneger core documentation.
`npx --package=@the-bds-maneger/core@latest bds_maneger -sk` `npx @the-bds-maneger/core@latest -sk`
### Telegram Bot
`npx --package=@the-bds-maneger/core@latest bds_telegram`
## Install Bds Maneger Core globally ## 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 #!/usr/bin/env node
if (process.platform === "win32") process.title = "Bds Maneger CLI"; else process.title = "Bds-Manger-CLI"; 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; process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
// Internal Modules
const fs = require("fs");
const path = require("path");
// External Modules // External Modules
const cli_color = require("cli-color"); const cli_color = require("cli-color");
@ -14,10 +17,37 @@ const BdsCore = require("../index");
const BdsNetwork = require("../src/BdsNetwork"); const BdsNetwork = require("../src/BdsNetwork");
const commandExits = require("../lib/commandExist"); const commandExits = require("../lib/commandExist");
const readline = require("readline"); const readline = require("readline");
// const BdsMenus = require("./bds_maneger/menus");
const { PlatformVersionsV2 } = require("../src/BdsServersDownload"); const { PlatformVersionsV2 } = require("../src/BdsServersDownload");
const { GetPlatform } = require("../lib/BdsSettings"); 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(`${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() { async function DownloadServer() {
const ora = (await import("ora")).default; const ora = (await import("ora")).default;
const PlatformVersion = await PlatformVersionsV2() const PlatformVersion = await PlatformVersionsV2()
@ -64,27 +94,33 @@ async function help() {
const help = [ const help = [
`Bds Maneger CLI version: ${cli_color.magentaBright(BdsCore.package_json.version)}`, `Bds Maneger CLI version: ${cli_color.magentaBright(BdsCore.package_json.version)}`,
`System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(BdsCore.arch)}`, `System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(BdsCore.arch)}`,
"**************************************************************", "",
"* Usage: bds-maneger-cli [options]", " Usage: bds-maneger-cli [options]",
"*", "",
"* Options:", " Options:",
"* -h, --help Print this help", " -h, --help Print this help",
"* -i, --info Print info about Bds Maneger Core and Platforms", " -i, --info Print info about Bds Maneger Core and Platforms",
"* -d, --download Download a server", " -d, --download Download a server",
"* -s, --start Start a server", " -s, --start Start a server",
"* --get_domain Get temporary public domain to connect in to server or API", " -k, --kill Kill Server if running",
"* -p, --platform Change the platform", " --get_domain Get temporary public domain to connect in to server or API",
"* -n, --no-api Don't start the Bds Maneger API Rest", " -p, --platform Change the platform",
"*", " -n, --no-api Don't start the Bds Maneger API Rest",
"* Examples:", "",
"* bds-maneger-cli -d", ...MoreHelp,
"* bds-maneger-cli -s", "",
"* bds-maneger-cli -p bedrock", " Examples:",
"* bds-maneger-cli -i", " bds-maneger-cli -d",
"* bds-maneger-cli -h", " 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 // Async functiona
@ -136,13 +172,19 @@ async function Runner() {
} }
} }
const BdsCoreStart = BdsCore.start(); // Load Plugins
BdsCoreStart.log(data => console.log(cli_color.blueBright(data.replace(/\n$/gi, "")))); for (let Plugin of BeforeRun) {
BdsCoreStart.exit(code => { if (!(ProcessArgs[Plugin.arg])) Plugin.main(ProcessArgs[Plugin.arg], ProcessArgs).catch(err => console.log("Plugin Crash:", "\n\n", err));
console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsCoreStart.uptime}`)); }
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); process.exit(code);
}); });
if (!(ProcessArgs["no-api"])) BdsCore.api(); 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(); 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 path = require("path")
const fs = require("fs"); const fs = require("fs");
const { randomUUID } = require("crypto"); const { randomUUID } = require("crypto");
const { bds_dir } = require("./lib/BdsSettings"); const BdsSettings = require("./lib/BdsSettings");
// Bds Maneger Core Package JSON File // Bds Maneger Core Package JSON File
module.exports.package_path = path.resolve(__dirname, "package.json"); module.exports.package_path = path.resolve(__dirname, "package.json");
@ -15,11 +15,10 @@ const { arch } = require("./lib/BdsSystemInfo");
module.exports.arch = arch module.exports.arch = arch
// Core Settings // Core Settings
const { GetJsonConfig, UpdatePlatform, UpdateTelegramToken } = require("./lib/BdsSettings"); module.exports.getBdsConfig = BdsSettings.GetJsonConfig;
module.exports.getBdsConfig = GetJsonConfig; module.exports.change_platform = BdsSettings.UpdatePlatform;
module.exports.change_platform = UpdatePlatform; module.exports.platform_update = BdsSettings.UpdatePlatform;
module.exports.platform_update = UpdatePlatform; module.exports.telegram_token_save = BdsSettings.UpdateTelegramToken;
module.exports.telegram_token_save = UpdateTelegramToken;
// Platforms Checkers // Platforms Checkers
const { CheckSystemAsync, GetKernel } = require("./lib/BdsSystemInfo"); const { CheckSystemAsync, GetKernel } = require("./lib/BdsSystemInfo");
@ -32,12 +31,12 @@ module.exports.internal_ip = BdsNetwork.LocalInterfaces;
module.exports.external_ip = BdsNetwork.GetExternalPublicAddress; module.exports.external_ip = BdsNetwork.GetExternalPublicAddress;
// Bds Maneger Core API // Bds Maneger Core API
const BdsManegerAPI = require("./src/api/api"); const BdsManegerAPI = require("./src/api");
module.exports.api = BdsManegerAPI; module.exports.api = BdsManegerAPI;
module.exports.BdsManegerAPI = BdsManegerAPI; module.exports.BdsManegerAPI = BdsManegerAPI;
// Bds Maneger Core API token Register // 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"]) { function token_register(Admin_Scoper = ["web_admin", "admin"]) {
Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper)); Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper));
let tokens = []; let tokens = [];
@ -110,3 +109,5 @@ module.exports.detect = Detect;
module.exports.bds_detect = Detect; module.exports.bds_detect = Detect;
module.exports.detect_server = Detect; module.exports.detect_server = Detect;
module.exports.kill = Kill; module.exports.kill = Kill;
setInterval(() => {} , 1000);

View File

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

View File

@ -3,7 +3,7 @@
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
"version": "1.14.1", "version": "1.15.0",
"description": "Scripts to manage minecraft server's", "description": "Scripts to manage minecraft server's",
"private": false, "private": false,
"main": "index.js", "main": "index.js",
@ -20,8 +20,7 @@
"remove_dev_versions": "node .Build/RemoveVersions.js" "remove_dev_versions": "node .Build/RemoveVersions.js"
}, },
"bin": { "bin": {
"bds_maneger": "bin/bds_maneger.js", "bds_maneger": "bin/BdsManeger.js"
"bds_telegram": "bin/telegram_bot.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,342 +6,342 @@ const { GetServerPaths, GetPlatform } = require("../lib/BdsSettings");
const TOML = require("@iarna/toml"); const TOML = require("@iarna/toml");
const ConfigFilePath = { const ConfigFilePath = {
bedrock: path.join(GetServerPaths("bedrock"), "server.properties"), bedrock: path.join(GetServerPaths("bedrock"), "server.properties"),
java: path.join(GetServerPaths("java"), "server.properties"), java: path.join(GetServerPaths("java"), "server.properties"),
pocketmine: path.join(GetServerPaths("pocketmine"), "server.properties"), pocketmine: path.join(GetServerPaths("pocketmine"), "server.properties"),
dragonfly: path.join(GetServerPaths("dragonfly"), "config.toml"), dragonfly: path.join(GetServerPaths("dragonfly"), "config.toml"),
} }
// Set Config // 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: ""}){ 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 BdsPlatform = GetPlatform();
const JsonConfig = { const JsonConfig = {
world: "Bds Maneger", world: "Bds Maneger",
description: "The Bds Maneger", description: "The Bds Maneger",
gamemode: "creative", gamemode: "creative",
difficulty: "normal", difficulty: "normal",
players: 10, players: 10,
commands: true, commands: true,
account: true, account: true,
whitelist: false, whitelist: false,
port: 19132, port: 19132,
portv6: 19133, portv6: 19133,
seed: "" seed: ""
}; };
// Strings // Strings
if (typeof NewConfig.world === "string" && NewConfig.world) JsonConfig.world = NewConfig.world 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.description === "string" && NewConfig.description) JsonConfig.description = NewConfig.description
if (typeof NewConfig.gamemode === "string" && NewConfig.gamemode) JsonConfig.gamemode = NewConfig.gamemode 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.difficulty === "string" && NewConfig.difficulty) JsonConfig.difficulty = NewConfig.difficulty
if ((typeof NewConfig.seed === "string" || typeof NewConfig.seed === "number") && NewConfig.seed) JsonConfig.seed = NewConfig.seed 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
// 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";
// Booleans // difficulty
if (typeof NewConfig.commands === "boolean" && (NewConfig.commands || NewConfig.commands === false)) JsonConfig.commands = NewConfig.commands if (JsonConfig.difficulty === "easy") JsonConfig.difficulty = 0;
if (typeof NewConfig.account === "boolean" && (NewConfig.account || NewConfig.account === false)) JsonConfig.account = NewConfig.account else if (JsonConfig.difficulty === "peaceful") JsonConfig.difficulty = 1;
if (typeof NewConfig.whitelist === "boolean" && (NewConfig.whitelist || NewConfig.whitelist === false)) JsonConfig.whitelist = NewConfig.whitelist else if (JsonConfig.difficulty === "normal") JsonConfig.difficulty = 2;
else if (JsonConfig.difficulty === "hard") JsonConfig.difficulty = 3;
else throw new Error("Difficulty error");
// Numbers // Required Accoutn
if (typeof NewConfig.port === "number" && NewConfig.port) JsonConfig.port = NewConfig.port if (JsonConfig.account === true) JsonConfig.account = "on";
if (typeof NewConfig.players === "number" && NewConfig.players) JsonConfig.players = NewConfig.players else JsonConfig.account = "off";
if (typeof NewConfig.portv6 === "number" && NewConfig.portv6) JsonConfig.portv6 = NewConfig.portv6
const Config = []; // Config
if (BdsPlatform === "bedrock") { Config.push(
const bedrockCPUThread = BdsInfo.GetCpuCoreCount(); "# By The Bds Maneger project",
var tickDistance; if (!(bedrockCPUThread % 2)) tickDistance = bedrockCPUThread; else tickDistance = 1; `# Date: ${Date.now()}`,
Config.push( "",
"# By The Bds Maneger project", "language=eng",
`# Date: ${Date.now()}`, `level-name=${JsonConfig.world}`,
"", `motd=${JsonConfig.description}`,
`level-name=${JsonConfig.world}`, `server-port=${JsonConfig.port}`,
`server-name=${JsonConfig.description}`, `white-list=${JsonConfig.whitelist}`,
`gamemode=${JsonConfig.gamemode}`, `max-players=${JsonConfig.players}`,
`difficulty=${JsonConfig.difficulty}`, `gamemode=${JsonConfig.gamemode}`,
`allow-cheats=${JsonConfig.commands}`, `difficulty=${JsonConfig.difficulty}`,
`max-players=${JsonConfig.players}`, `xbox-auth=${JsonConfig.account}`,
`online-mode=${JsonConfig.account}`, `level-seed=${JsonConfig.seed}`,
`white-list=${JsonConfig.whitelist}`, "view-distance=32",
`server-port=${JsonConfig.port}`, "hardcore=0",
`server-portv6=${JsonConfig.portv6}`, "announce-player-achievements=on",
`tick-distance=${tickDistance}`, "spawn-protection=16",
`max-threads=${bedrockCPUThread}`, "force-gamemode=off",
`level-seed=${JsonConfig.seed}`, "pvp=on",
"default-player-permission-level=member", "generator-settings=",
"view-distance=32", "level-type=DEFAULT",
"player-idle-timeout=0", "enable-query=on",
"texturepack-required=true", "enable-rcon=off",
"content-log-file-enabled=false", "rcon.password=F/deZ5kefY",
"compression-threshold=1", "auto-save=on",
"server-authoritative-movement=server-auth", );
"player-movement-score-threshold=20", }
"player-movement-distance-threshold=0.3", fs.writeFileSync(ConfigFilePath[BdsPlatform], Config.join("\n"))
"player-movement-duration-threshold-in-ms=500", return Config.join("\n");
"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");
// 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");
} }
// Get Config // Get Config
function bds_get_config(){ function bds_get_config(){
const BdsPlatform = GetPlatform(); const BdsPlatform = GetPlatform();
var config; var config;
const JsonConfig = { const JsonConfig = {
world: "", world: "",
description: "", description: "",
gamemode: "", gamemode: "",
difficulty: "", difficulty: "",
players: "", players: "",
whitelist: null, whitelist: null,
portv4: 0, portv4: 0,
portv6: 0, portv6: 0,
}; };
if (BdsPlatform === "bedrock") { if (BdsPlatform === "bedrock") {
if (fs.existsSync(ConfigFilePath[BdsPlatform])) { if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(ConfigFilePath["bedrock"], "utf8")); config = propertiesToJSON(fs.readFileSync(ConfigFilePath["bedrock"], "utf8"));
// Players // Players
JsonConfig.world = config["level-name"]; JsonConfig.world = config["level-name"];
JsonConfig.description = config["server-name"]; JsonConfig.description = config["server-name"];
JsonConfig.gamemode = config["gamemode"]; JsonConfig.gamemode = config["gamemode"];
JsonConfig.difficulty = config["difficulty"]; JsonConfig.difficulty = config["difficulty"];
JsonConfig.players = parseInt(config["max-players"]); JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.account = (config["online-mode"] === "true"); JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true"); JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World // Server/World
JsonConfig.portv4 = parseInt(config["server-port"]); JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.portv6 = parseInt(config["server-portv6"]); JsonConfig.portv6 = parseInt(config["server-portv6"]);
JsonConfig.seed = config["level-seed"]; JsonConfig.seed = config["level-seed"];
JsonConfig.commands = (config["allow-cheats"] === "true"); JsonConfig.commands = (config["allow-cheats"] === "true");
// JsonConfig.worldtype = "default"; // JsonConfig.worldtype = "default";
}
} }
else if (BdsPlatform === "java") { }
if (fs.existsSync(ConfigFilePath[BdsPlatform])) { else if (BdsPlatform === "java") {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["java"], "server.properties"), "utf8")); if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["java"], "server.properties"), "utf8"));
// Players
JsonConfig.world = config["level-name"]; // Players
JsonConfig.description = config["motd"]; JsonConfig.world = config["level-name"];
JsonConfig.gamemode = config["gamemode"]; JsonConfig.description = config["motd"];
JsonConfig.difficulty = config["difficulty"]; JsonConfig.gamemode = config["gamemode"];
JsonConfig.players = parseInt(config["max-players"]); JsonConfig.difficulty = config["difficulty"];
JsonConfig.account = (config["online-mode"] === "true"); JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.whitelist = (config["white-list"] === "true"); JsonConfig.account = (config["online-mode"] === "true");
JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]); // Server/World
JsonConfig.portv6 = parseInt(config["server-port"]); JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"]; JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.commands = (config["enable-command-block"] === "true"); JsonConfig.seed = config["level-seed"];
// JsonConfig.worldtype = config["level-type"]; JsonConfig.commands = (config["enable-command-block"] === "true");
} // JsonConfig.worldtype = config["level-type"];
} }
else if (BdsPlatform === "pocketmine") { }
if (fs.existsSync(ConfigFilePath[BdsPlatform])) { else if (BdsPlatform === "pocketmine") {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["pocketmine"], "server.properties"), "utf8")); if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
config = propertiesToJSON(fs.readFileSync(path.join(ConfigFilePath["pocketmine"], "server.properties"), "utf8"));
// Players
JsonConfig.world = config["level-name"]; // Players
JsonConfig.description = config["motd"]; JsonConfig.world = config["level-name"];
JsonConfig.gamemode = (()=>{let test = parseInt(config["gamemode"]);if (test === 0) return "survival";else if (test === 1) return "creative";else return undefined;})(); JsonConfig.description = config["motd"];
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.gamemode = (()=>{let test = parseInt(config["gamemode"]);if (test === 0) return "survival";else if (test === 1) return "creative";else return undefined;})();
JsonConfig.players = parseInt(config["max-players"]); 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.account = (config["xbox-auth"] === "on"); JsonConfig.players = parseInt(config["max-players"]);
JsonConfig.whitelist = (config["white-list"] === "true"); JsonConfig.account = (config["xbox-auth"] === "on");
JsonConfig.whitelist = (config["white-list"] === "true");
// Server/World
JsonConfig.portv4 = parseInt(config["server-port"]); // Server/World
JsonConfig.portv6 = parseInt(config["server-port"]); JsonConfig.portv4 = parseInt(config["server-port"]);
JsonConfig.seed = config["level-seed"]; JsonConfig.portv6 = parseInt(config["server-port"]);
JsonConfig.commands = false; JsonConfig.seed = config["level-seed"];
// JsonConfig.worldtype = config["level-type"]; JsonConfig.commands = false;
} // JsonConfig.worldtype = config["level-type"];
} else if (BdsPlatform === "dragonfly") { }
if (fs.existsSync(ConfigFilePath[BdsPlatform])) { } else if (BdsPlatform === "dragonfly") {
const ConfigFile = TOML.parse(fs.readFileSync(ConfigFilePath[BdsPlatform], "utf8")); if (fs.existsSync(ConfigFilePath[BdsPlatform])) {
JsonConfig.world = ConfigFile.World.Name; const ConfigFile = TOML.parse(fs.readFileSync(ConfigFilePath[BdsPlatform], "utf8"));
JsonConfig.description = ConfigFile.Server.Name; JsonConfig.world = ConfigFile.World.Name;
JsonConfig.gamemode = "creative"; JsonConfig.description = ConfigFile.Server.Name;
JsonConfig.difficulty = null; JsonConfig.gamemode = "creative";
JsonConfig.players = parseInt(ConfigFile.Players.MaxCount || 0); JsonConfig.difficulty = null;
JsonConfig.account = false; JsonConfig.players = parseInt(ConfigFile.Players.MaxCount || 0);
JsonConfig.whitelist = null; JsonConfig.account = false;
JsonConfig.portv4 = parseInt(ConfigFile.Network.Address.replace(":", "")); JsonConfig.whitelist = null;
JsonConfig.portv6 = parseInt(ConfigFile.Network.Address.replace(":", "")); JsonConfig.portv4 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.seed = null; JsonConfig.portv6 = parseInt(ConfigFile.Network.Address.replace(":", ""));
JsonConfig.commands = false; JsonConfig.seed = null;
} JsonConfig.commands = false;
} else throw new Error("Platform no exists, check config file"); }
return JsonConfig; } else throw new Error("Platform no exists, check config file");
return JsonConfig;
} }
// Get Withelist // Get Withelist
function bds_get_whitelist(){ function bds_get_whitelist(){
const BdsPlatform = GetPlatform(); const BdsPlatform = GetPlatform();
const ToReturn = []; const ToReturn = [];
// Bedrock // Bedrock
if (BdsPlatform === "bedrock") { if (BdsPlatform === "bedrock") {
if (fs.existsSync(path.join(GetServerPaths("bedrock"), "whitelist.json"))) { if (fs.existsSync(path.join(GetServerPaths("bedrock"), "whitelist.json"))) {
const LocalWhitelist = JSON.parse(fs.readFileSync(path.join(GetServerPaths("bedrock"), "whitelist.json"), "utf8")); const LocalWhitelist = JSON.parse(fs.readFileSync(path.join(GetServerPaths("bedrock"), "whitelist.json"), "utf8"));
for (let i = 0; i < LocalWhitelist.length; i++) { for (let i = 0; i < LocalWhitelist.length; i++) {
const Player = LocalWhitelist[i]; const Player = LocalWhitelist[i];
ToReturn.push({ ToReturn.push({
name: Player.name, name: Player.name,
// permissons: Player.permission, // permissons: Player.permission,
}); });
} }
}
} }
}
// Pocketmine // Pocketmine
else if (BdsPlatform === "pocketmine") { else if (BdsPlatform === "pocketmine") {
throw new Error("Not implemented yet"); throw new Error("Not implemented yet");
} }
// Java and Spigot // Java and Spigot
else if (BdsPlatform === "java" || BdsPlatform === "spigot") { else if (BdsPlatform === "java" || BdsPlatform === "spigot") {
throw new Error("Not implemented yet"); throw new Error("Not implemented yet");
} }
// If not exists Platform return throw // If not exists Platform return throw
else throw new Error("Platform no exists, check config file"); else throw new Error("Platform no exists, check config file");
return ToReturn; return ToReturn;
} }
// Export modules // Export modules

View File

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

432
src/api.js Normal file
View File

@ -0,0 +1,432 @@
// 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");
const docs = require("../BdsManegerInfo.json").docs;
// 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
// ? /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)];