Remove fist API Routes and Modifications to CLI #239
@ -30,10 +30,3 @@ describe("Small functions", () => {
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Slow Functions", function () {
|
||||
it ("Download Server", async function () {
|
||||
this.timeout(60 * 1000);
|
||||
await BdsCore.download_server();
|
||||
});
|
||||
});
|
18
.vscode/launch.json
vendored
18
.vscode/launch.json
vendored
@ -1,24 +1,18 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Start Index",
|
||||
"program": "${workspaceFolder}/index.js"
|
||||
},
|
||||
{
|
||||
"type": "pwa-node",
|
||||
"request": "launch",
|
||||
"name": "API",
|
||||
"program": "${workspaceFolder}/bin/bds_maneger.js",
|
||||
"args": ["-sk"]
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Start Telegram bot dev",
|
||||
"program": "${workspaceFolder}/bin/telegram_bot.js"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Docker Build and Run",
|
||||
"program": "${workspaceFolder}/.Build/DockerImage.js",
|
||||
}
|
||||
]
|
||||
}
|
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"files.eol": "\n"
|
||||
}
|
@ -1,16 +1,9 @@
|
||||
{
|
||||
"docs_base": "https://docs.bdsmaneger.com/docs/Bds Maneger core",
|
||||
"docs": {
|
||||
"url": "https://docs.bdsmaneger.com",
|
||||
"main": "Bds Maneger core",
|
||||
"rest_api": "docs/Bds Maneger core/REST API/"
|
||||
},
|
||||
"temp_host": {
|
||||
"url": "http://hosts.bdsmaneger.com:3020"
|
||||
},
|
||||
"Fetchs": {
|
||||
"php": "https://raw.githubusercontent.com/The-Bds-Maneger/Php_Static_Binary/main/binarys.json",
|
||||
"servers": "https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Server.json"
|
||||
"php": "https://raw.githubusercontent.com/The-Bds-Maneger/Php_Static_Binary/main/binarys.json"
|
||||
},
|
||||
"IgnoreLog": {
|
||||
"bedrock": [
|
||||
|
@ -31,11 +31,7 @@ We have a separate repository for all Bds Maneger Project documentation, [link h
|
||||
|
||||
All options can be found in the bds maneger core documentation.
|
||||
|
||||
`npx --package=@the-bds-maneger/core@latest bds_maneger -sk`
|
||||
|
||||
### Telegram Bot
|
||||
|
||||
`npx --package=@the-bds-maneger/core@latest bds_telegram`
|
||||
`npx @the-bds-maneger/core@latest -sk`
|
||||
|
||||
## Install Bds Maneger Core globally
|
||||
|
||||
|
94
bin/bds_maneger.js → bin/BdsManeger.js
Executable file → Normal file
94
bin/bds_maneger.js → bin/BdsManeger.js
Executable file → Normal file
@ -1,6 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
if (process.platform === "win32") process.title = "Bds Maneger CLI"; else process.title = "Bds-Manger-CLI";
|
||||
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
|
||||
// Internal Modules
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
// External Modules
|
||||
const cli_color = require("cli-color");
|
||||
@ -14,10 +17,37 @@ const BdsCore = require("../index");
|
||||
const BdsNetwork = require("../src/BdsNetwork");
|
||||
const commandExits = require("../lib/commandExist");
|
||||
const readline = require("readline");
|
||||
// const BdsMenus = require("./bds_maneger/menus");
|
||||
const { PlatformVersionsV2 } = require("../src/BdsServersDownload");
|
||||
const { GetPlatform } = require("../lib/BdsSettings");
|
||||
|
||||
// Load Bds Maneger CLI Plugins
|
||||
const MoreHelp = [];
|
||||
const BeforeRun = [];
|
||||
fs.readdirSync(path.join(__dirname, "plugins")).map(file => path.resolve(__dirname, "plugins", file)).filter(Mod => fs.lstatSync(Mod).isFile() && Mod.endsWith(".js")).forEach(Plugin => {
|
||||
try {
|
||||
const __module = require(Plugin);
|
||||
(__module.Args || []).forEach(PluginArg => {
|
||||
["h", "help", "i", "info", "d", "download", "s", "start", "k", "kill", "get_domain", "p", "platform", "n", "no-api"].forEach(Arg => {
|
||||
if (PluginArg.arg === Arg) {
|
||||
console.log(cli_color.redBright(`${path.basename(Plugin).replace(/\.js$/gi, "")}:`, "Conflicted with Bds Maneger CLI argument"));
|
||||
process.exit(12);
|
||||
}
|
||||
});
|
||||
BeforeRun.forEach(Arg => {
|
||||
if (PluginArg.arg === Arg) {
|
||||
console.log(cli_color.redBright(`${path.basename(Plugin).replace(/\.js$/gi, "")}:`, "Conflicted with another plugin argument"));
|
||||
process.exit(13);
|
||||
}
|
||||
});
|
||||
BeforeRun.push(PluginArg);
|
||||
});
|
||||
MoreHelp.push(cli_color.redBright(`Plugin: ${path.basename(Plugin).replace(/\.js$/gi, "")} - ${__module.description}`), "", ...(__module.help || []), "");
|
||||
} catch (err) {
|
||||
console.log(cli_color.redBright(`Error loading plugin: ${Plugin}`));
|
||||
console.log(cli_color.redBright(err));
|
||||
}
|
||||
});
|
||||
|
||||
async function DownloadServer() {
|
||||
const ora = (await import("ora")).default;
|
||||
const PlatformVersion = await PlatformVersionsV2()
|
||||
@ -64,27 +94,33 @@ async function help() {
|
||||
const help = [
|
||||
`Bds Maneger CLI version: ${cli_color.magentaBright(BdsCore.package_json.version)}`,
|
||||
`System: ${cli_color.yellow(process.platform)}, architecture: ${cli_color.blue(BdsCore.arch)}`,
|
||||
"**************************************************************",
|
||||
"* Usage: bds-maneger-cli [options]",
|
||||
"*",
|
||||
"* Options:",
|
||||
"* -h, --help Print this help",
|
||||
"* -i, --info Print info about Bds Maneger Core and Platforms",
|
||||
"* -d, --download Download a server",
|
||||
"* -s, --start Start a server",
|
||||
"* --get_domain Get temporary public domain to connect in to server or API",
|
||||
"* -p, --platform Change the platform",
|
||||
"* -n, --no-api Don't start the Bds Maneger API Rest",
|
||||
"*",
|
||||
"* Examples:",
|
||||
"* bds-maneger-cli -d",
|
||||
"* bds-maneger-cli -s",
|
||||
"* bds-maneger-cli -p bedrock",
|
||||
"* bds-maneger-cli -i",
|
||||
"* bds-maneger-cli -h",
|
||||
"**************************************************************"
|
||||
"",
|
||||
" Usage: bds-maneger-cli [options]",
|
||||
"",
|
||||
" Options:",
|
||||
" -h, --help Print this help",
|
||||
" -i, --info Print info about Bds Maneger Core and Platforms",
|
||||
" -d, --download Download a server",
|
||||
" -s, --start Start a server",
|
||||
" -k, --kill Kill Server if running",
|
||||
" --get_domain Get temporary public domain to connect in to server or API",
|
||||
" -p, --platform Change the platform",
|
||||
" -n, --no-api Don't start the Bds Maneger API Rest",
|
||||
"",
|
||||
...MoreHelp,
|
||||
"",
|
||||
" Examples:",
|
||||
" bds-maneger-cli -d",
|
||||
" bds-maneger-cli -s",
|
||||
" bds-maneger-cli -sk",
|
||||
" bds-maneger-cli -k",
|
||||
" bds-maneger-cli -p bedrock",
|
||||
" bds-maneger-cli -i",
|
||||
" bds-maneger-cli -h",
|
||||
""
|
||||
];
|
||||
return console.log(cli_color.whiteBright(help.join("\n").replace(/true/gi, cli_color.greenBright("true")).replace(/false/gi, cli_color.redBright("false")).replace(/undefined/gi, cli_color.red("undefined"))));
|
||||
console.log(cli_color.whiteBright(help.join("\n").replace(/true/gi, cli_color.greenBright("true")).replace(/false/gi, cli_color.redBright("false")).replace(/undefined/gi, cli_color.red("undefined"))));
|
||||
return process.exit(0);
|
||||
}
|
||||
|
||||
// Async functiona
|
||||
@ -136,13 +172,19 @@ async function Runner() {
|
||||
}
|
||||
}
|
||||
|
||||
const BdsCoreStart = BdsCore.start();
|
||||
BdsCoreStart.log(data => console.log(cli_color.blueBright(data.replace(/\n$/gi, ""))));
|
||||
BdsCoreStart.exit(code => {
|
||||
console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsCoreStart.uptime}`));
|
||||
// Load Plugins
|
||||
for (let Plugin of BeforeRun) {
|
||||
if (!(ProcessArgs[Plugin.arg])) Plugin.main(ProcessArgs[Plugin.arg], ProcessArgs).catch(err => console.log("Plugin Crash:", "\n\n", err));
|
||||
}
|
||||
|
||||
const BdsManegerServer = BdsCore.start();
|
||||
BdsManegerServer.log(data => console.log(cli_color.blueBright(data.replace(/\n$/gi, ""))));
|
||||
BdsManegerServer.exit(code => {
|
||||
console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsManegerServer.uptime}`));
|
||||
process.exit(code);
|
||||
});
|
||||
if (!(ProcessArgs["no-api"])) BdsCore.api();
|
||||
readline
|
||||
const __readline = readline.createInterface({input: process.stdin, output: process.stdout});
|
||||
__readline.on("line", data => BdsManegerServer.command(data));
|
||||
}
|
||||
Runner();
|
@ -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;
|
@ -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
314
bin/plugins/TelegramBot.js
Normal 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"
|
||||
];
|
@ -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");
|
17
index.js
17
index.js
@ -2,7 +2,7 @@
|
||||
const path = require("path")
|
||||
const fs = require("fs");
|
||||
const { randomUUID } = require("crypto");
|
||||
const { bds_dir } = require("./lib/BdsSettings");
|
||||
const BdsSettings = require("./lib/BdsSettings");
|
||||
|
||||
// Bds Maneger Core Package JSON File
|
||||
module.exports.package_path = path.resolve(__dirname, "package.json");
|
||||
@ -15,11 +15,10 @@ const { arch } = require("./lib/BdsSystemInfo");
|
||||
module.exports.arch = arch
|
||||
|
||||
// Core Settings
|
||||
const { GetJsonConfig, UpdatePlatform, UpdateTelegramToken } = require("./lib/BdsSettings");
|
||||
module.exports.getBdsConfig = GetJsonConfig;
|
||||
module.exports.change_platform = UpdatePlatform;
|
||||
module.exports.platform_update = UpdatePlatform;
|
||||
module.exports.telegram_token_save = UpdateTelegramToken;
|
||||
module.exports.getBdsConfig = BdsSettings.GetJsonConfig;
|
||||
module.exports.change_platform = BdsSettings.UpdatePlatform;
|
||||
module.exports.platform_update = BdsSettings.UpdatePlatform;
|
||||
module.exports.telegram_token_save = BdsSettings.UpdateTelegramToken;
|
||||
|
||||
// Platforms Checkers
|
||||
const { CheckSystemAsync, GetKernel } = require("./lib/BdsSystemInfo");
|
||||
@ -32,12 +31,12 @@ module.exports.internal_ip = BdsNetwork.LocalInterfaces;
|
||||
module.exports.external_ip = BdsNetwork.GetExternalPublicAddress;
|
||||
|
||||
// Bds Maneger Core API
|
||||
const BdsManegerAPI = require("./src/api/api");
|
||||
const BdsManegerAPI = require("./src/api");
|
||||
module.exports.api = BdsManegerAPI;
|
||||
module.exports.BdsManegerAPI = BdsManegerAPI;
|
||||
|
||||
// Bds Maneger Core API token Register
|
||||
const path_tokens = path.join(bds_dir, "bds_tokens.json");
|
||||
const path_tokens = path.join(BdsSettings.bds_dir, "bds_tokens.json");
|
||||
function token_register(Admin_Scoper = ["web_admin", "admin"]) {
|
||||
Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper));
|
||||
let tokens = [];
|
||||
@ -110,3 +109,5 @@ module.exports.detect = Detect;
|
||||
module.exports.bds_detect = Detect;
|
||||
module.exports.detect_server = Detect;
|
||||
module.exports.kill = Kill;
|
||||
|
||||
setInterval(() => {} , 1000);
|
@ -1,8 +1,7 @@
|
||||
// Load Fetch.js
|
||||
const fetchS = (...args) => import("node-fetch").then(mod => mod.default(...args));
|
||||
|
||||
// Set global fetch
|
||||
if (typeof fetch === "undefined") global.fetch = fetchS;
|
||||
if (typeof fetch === "undefined") {
|
||||
global.fetch = (...args) => import("node-fetch").then(mod => mod.default(...args));
|
||||
import("node-fetch").then(mod => global.fetch = mod.default);
|
||||
}
|
||||
|
||||
// Request Json
|
||||
const ReqJson = async (url = "", options) => await (await fetch(url, options)).json()
|
||||
|
118
package-lock.json
generated
118
package-lock.json
generated
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@the-bds-maneger/core",
|
||||
"version": "1.14.1",
|
||||
"version": "1.15.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@the-bds-maneger/core",
|
||||
"version": "1.14.1",
|
||||
"version": "1.15.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"os": [
|
||||
"linux",
|
||||
@ -34,24 +34,20 @@
|
||||
"node-cron": "^3.0.0",
|
||||
"node-fetch": "^3.0.0",
|
||||
"oci-sdk": "^2.0.0",
|
||||
"open": "^8.0.0",
|
||||
"ora": "^6.0.1",
|
||||
"properties-to-json": "^0.2.1",
|
||||
"request-ip": "^2.1.3",
|
||||
"serverline": "^1.5.0",
|
||||
"telegraf": "^4.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"bds_maneger": "bin/bds_maneger.js",
|
||||
"bds_telegram": "bin/telegram_bot.js"
|
||||
"bds_maneger": "bin/BdsManeger.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@actions/core": "^1.5.0",
|
||||
"chai": "^4.3.4",
|
||||
"eslint": "^8.0.0",
|
||||
"mocha": "^9.1.3",
|
||||
"nodemon": "^2.0.12",
|
||||
"os-tmpdir": "^2.0.0"
|
||||
"nodemon": "^2.0.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=15.6.0"
|
||||
@ -1291,14 +1287,6 @@
|
||||
"integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/define-lazy-prop": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
|
||||
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
@ -2651,20 +2639,6 @@
|
||||
"is-ci": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/is-docker": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
|
||||
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
|
||||
"bin": {
|
||||
"is-docker": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
@ -2802,17 +2776,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/is-wsl": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
|
||||
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
|
||||
"dependencies": {
|
||||
"is-docker": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-yarn-global": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz",
|
||||
@ -4537,22 +4500,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/open": {
|
||||
"version": "8.4.0",
|
||||
"resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz",
|
||||
"integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==",
|
||||
"dependencies": {
|
||||
"define-lazy-prop": "^2.0.0",
|
||||
"is-docker": "^2.1.1",
|
||||
"is-wsl": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/opossum": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/opossum/-/opossum-5.0.1.tgz",
|
||||
@ -4654,16 +4601,6 @@
|
||||
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/os-tmpdir": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-2.0.0.tgz",
|
||||
"integrity": "sha512-wZojVQP1fR3zW/Z9YLGJz4etXiu5d2tm4D6R4w2FTx1BAx9F1T+tEBb4+0deWQoskF1xe9zgBr/9mYwE+KY3xw==",
|
||||
"deprecated": "This is not needed anymore. `require('os').tmpdir()` in Node.js 4 and up is good.",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/p-cancelable": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz",
|
||||
@ -5232,14 +5169,6 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/serverline": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/serverline/-/serverline-1.5.0.tgz",
|
||||
"integrity": "sha512-QzNBH8omGchv+L5n/irZEeU2IGK3r8EMRh3EKRIlbfTklf9PtNRiRbWcYr8kqdNeWdc5M5jS13VtspDKgFXFFg==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
|
||||
@ -6933,11 +6862,6 @@
|
||||
"integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==",
|
||||
"dev": true
|
||||
},
|
||||
"define-lazy-prop": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
|
||||
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="
|
||||
},
|
||||
"delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
@ -7961,11 +7885,6 @@
|
||||
"ci-info": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"is-docker": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
|
||||
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="
|
||||
},
|
||||
"is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
@ -8052,14 +7971,6 @@
|
||||
"resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.1.0.tgz",
|
||||
"integrity": "sha512-lDcxivp8TJpLG75/DpatAqNzOpDPSpED8XNtrpBHTdQ2InQ1PbW78jhwSxyxhhu+xbVSast2X38bwj8atwoUQA=="
|
||||
},
|
||||
"is-wsl": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
|
||||
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
|
||||
"requires": {
|
||||
"is-docker": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"is-yarn-global": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz",
|
||||
@ -9601,16 +9512,6 @@
|
||||
"mimic-fn": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"open": {
|
||||
"version": "8.4.0",
|
||||
"resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz",
|
||||
"integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==",
|
||||
"requires": {
|
||||
"define-lazy-prop": "^2.0.0",
|
||||
"is-docker": "^2.1.1",
|
||||
"is-wsl": "^2.2.0"
|
||||
}
|
||||
},
|
||||
"opossum": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/opossum/-/opossum-5.0.1.tgz",
|
||||
@ -9678,12 +9579,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"os-tmpdir": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-2.0.0.tgz",
|
||||
"integrity": "sha512-wZojVQP1fR3zW/Z9YLGJz4etXiu5d2tm4D6R4w2FTx1BAx9F1T+tEBb4+0deWQoskF1xe9zgBr/9mYwE+KY3xw==",
|
||||
"dev": true
|
||||
},
|
||||
"p-cancelable": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz",
|
||||
@ -10121,11 +10016,6 @@
|
||||
"send": "0.17.1"
|
||||
}
|
||||
},
|
||||
"serverline": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/serverline/-/serverline-1.5.0.tgz",
|
||||
"integrity": "sha512-QzNBH8omGchv+L5n/irZEeU2IGK3r8EMRh3EKRIlbfTklf9PtNRiRbWcYr8kqdNeWdc5M5jS13VtspDKgFXFFg=="
|
||||
},
|
||||
"setprototypeof": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
|
||||
|
12
package.json
12
package.json
@ -3,7 +3,7 @@
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "1.14.1",
|
||||
"version": "1.15.0",
|
||||
"description": "Scripts to manage minecraft server's",
|
||||
"private": false,
|
||||
"main": "index.js",
|
||||
@ -11,7 +11,7 @@
|
||||
"start": "node bin/bds_maneger.js -s",
|
||||
"start:telegram": "node bin/telegram_bot.js -e js",
|
||||
"stop": "node -p 'console.log(require(\"./\").kill());'",
|
||||
"test": "mocha .test/*.js",
|
||||
"test": "mocha --exit .test/*.js",
|
||||
"ci": "node .Build/test/ci.js",
|
||||
"eslint": "eslint --debug .",
|
||||
"eslint:fix": "eslint --debug --fix .",
|
||||
@ -20,8 +20,7 @@
|
||||
"remove_dev_versions": "node .Build/RemoveVersions.js"
|
||||
},
|
||||
"bin": {
|
||||
"bds_maneger": "bin/bds_maneger.js",
|
||||
"bds_telegram": "bin/telegram_bot.js"
|
||||
"bds_maneger": "bin/BdsManeger.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -72,11 +71,9 @@
|
||||
"node-cron": "^3.0.0",
|
||||
"node-fetch": "^3.0.0",
|
||||
"oci-sdk": "^2.0.0",
|
||||
"open": "^8.0.0",
|
||||
"ora": "^6.0.1",
|
||||
"properties-to-json": "^0.2.1",
|
||||
"request-ip": "^2.1.3",
|
||||
"serverline": "^1.5.0",
|
||||
"telegraf": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@ -84,7 +81,6 @@
|
||||
"chai": "^4.3.4",
|
||||
"eslint": "^8.0.0",
|
||||
"mocha": "^9.1.3",
|
||||
"nodemon": "^2.0.12",
|
||||
"os-tmpdir": "^2.0.0"
|
||||
"nodemon": "^2.0.12"
|
||||
}
|
||||
}
|
||||
|
435
src/api.js
Normal file
435
src/api.js
Normal file
@ -0,0 +1,435 @@
|
||||
// Node Modules
|
||||
const os = require("os");
|
||||
const fs = require("fs");
|
||||
|
||||
// Bds Maneger Core
|
||||
const BdsManegerCore = require("../index");
|
||||
const BdsSystemInfo = require("../lib/BdsSystemInfo");
|
||||
const BdsChecks = require("./UsersAndtokenChecks");
|
||||
const BdsSettings = require("../lib/BdsSettings");
|
||||
|
||||
// Init Express
|
||||
const express = require("express");
|
||||
const app = express();
|
||||
|
||||
// Express Middleware
|
||||
const rateLimit = require("express-rate-limit");
|
||||
const bodyParser = require("body-parser");
|
||||
const fileUpload = require("express-fileupload");
|
||||
const pretty = require("express-prettify");
|
||||
const cors = require("cors");
|
||||
app.use(cors());
|
||||
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
app.use(rateLimit({windowMs: 15 * 60 * 1000, /* 15 minutes */ max: 100 /* limit each IP to 100 requests per windowMs*/ }));
|
||||
app.use(pretty({always: true, spaces: 2}));
|
||||
app.use(fileUpload({limits: { fileSize: 512 * 1024 }}));
|
||||
app.use(require("request-ip").mw());
|
||||
|
||||
// Routes
|
||||
|
||||
app.all(["/v2", "/v2/*"], ({res}) => res.status(401).json({
|
||||
Error: "v2 route moved to root routes"
|
||||
}));
|
||||
|
||||
// ? /bds/
|
||||
app.get(["/bds/info", "/bds", "/"], ({res}) => {
|
||||
try {
|
||||
const BdsConfig = BdsManegerCore.getBdsConfig();
|
||||
const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
|
||||
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
|
||||
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
|
||||
const Info = {
|
||||
core: {
|
||||
version: BdsManegerCore.package_json.version,
|
||||
Total_dependencies: Object.keys(BdsManegerCore.package_json.dependencies).length + Object.keys(BdsManegerCore.package_json.devDependencies).length,
|
||||
},
|
||||
server: {
|
||||
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
|
||||
versions: BdsConfig.server.versions,
|
||||
players: {
|
||||
online: Online.length,
|
||||
offline: Offline.length,
|
||||
}
|
||||
},
|
||||
host: {
|
||||
System: process.platform,
|
||||
Arch: BdsManegerCore.arch,
|
||||
Kernel: BdsSystemInfo.GetKernel(),
|
||||
Cpu_Model: (os.cpus()[0] || {}).model || null,
|
||||
IsDocker: false,
|
||||
IsNpx: false,
|
||||
IsCLI: false,
|
||||
}
|
||||
}
|
||||
if (process.env.BDS_DOCKER_IMAGE) Info.host.IsDocker = true;
|
||||
if (process.env.npm_lifecycle_event === "npx") Info.host.IsNpx = true;
|
||||
if (process.env.IS_BDS_CLI) Info.host.IsCLI = true;
|
||||
res.json(Info);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
error: "Backend Error",
|
||||
message: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Server Info
|
||||
app.get("/bds/info/server", ({res}) => {
|
||||
let ServerRunner = require("./BdsManegerServer").BdsRun;
|
||||
if (!ServerRunner)ServerRunner = {};
|
||||
try {
|
||||
const BdsConfig = BdsManegerCore.getBdsConfig();
|
||||
const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()];
|
||||
const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)));
|
||||
const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1)))
|
||||
const Info = {
|
||||
version: BdsConfig.server.versions[BdsSettings.GetPlatform()],
|
||||
Platform: BdsSettings.GetPlatform(),
|
||||
players: {
|
||||
online: Online.length,
|
||||
offline: Offline.length,
|
||||
},
|
||||
Config: BdsManegerCore.get_config(),
|
||||
Process: {
|
||||
PID: ServerRunner.pid || 0,
|
||||
Uptime: ServerRunner.uptime || 0,
|
||||
StartTime: ServerRunner.StartTime || NaN,
|
||||
}
|
||||
}
|
||||
res.json(Info);
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
error: "Backend Error",
|
||||
message: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Whitelist
|
||||
app.get("/bds/info/server/whitelist", (req, res) => {
|
||||
const ServerConfig = BdsManegerCore.get_config();
|
||||
if (ServerConfig.whitelist) {
|
||||
const { Token = null , Action = null } = req.query;
|
||||
const WgiteList = BdsSettings.get_whitelist();
|
||||
if (Action) {
|
||||
if (Action === "add") {
|
||||
if (WgiteList.findIndex(WL => WL.Token === Token) === -1) {
|
||||
WgiteList.push({
|
||||
Token: Token,
|
||||
Time: Date.now()
|
||||
});
|
||||
fs.writeFileSync(BdsManegerCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Whitelist Added"
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
success: false,
|
||||
message: "Whitelist Already Exist"
|
||||
});
|
||||
}
|
||||
} else if (Action === "remove") {
|
||||
if (WgiteList.findIndex(WL => WL.Token === Token) !== -1) {
|
||||
WgiteList.splice(WgiteList.findIndex(WL => WL.Token === Token), 1);
|
||||
fs.writeFileSync(BdsManegerCore.BdsSettigs.GetPaths("whitelist"), JSON.stringify(WgiteList));
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Whitelist Removed"
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
success: false,
|
||||
message: "Whitelist Not Found"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
res.json({
|
||||
success: false,
|
||||
message: "Invalid Action"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
res.json(WgiteList)
|
||||
}
|
||||
} else {
|
||||
res.status(400).json({
|
||||
error: "Whitelist Not Enabled"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Download Server
|
||||
app.get("/bds/download_server", (req, res) => {
|
||||
const { Token = null, Version = "latest" } = req.query;
|
||||
|
||||
// Check is Token is String
|
||||
if (!Token) return res.status(400).json({
|
||||
error: "Bad Request",
|
||||
message: "Token is required"
|
||||
});
|
||||
|
||||
// Check Token
|
||||
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
|
||||
error: "Bad Request",
|
||||
message: "Token is invalid"
|
||||
});
|
||||
|
||||
// Download Server
|
||||
BdsManegerCore.download(Version, true).then(() => {
|
||||
res.json({
|
||||
message: "Server Downloaded"
|
||||
});
|
||||
}).catch(error => {
|
||||
res.status(500).json({
|
||||
error: "Backend Error",
|
||||
message: `${error}`
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Update/Set Server Settings
|
||||
app.post("/bds/save_settings", (req, res) => {
|
||||
const { Token = null,
|
||||
WorldName = "Bds Maneger",
|
||||
ServerDescription = "The Bds Maneger",
|
||||
DefaultGamemode = "creative",
|
||||
ServerDifficulty = "normal",
|
||||
MaxPlayer = "10",
|
||||
WorldSeed = "",
|
||||
AllowCommands = "true",
|
||||
RequireLogin = "true",
|
||||
EnableWhitelist = "false",
|
||||
port_v4 = "19132",
|
||||
port_v6 = "19133",
|
||||
} = req.body;
|
||||
|
||||
// Check is Token is String
|
||||
if (!Token) return res.status(400).json({
|
||||
error: "Bad Request",
|
||||
message: "Token is required"
|
||||
});
|
||||
|
||||
// Check Token
|
||||
if (!(BdsChecks.token_verify(Token))) return res.status(400).json({
|
||||
error: "Bad Request",
|
||||
message: "Token is invalid"
|
||||
});
|
||||
|
||||
// Save Settings
|
||||
try {
|
||||
BdsManegerCore.set_config({
|
||||
world: WorldName,
|
||||
description: ServerDescription,
|
||||
gamemode: DefaultGamemode,
|
||||
difficulty: ServerDifficulty,
|
||||
players: parseInt(MaxPlayer) || 10,
|
||||
commands: AllowCommands === "true",
|
||||
account: RequireLogin === "true",
|
||||
whitelist: EnableWhitelist === "true",
|
||||
port: parseInt(port_v4) || 19132,
|
||||
portv6: parseInt(port_v6) || 19133,
|
||||
seed: WorldSeed || "",
|
||||
});
|
||||
res.json({
|
||||
message: "Settings Saved",
|
||||
Config: {
|
||||
world: WorldName,
|
||||
description: ServerDescription,
|
||||
gamemode: DefaultGamemode,
|
||||
difficulty: ServerDifficulty,
|
||||
seed: WorldSeed || "",
|
||||
players: parseInt(MaxPlayer) || 10,
|
||||
commands: AllowCommands === "true",
|
||||
account: RequireLogin === "true",
|
||||
whitelist: EnableWhitelist === "true",
|
||||
port: parseInt(port_v4) || 19132,
|
||||
portv6: parseInt(port_v6) || 19133,
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
error: "Backend Error",
|
||||
message: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Bds Maneger Bridge Communication
|
||||
app.get("/bds/bridge", (req, res) => {
|
||||
const ServerHost = require("./BdsNetwork").host || req.headers.host.replace(/^(.*?):\d+$/, (match, p1) => p1) || require("./BdsNetwork").externalIP.ipv4;
|
||||
const ServerConfig = BdsManegerCore.get_config();
|
||||
res.json({
|
||||
host: ServerHost,
|
||||
port: ServerConfig.portv4,
|
||||
});
|
||||
});
|
||||
|
||||
// ? /player
|
||||
const GetPlayerJson = (Platform = BdsManegerCore.getBdsConfig().server.platform) => ([...{...JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettigs.GetPaths("player"), "utf8"))}[Platform]]);
|
||||
app.get("/players", (req, res) => {
|
||||
const { Platform = BdsSettings.GetPlatform(), Player = null, Action = null } = req.query;
|
||||
let PlayerList = GetPlayerJson(Platform);
|
||||
if (Player) PlayerList = PlayerList.filter(PLS => PLS.Player === Player);
|
||||
if (Action) PlayerList = PlayerList.filter(PLS => PLS.Action === Action);
|
||||
|
||||
if (Player || Action) {
|
||||
if (PlayerList.length > 0) res.json(PlayerList);
|
||||
else res.status(404).json({
|
||||
Error: "Player not found",
|
||||
querys: req.query
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.json(PlayerList);
|
||||
return;
|
||||
});
|
||||
|
||||
// Players Actions in Backside Manager
|
||||
// kick player
|
||||
app.get("/players/kick", (req, res) => {
|
||||
const { Token = null, Player = "Sirherobrine", Text = "You have been removed from the Server" } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Kick player
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.kick(Player, Text);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Ban player
|
||||
app.get("/players/ban", (req, res) => {
|
||||
const { Token = null, Player = "Sirherobrine" } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Ban player
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.ban(Player);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Op player
|
||||
app.get("/players/op", (req, res) => {
|
||||
const { Token = null, Player = "Sirherobrine" } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Op player
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.op(Player);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Deop player
|
||||
app.get("/players/deop", (req, res) => {
|
||||
const { Token = null, Player = "Sirherobrine" } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Deop player
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.deop(Player);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Say to Server
|
||||
app.get("/players/say", (req, res) => {
|
||||
const { Token = null, Text = "Hello Server" } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Say to Server
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.say(Text);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Tp player
|
||||
app.get("/players/tp", (req, res) => {
|
||||
const { Token = null, Player = "Sirherobrine", X = 0, Y = 0, Z = 0 } = req.query;
|
||||
if (!Token) return res.status(400).json({ error: "Token is required" });
|
||||
if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" });
|
||||
|
||||
// Tp player
|
||||
const RunnerServer = require("../../../BdsManegerServer").BdsRun;
|
||||
try {
|
||||
RunnerServer.tp(Player, {
|
||||
x: X,
|
||||
y: Y,
|
||||
z: Z
|
||||
});
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: "Server nots Run",
|
||||
text: `${error}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Export API Routes
|
||||
function API(port_api = 1932, callback = port => {console.log("Bds Maneger Core REST API, http port", port)}){
|
||||
const MapRoutes = app._router.stack.map(d => {if (d.route) {if (d.route.path) return d.route.path;else return d.route.regexp.source;} else return null;}).filter(d => d);
|
||||
app.all("*", (req, res) => {
|
||||
return res.status(404).json({
|
||||
error: "Not Found",
|
||||
message: "The requested URL " + req.originalUrl || req.path + " was not found on this server.",
|
||||
AvaibleRoutes: MapRoutes
|
||||
});
|
||||
});
|
||||
const port = (port_api || 1932);
|
||||
app.listen(port, () => {
|
||||
if (typeof callback === "function") callback(port);
|
||||
});
|
||||
return port;
|
||||
}
|
||||
|
||||
function MainAPI(apiConfig = {api_port: 1932}, callback = function (port){console.log("Bds Maneger Core REST API, http port", port)}){
|
||||
var port_rest = 1932;
|
||||
if (typeof apiConfig === "object" && apiConfig.api_port !== undefined) port_rest = apiConfig.api_port;
|
||||
else if (typeof apiConfig === "number") port_rest = apiConfig;
|
||||
return API(port_rest, callback);
|
||||
}
|
||||
|
||||
module.exports = MainAPI;
|
||||
module.exports.api = API;
|
||||
module.exports.BdsRoutes = app;
|
||||
|
@ -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;
|
@ -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;
|
@ -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;
|
@ -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)];
|
@ -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)];
|
Reference in New Issue
Block a user