Move files from Scripts/ to src/ and add 'on' to start server. #144

Merged
Sirherobrine23 merged 8 commits from Changes-and-move-Scripts-dir into main 2021-08-02 22:33:21 +00:00
26 changed files with 531 additions and 387 deletions

View File

@ -19,7 +19,13 @@
"smcpeak.default-keys-windows",
"vscode-icons-team.vscode-icons",
"me-dutour-mathieu.vscode-github-actions",
"cschleiden.vscode-github-actions"
"cschleiden.vscode-github-actions",
"github.copilot",
"eamodio.gitlens",
"github.vscode-pull-request-github",
"oderwat.indent-rainbow",
"visualstudioexptteam.vscodeintellicode",
"redhat.vscode-yaml"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.

View File

@ -3,8 +3,7 @@
"browser": true,
"commonjs": true,
"es2021": true,
"node": true,
"shelljs": true
"node": true
},
"globals": {
"bds_log_string": "writable",
@ -24,6 +23,7 @@
"error",
"double"
],
"eqeqeq": 0
"eqeqeq": 0,
"no-async-promise-executor": "off"
}
}

5
.gitattributes vendored
View File

@ -1 +1,4 @@
*.sh text eol=lf
*.sh text=LF eol=LF
.devcontainer/* eol=LF text=LF
*.js text=LF eol=LF
* text=CRLF eol=CRLF

View File

@ -8,14 +8,11 @@ Any contribution is welcome, but before a look at [CONTRIBUTING.md](CONTRIBUTING
In Version 1.11.0 there was a big change in the way to get the new settings and that left a good part of the program broken, so for those who are going to upgrade to the latest versions of Bds maneger Core will have to change the settings manually.
## CI/CD tests
## Badges
[![Github CodeQL and OSSAR](https://github.com/The-Bds-Maneger/Bds-Maneger-Core/actions/workflows/codeql%20and%20ossar%20analysis.yml/badge.svg)](https://github.com/The-Bds-Maneger/Bds-Maneger-Core/actions/workflows/codeql%20and%20ossar%20analysis.yml)
[![Gitlab pipeline status](https://the-bds-maneger.org/The-Bds-Maneger/Bds-Maneger-Core/badges/main/pipeline.svg)](https://the-bds-maneger.org/The-Bds-Maneger/Bds-Maneger-Core/-/pipelines/latest)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/Bds-Maneger/bds_maneger_api.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Bds-Maneger/bds_maneger_api/alerts/)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Bds-Maneger/bds_maneger_api.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Bds-Maneger/bds_maneger_api/context:javascript)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/4d19af8fe5b146608a8f4a5e2092f66d)](https://www.codacy.com/gh/The-Bds-Maneger/Bds-Maneger-Core/dashboard?utm_source=github.com&utm_medium=referral&utm_content=The-Bds-Maneger/Bds-Maneger-Core&utm_campaign=Badge_Grade)
[![DeepScan grade](https://deepscan.io/api/teams/13683/projects/16691/branches/363172/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=13683&pid=16691&bid=363172)
## Start our Docker image, making everything easier.

View File

@ -1,12 +1,15 @@
#!/usr/bin/env node
if (process.platform === "win32") process.title = "Bds Maneger CLI";else process.title = "Bds_Manger_CLI"
if (process.platform === "win32") process.title = "Bds Maneger CLI"; else process.title = "Bds_Manger_CLI";
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
// Inports
const readline = require("readline");
const bds = require("../index");
const { valid_platform } = require("../lib/BdsSystemInfo");
const { bds_dir, GetServerVersion, GetPlatform, UpdatePlatform, GetServerPaths, GetPaths } = require("../lib/BdsSettings");
const commandExits = require("../lib/commandExist");
const download = require("../src/Scripts/download");
process.env.IS_BDS_CLI = process.env.IS_BIN_BDS = true;
const download = require("../src/download");
// Bds Maneger ArgV
const argv = require("minimist")(process.argv.slice(2));
if (Object.getOwnPropertyNames(argv).length <= 1) argv.help = true
@ -32,7 +35,7 @@ if (kill) bds.kill();
if (server) UpdatePlatform(server);
function StartServer(){
const { Servers } = require("../../lib/ServerURL");
const { Servers } = require("../lib/ServerURL");
// Check Server Update
if (Versions[GetPlatform()] !== null) {
if (Versions[GetPlatform()] !== Servers.latest[GetPlatform()]) {
@ -56,9 +59,22 @@ function StartServer(){
// CLI Commands
const rl = readline.createInterface({input: process.stdin,output: process.stdout});
rl.on("line", (input) => {if (input === "@stop") {rl.close(); bds_server.stop()} else bds_server.command(input)});
rl.on("close", ()=>{console.log("CTRL + C closed readline, stopping server");bds_server.stop()})
bds_server.exit(function(c){if (c !== 0) rl.close()})
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("CTRL + C closed readline, stopping server");
bds_server.stop();
})
bds_server.exit(function(c){
if (c !== 0) rl.close();
})
bds.api();
} catch (err) {
console.log(`Bds Maneger Start Server Error: \n******\n${err}`);

View File

@ -4,7 +4,7 @@ const path = require("path");
const bds = require("../index");
const { GetPlatform, GetPaths } = require("../lib/BdsSettings");
const { GetKernel, arch, system } = require("../lib/BdsSystemInfo");
const { Detect } = require("../src/Scripts/CheckKill");
const { Detect } = require("../src/CheckKill");
const TelegramOptions = require("minimist")(process.argv.slice(2));
if (TelegramOptions.h || TelegramOptions.help) {

View File

@ -3,6 +3,7 @@ const { resolve } = require("path");
const path = require("path")
const fs = require("fs");
const { randomUUID } = require("crypto");
function date(format) {
const today = new Date(),
yaer = today.getFullYear(),
@ -26,13 +27,15 @@ module.exports.package_json = require("./package.json");
module.exports.extra_json = require("./BdsManegerInfo.json");
const { bds_dir } = require("./lib/BdsSettings");
const { arch } = require("./lib/BdsSystemInfo");
const { GetPaths, GetJsonConfig, UpdatePlatform, UpdateTelegramToken, GetTelegramToken } = require("./lib/BdsSettings")
// Inport and Export Arch
const { arch } = require("./lib/BdsSystemInfo");
module.exports.arch = arch
const { GetJsonConfig, UpdatePlatform, UpdateTelegramToken, GetTelegramToken } = require("./lib/BdsSettings");
if (typeof fetch === "undefined") global.fetch = require("node-fetch");
const maneger_ips = require("./src/Scripts/external_ip")
const maneger_ips = require("./src/external_ip")
module.exports.internal_ip = maneger_ips.internal_ip
module.exports.external_ip = maneger_ips.external_ip
module.exports.save_google_id = require("./lib/BdsSettings").CloudConfig.Driver
@ -41,26 +44,7 @@ module.exports.change_platform = module.exports.platform_update = UpdatePlatform
module.exports.telegram_token_save = UpdateTelegramToken
module.exports.api = require("./src/rest/api");
// ------------
const user_file_connected = GetPaths("player");
module.exports.players_files = user_file_connected
if (!(fs.existsSync(user_file_connected))) {
let config = {};
config["bedrock"] = {};
config["java"] = {};
config["pocketmine"] = {};
config["jsprismarine"] = {};
let NewJson = JSON.stringify(config, null, 4);
fs.writeFileSync(user_file_connected, NewJson);
}
const file_user_check = fs.readFileSync(user_file_connected, "utf8");
try {
JSON.parse(file_user_check)
} catch (error) {
fs.renameSync(user_file_connected, `${user_file_connected}_old_${Math.random()}_${new Date().getDate()}_${new Date().getMonth()}_${new Date().getFullYear()}.json`)
}
// Telegram
module.exports.telegram_token = GetTelegramToken();
function token_register() {
@ -89,10 +73,10 @@ function token_register() {
module.exports.BdsSettigs = require("./lib/BdsSettings");
// Requires
const { World_BAckup } = require("./src/Scripts/backups");
const { config, get_config, config_example } = require("./src/Scripts/ServerSettings");
const download = require("./src/Scripts/download");
const { start, stop, BdsCommand } = require("./src/Scripts/basic_server")
const { World_BAckup } = require("./src/backups");
const { config, get_config, config_example } = require("./src/ServerSettings");
const download = require("./src/download");
const { start, stop, BdsCommand, CronBackups } = require("./src/basic_server")
/**
* Register tokens to use in Bds Maneger REST and other supported applications
@ -130,14 +114,14 @@ module.exports.stop = stop
*/
module.exports.backup = World_BAckup
const { Kill, Detect } = require("./src/Scripts/CheckKill")
const { Kill, Detect } = require("./src/CheckKill")
/**
* identify if there are any servers running in the background
*
* @example bds.detect()
* // true: if the server is running
* // false: if not already
* true: if the server is running
* false: if not already
*/
module.exports.detect = Detect
module.exports.bds_detect = Detect
@ -165,7 +149,7 @@ module.exports.config_example = config_example
/**
* use this command to modify server settings
*
* @example bds.set_config({
* @example set_config({
name: "Bedrock our Java",
description: "BDS Maneger",
gamemode: "survival",
@ -177,7 +161,7 @@ module.exports.config_example = config_example
players: 100,
port: 19132,
port6: 19133
})
});
*/
module.exports.set_config = config
/**
@ -196,4 +180,4 @@ module.exports.tmphost = require("./lib/tempHost")
/**
* Load Crontab Backup
*/
module.exports.Cron_Loaded = require("./src/Scripts/LoadCronBackup")
module.exports.Cron_Loaded = CronBackups;

View File

@ -6,7 +6,7 @@ const yaml = {
stringify: require("js-yaml").dump
}
const FetchSync = require("@the-bds-maneger/fetchsync");
const { external_ip } = require("../src/Scripts/external_ip");
const { external_ip } = require("../src/external_ip");
const { valid_platform } = require("./BdsSystemInfo");
// PATHs

View File

@ -77,11 +77,11 @@ function GetKernel() {
else return `Amazon AWS Cloud ${process.arch}: ${require("os").cpus()[0].model}`;
// Windows WSL 1
case /WSL2|microsft/.test(str):
return "Microsoft WSL 2";
// Windows WSL 2
case /microsoft/.test(str):
return "Microsoft WSL 1";
// Windows WSL 2
case /Microsoft/.test(str):
return "Microsoft WSL 2";
// Azure Virtual Machinime (VM)
case /[aA]zure/.test(str):

View File

@ -1,5 +1,5 @@
const fetchSync = require("@the-bds-maneger/fetchsync");
const { external_ip, Interfaces } = require("../src/Scripts/external_ip");
const { external_ip, Interfaces } = require("../src/external_ip");
const { GetTempHost } = require("./BdsSettings")
if (GetTempHost()){

View File

@ -1,6 +1,6 @@
const bds = require("../../index")
const bds = require("../index")
const { CheckBan } = require("./check");
const { GetPlatform, GetPaths } = require("../../lib/BdsSettings");
const { GetPlatform, GetPaths } = require("../lib/BdsSettings");
const fs = require("fs");
function MytypeKill(player) {

View File

@ -1,21 +0,0 @@
const { CronJob } = require("cron");
const { GetCronBackup } = require("../../lib/BdsSettings");
const { Backup } = require("./backups")
const Cloud = {
Azure: require("../clouds/Azure").Uploadbackups,
Driver: require("../clouds/GoogleDriver").Uploadbackups,
Oracle: require("../clouds/OracleCI").Uploadbackups,
}
const CurrentBackups = GetCronBackup();
module.exports = CurrentBackups.map(Crron => {
return {
CronFunction: new CronJob(Crron.cron, function(){
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
if (Crron.Azure) Cloud.Azure(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Azure Backup Disabled");
if (Crron.Driver) Cloud.Driver(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Google Driver Backup Disabled");
if (Crron.Oracle) Cloud.Oracle(CurrentBackup.file_name, CurrentBackup.file_path); else console.info("Oracle Bucket Backup Disabled");
})
}
})

View File

@ -1,182 +0,0 @@
const { exec, execFile } = require("child_process");
const fs = require("fs");
const path = require("path");
const { resolve, join } = require("path");
const commandExists = require("../../lib/commandExist");
const saveUser = require("./PlayersSave");
const bds = require("../../index");
const { GetServerPaths, GetPaths, GetServerSettings, GetPlatform } = require("../../lib/BdsSettings");
const BdsDetect = require("./CheckKill").Detect;
const { randomUUID } = require("crypto");
const { warn } = console;
// Set bdsexec functions
global.BdsExecs = {};
function saveLog(data = "", LogFile = ""){
fs.appendFileSync(path.join(GetPaths("log"), "latest.log"), data)
fs.appendFileSync(LogFile, data)
}
function start() {
if (BdsDetect()){
console.warn("You already have a server running");
throw "You already have a server running";
} else {
var start_server;
// Minecraft Bedrock Oficial
if (GetPlatform() === "bedrock"){
if (process.platform === "darwin") throw Error("Use a imagem Docker");
else if (process.platform == "win32") start_server = exec("bedrock_server.exe", {
cwd: GetServerPaths("bedrock"),
});
else if (process.platform == "linux"){
// Set Executable file
execFile("chmod 777 bedrock_server", {cwd: GetServerPaths("bedrock")});
var BedrockCommand = "./bedrock_server";
// Emulation of the x86_64 architecture
if (commandExists("qemu-x86_64-static") && process.arch !== "x64") BedrockCommand = "qemu-x86_64-static "+BedrockCommand;
// Start Bedrock Server
start_server = exec(BedrockCommand, {cwd: GetServerPaths("bedrock"), env: {...process.env, LD_LIBRARY_PATH: GetServerPaths("bedrock")}})
} else throw new Error("your system does not support Minecraft Bedrock (yet)")
}
// Minecraft Java Oficial
else if (GetPlatform() === "java") {
const JavaConfig = GetServerSettings("java")
// Checking if java is installed on the device
if (commandExists("java")) {
start_server = execFile("java", [
"-jar",
`-Xms${JavaConfig.ram_mb}M`,
`-Xmx${JavaConfig.ram_mb}M`,
"MinecraftServerJava.jar",
"nogui"
], {cwd: GetServerPaths("java")})
} else {
var url = bds.package_json.docs_base; if (bds.system == "windows") url += "Java-Download#windows"; else if (bds.system === "linux") url = "Java-Download#linux"; else if (process.platform === "darwin") url = "Java-Download#macos"; else url = "Java-Download";
require("open")(url);
throw new Error(`Open: ${url}`)
}
} else if (GetPlatform() === "pocketmine") {
// Start PocketMine-MP
const php_bin_path = join(resolve(GetServerPaths("pocketmine"), "bin", "php7", "bin"), "php");
start_server = execFile(php_bin_path, [
"./PocketMine-MP.phar"
], {
cwd: GetServerPaths("pocketmine")
})
} else if (GetPlatform() === "jsprismarine") {
// Start JSPrismarine
start_server = execFile("node", [
"./packages/server/dist/Server.js"
], {
cwd: GetServerPaths("jsprismarine")
});
} else throw Error("Bds Config Error")
// Post Start
if (GetPlatform() === "java") {
start_server.stdout.on("data", function(data){
if (data.includes("agree"))
if (data.includes("EULA")){
const eula_file = path.join(GetServerPaths("java"), "eula.txt");
fs.writeFileSync(eula_file, fs.readFileSync(eula_file, "utf8").split("eula=false").join("eula=true"));
throw new Error("Restart application/CLI")
}
});
}
// Log file
const LogFile = join(GetPaths("log"), `${bds.date()}_${GetPlatform()}_Bds_log.log`);
// save User in Json
start_server.stdout.on("data", data => saveUser(data))
start_server.stderr.on("data", data => saveUser(data))
// ---------------------------------------------------
// Clear latest.log
fs.writeFileSync(path.join(GetPaths("log"), "latest.log"), "")
// ---------------------------------------------------
// stdout
start_server.stdout.on("data", a=>saveLog(a, LogFile));
start_server.stderr.on("data", a=>saveLog(a, LogFile));
// ---------------------------------------------------
// Global and Run
global.bds_log_string = ""
start_server.stdout.on("data", function(data){
if (global.bds_log_string === undefined || global.bds_log_string === "") global.bds_log_string = data; else global.bds_log_string += data
});
global.bds_server_string = start_server;
// Functions return
const returnFuntion = {
uuid: randomUUID(),
exec: start_server,
stop: function (){start_server.stdin.write("stop\n")},
command: function (command = "list", callback){
const oldLog = global.bds_log_string;
start_server.stdin.write(`${command}\n`);
if (typeof callback === "function") {
setTimeout(() => {
// Run commands from command run in server;
const log = global.bds_log_string.replace(oldLog, "").split(/\r/).filter(data => {if (data === "") return false; else return true;}).join("\n")
if (log.length >= 1) callback(log); else callback("no log")
}, 1555);
}
},
log: function (logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}){
if (typeof logCallback !== "function") {
warn("The log callback is not a function using console.log");
logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}
}
start_server.stdout.on("data", data => logCallback(data));
start_server.stderr.on("data", data => logCallback(data));
},
exit: function (exitCallback = process.exit){if (
typeof exitCallback === "function") start_server.on("exit", code => exitCallback(code));
}
}
start_server.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]})
global.BdsExecs[returnFuntion.uuid] = returnFuntion
return returnFuntion
}
}
function GetSessions(){
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
if (ArraySessions.length === 0) throw "Start Server";
if (ArraySessions.length >= 2) throw "Select a session manually:" + ArraySessions.join(", ")
return global.BdsExecs[0]
}
function BdsCommand(command = "list", SessionID = null) {
if (!(command)) return false;
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.command(command);
return true
} catch (error) {
return false
}
}
function stop(SessionID = null) {
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.stop()
return true
} catch (error) {
return false
}
}
module.exports = {
start,
BdsCommand,
stop
}

View File

@ -2,7 +2,7 @@ var fs = require("fs");
const path = require("path");
const propertiesToJSON = require("properties-to-json");
const { join } = require("path");
const { GetServerPaths, GetPlatform } = require("../../lib/BdsSettings");
const { GetServerPaths, GetPlatform } = require("../lib/BdsSettings");
const bds_dir_bedrock = GetServerPaths("bedrock"), bds_dir_java = GetServerPaths("java"), bds_dir_pocketmine = GetServerPaths("pocketmine");
const bedrockCPUThread = require("os").cpus().length;

View File

@ -1,8 +1,8 @@
const bds = require("../../index")
const bds = require("../index")
const { join, resolve } = require("path");
const { readdirSync, existsSync, readFileSync, statSync } = require("fs")
const AdmZip = require("adm-zip");
const { GetServerPaths, GetPaths, bds_dir } = require("../../lib/BdsSettings")
const { GetServerPaths, GetPaths, bds_dir } = require("../lib/BdsSettings")
function Backup() {
const zip = new AdmZip();

324
src/basic_server.js Normal file
View File

@ -0,0 +1,324 @@
const child_process = require("child_process");
const fs = require("fs");
const path = require("path");
const { resolve, join } = require("path");
const { randomUUID } = require("crypto");
const { CronJob } = require("cron");
const { GetCronBackup } = require("../lib/BdsSettings");
const { Backup } = require("./backups");
// Bds Maneger Inports
const commandExists = require("../lib/commandExist");
const BdsDetect = require("./CheckKill").Detect;
const bds = require("../index");
const { GetServerPaths, GetPaths, GetServerSettings, GetPlatform } = require("../lib/BdsSettings");
const BdsInfo = require("../BdsManegerInfo.json");
// Set bdsexec functions
global.BdsExecs = {};
function start() {
if (BdsDetect()){let ErrorReturn = "You already have a server running"; console.warn(ErrorReturn); throw new Error(ErrorReturn);}
const SetupCommands = {
command: String,
args: [],
cwd: String,
env: process.env,
}
// Minecraft Bedrock Oficial
if (GetPlatform() === "bedrock"){
// Check Darwin Platform
if (process.platform === "darwin") throw new Error("Use a imagem Docker");
// Windows Platform
else if (process.platform === "win32") {
SetupCommands.command = "bedrock_server.exe";
SetupCommands.cwd = GetServerPaths("bedrock")
}
// Linux Platform
else if (process.platform === "linux"){
// Set Executable file
try {child_process.execSync("chmod 777 bedrock_server", {cwd: GetServerPaths("bedrock")});} catch (error) {console.log(error);}
// Set Env and Cwd
SetupCommands.cwd = GetServerPaths("bedrock");
SetupCommands.env.LD_LIBRARY_PATH = GetServerPaths("bedrock");
// In case the cpu is different from x64, the command will use qemu static to run the server
if (process.arch !== "x64") {
if (!(commandExists("qemu-x86_64-static"))) throw new Error("Install qemu static")
SetupCommands.command = "qemu-x86_64-static"
SetupCommands.args.push("./bedrock_server");
} else SetupCommands.command = "./bedrock_server";
} else throw new Error("your system does not support Minecraft Bedrock (yet)")
}
// Minecraft Java Oficial
else if (GetPlatform() === "java") {
const JavaConfig = GetServerSettings("java")
// Checking if java is installed on the device
if (commandExists("java")) {
SetupCommands.cwd = GetServerPaths("java");
SetupCommands.command = "java";
SetupCommands.args.push("-jar", `-Xms${JavaConfig.ram_mb}M`, `-Xmx${JavaConfig.ram_mb}M`, "MinecraftServerJava.jar", "nogui");
} else {require("open")(bds.package_json.docs_base + "Java-Download#windows"); throw new Error(`Open: ${bds.package_json.docs_base + "Java-Download#windows"}`)}
}
// Minecraft Bedrock (Pocketmine-MP)
else if (GetPlatform() === "pocketmine") {
// Start PocketMine-MP
SetupCommands.command = join(resolve(GetServerPaths("pocketmine"), "bin", "php7", "bin"), "php");
SetupCommands.args.push("./PocketMine-MP.phar");
SetupCommands.cwd = GetServerPaths("pocketmine");
}
// Minecraft Bedrock (JSPrismarine)
else if (GetPlatform() === "jsprismarine") {
// Start JSPrismarine
SetupCommands.command = "node";
SetupCommands.args.push("./packages/server/dist/Server.js");
SetupCommands.cwd = GetServerPaths("jsprismarine");
} else throw Error("Bds Config Error")
// Setup commands
const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, {
cwd: SetupCommands.cwd,
env: SetupCommands.env
});
// Post Start
if (GetPlatform() === "java") {
const eula_file = path.join(GetServerPaths("java"), "eula.txt");
console.log(fs.readFileSync(eula_file, "utf8"));
if (fs.readFileSync(eula_file, "utf8").includes("eula=false")) {
fs.writeFileSync(eula_file, fs.readFileSync(eula_file, "utf8").replaceAll("eula=false", "eula=true"));
throw new Error("Restart application/CLI")
}
}
// Log file
const LogFile = join(GetPaths("log"), `${bds.date()}_${GetPlatform()}_Bds_log.log`);
const LatestLog_Path = path.join(GetPaths("log"), "latest.log");
const LogSaveFunction = data => {
fs.appendFileSync(LogFile, data);
fs.appendFileSync(LatestLog_Path, data);
return data;
}
fs.writeFileSync(LatestLog_Path, "");
// Player JSON File
ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON));
ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON));
// Log File
ServerExec.stdout.on("data", LogSaveFunction);
ServerExec.stderr.on("data", LogSaveFunction);
// Global and Run
global.bds_log_string = ""
ServerExec.stdout.on("data", data => {if (global.bds_log_string) global.bds_log_string = data; else global.bds_log_string += data});
const returnFuntion = {
uuid: randomUUID(),
stop: function (){
ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n");
return BdsInfo.Servers[GetPlatform()].stop;
},
command: async function (command = "list", callback = data => console.log(data)){
return new Promise((resolve) => {
ServerExec.stdin.write(`${command}\n`);
if (typeof callback === "function") {
const TempLog = []
const ControlTempHost = data => {TempLog.push(data); return data;}
ServerExec.stdout.on("data", data => ControlTempHost(data));
ServerExec.stderr.on("data", data => ControlTempHost(data));
setTimeout(() => {
callback(TempLog.join("\n"));
resolve(TempLog.join("\n"));
}, 2500);
}
});
},
log: function (logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}){
if (typeof logCallback !== "function") {
console.warn("The log callback is not a function using console.log");
logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}
}
ServerExec.stdout.on("data", data => logCallback(data));
ServerExec.stderr.on("data", data => logCallback(data));
},
exit: function (exitCallback = process.exit){if (
typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code));
},
on: function(action = String(), callback = Function) {
if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect");
// Functions
const data = data => Player_Json(data, function (array_status){
for (let _player of array_status) {
if (action === "all") callback(_player);
else if (_player.Action === action) callback(_player)
}
});
ServerExec.stdout.on("data", data);
ServerExec.stderr.on("data", data);
}
}
ServerExec.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]});
global.BdsExecs[returnFuntion.uuid] = returnFuntion;
return returnFuntion;
}
function Player_Json(data = "aaaaaa\n\n\naa", callback = () => {}){
const Current_platorm = GetPlatform();
// Bedrock
if (Current_platorm === "bedrock") {
// "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840",
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
const BedrockMap = data.split(/\n|\r/gi).map(line => {
if (line.includes("connected") || line.includes("disconnected")) {
let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi);
// player
let Player = line.trim().replace(/\[.+\]\s+Player/gi, "").trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a);
//
let Actions = null;
if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect";
else if (/^connected/.test(SplitLine[0].trim())) Actions = "connect";
// Object Map
const ObjectReturn = {
Player: Player[0],
Action: Actions,
xuid: Player[1] || null,
Date: new Date(),
}
// Return
return ObjectReturn
} else return false;
}).filter(a=>a);
callback(BedrockMap);
}
// Java and Pocketmine-MP
else if (Current_platorm === "java" || Current_platorm === "pocketmine") {
const JavaMap = data.split(/\n|\r/gi).map(line => {
if (line.trim().includes("joined the game") || line.includes("left the game")) {
line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim();
let Actions = null;
if (/joined/.test(line)) Actions = "connect";
else if (/left/.test(line)) Actions = "disconnect";
// Player Object
const JavaObject = {
Player: line.replace(/joined the game|left the game/gi, "").trim(),
Action: Actions,
Date: new Date(),
}
// Return JSON
return JavaObject
} else return false;
}).filter(a=>a);
callback(JavaMap);
}
// JSPrismarine
// else if (Current_platorm === "jsprismarine") console.log("It's still not working");
}
const UpdateUserJSON = function (New_Object = new Array()){
const Player_Json_path = GetPaths("player");
const Current_platorm = GetPlatform();
let Players_Json = {
bedrock: [],
java: [],
pocketmine: [],
jsprismarine: [],
}
if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"));
// Array
Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object)
fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2));
return Players_Json
}
// Search player in JSON
function Player_Search(player = "dontSteve") {
const Player_Json_path = GetPaths("player"), Current_platorm = GetPlatform();
const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[Current_platorm]
for (let Player of Players_Json) {
if (Player.Player === player.trim()) return Player;
}
return {};
}
function GetSessions(){
const ArraySessions = Object.getOwnPropertyNames(global.BdsExecs)
if (ArraySessions.length === 0) throw "Start Server";
if (ArraySessions.length >= 2) throw "Select a session manually:" + ArraySessions.join(", ")
return global.BdsExecs[0]
}
function BdsCommand(command = "list", SessionID = null) {
if (!(command)) return false;
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.command(command);
return true
} catch (error) {
return false
}
}
function stop(SessionID = null) {
try {
var Session = {}
if (!(SessionID)) Session = GetSessions(); else Session = global.BdsExecs[SessionID]
Session.stop()
return true
} catch (error) {
return false
}
}
const Cloud_Backup = {
Azure: require("./clouds/Azure").Uploadbackups,
Driver: require("./clouds/GoogleDriver").Uploadbackups,
Oracle: require("./clouds/OracleCI").Uploadbackups,
}
const CurrentBackups = GetCronBackup().map(Crron => {
return {
CronFunction: new CronJob(Crron.cron, async () => {
console.log("Starting Server and World Backup");
const CurrentBackup = Backup();
// Azure
if (Crron.Azure) Cloud_Backup.Azure(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Azure Backup Disabled");
// Google Driver
if (Crron.Driver) Cloud_Backup.Driver(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Google Driver Backup Disabled");
// Oracle Bucket
if (Crron.Oracle) Cloud_Backup.Oracle(CurrentBackup.file_name, CurrentBackup.file_path);
else console.info("Oracle Bucket Backup Disabled");
})
}
});
module.exports = {
start,
BdsCommand,
stop,
CronBackups: CurrentBackups,
Player_Search,
}

View File

@ -1,4 +1,4 @@
const { bds_dir, GetServerBan, GetTelegramAdmins, GetPlatform, GetPaths } = require("../../lib/BdsSettings");
const { bds_dir, GetServerBan, GetTelegramAdmins, GetPlatform, GetPaths } = require("../lib/BdsSettings");
const { existsSync, readFileSync } = require("fs")
const { join } = require("path")

View File

@ -1,44 +1,39 @@
const fs = require("fs");
const { join } = require("path")
const { google } = require("googleapis");
const { bds_dir } = require("../../../lib/BdsSettings")
const { randomUUID } = require("crypto");
const express = require("express");
const app = express();
var cors = require("cors");
const rateLimit = require("express-rate-limit");
const bodyParser = require("body-parser");
const fetchSync = require("@the-bds-maneger/fetchsync");
const Ips = require("../../Scripts/external_ip");
const DefaultLoginDrive = {
access_type: "offline",
scope: [
"https://www.googleapis.com/auth/drive"
]
}
const GoogleDriveCredentials = fetchSync("https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Credentials/Google.json").json()
// -------------------------------------------------------------
const { google } = require("googleapis");
const ip_andress = require("../../external_ip");
const { bds_dir } = require("../../../lib/BdsSettings");
const PathToToken = join(bds_dir, "google_user_token.json");
function expressGetGoogleDriveToken(callback){
// Settings
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(bodyParser.json()); /* https://github.com/github/fetch/issues/323#issuecomment-331477498 */
app.use(bodyParser.urlencoded({ extended: true }));
app.use(limiter);
app.use(cors());
// Urls
app.get("/request", (req, res) => {
const secret = GoogleDriveCredentials.installed.client_secret;
const client = GoogleDriveCredentials.installed.client_id;
const redirect = `${req.protocol}://${req.headers.host}/save`;
const oAuth2Client = new google.auth.OAuth2(client, secret, redirect);
res.redirect(oAuth2Client.generateAuthUrl(DefaultLoginDrive))
app.get("/save", (req, res) => {
// Urls
global.GoogleAuth = {}
async function LoadExpress(GoogleDriveCredentials, app = express(), closer = express().listen(1221)){
return new Promise((resolve => {
app.get("/request", (req, res) => {
const SessionUUID = randomUUID();
const secret = GoogleDriveCredentials.installed.client_secret;
const client = GoogleDriveCredentials.installed.client_id;
const redirect = `${req.protocol}://${req.headers.host}/${SessionUUID}/save`;
const oAuth2Client = new google.auth.OAuth2(client, secret, redirect);
global.GoogleAuth[SessionUUID] = oAuth2Client;
res.redirect(oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: [
"https://www.googleapis.com/auth/drive"
]
}));
});
app.get("/:SessionUUID/save", (req, res) => {
const { code } = req.query;
const { SessionUUID } = req.params;
// http://localhost:6899/save?code=********************************************************************&scope=https://www.googleapis.com/auth/drive
const code = req.query.code
const oAuth2Client = global.GoogleAuth[SessionUUID];
oAuth2Client.getToken(code, (err, save_token) => {
if (err) return console.error("Error accessing keys and saving, Error:", err);
oAuth2Client.setCredentials(save_token);
@ -46,40 +41,58 @@ function expressGetGoogleDriveToken(callback){
fs.writeFile(PathToToken, JSON.stringify(save_token, null, 4), function (err){
if (err) {
console.error("We were unable to save json, please try again later");
return close_server();
return closer();
}
callback(oAuth2Client);
res.json({
"token": save_token,
status: "success"
})
close_server();
closer.close()
resolve(oAuth2Client);
});
});
});
app.get("*", (req, res)=>{res.redirect("/request")});
})
const saver = app.listen(6658)
function close_server() {saver.close()}
return 6658
app.all("*", ({res}) => res.redirect("/request"));
}));
}
module.exports.authorize = function (callback) {
const client_secret = GoogleDriveCredentials.installed.client_secret;
const client_id = GoogleDriveCredentials.installed.client_id;
const redirect_uris = GoogleDriveCredentials.installed.redirect_uris[0].split("@PORT_REDIRECT").join(6658).split("@URLREDIRECT").join("localhost");
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
fs.readFile(PathToToken, (err, user_cred) => {
if (err) {
var GetReturn = expressGetGoogleDriveToken(callback);
if (process.argv0 === "electron") open("http://localhost:6658/request")
console.log("Open one of these links in your browser:");
console.log("http://localhost:6658/request");
for (let index of Ips.internal_ip) console.log(`http://${index}:6658/request`)
return GetReturn
}
oAuth2Client.setCredentials(JSON.parse(user_cred));
callback(oAuth2Client);
function RandomPort(){
let Port = parseInt(Math.random().toString().replace(/[01]\./, "").slice(0, 4));
if (Port > 1024 && Port < 2542) return Port; else return RandomPort();
}
async function authorize() {
return new Promise(async resolve => {
const GoogleDriveCredentials = (await (await fetch("https://raw.githubusercontent.com/The-Bds-Maneger/external_files/main/Credentials/Google.json")).json())
const client_secret = GoogleDriveCredentials.installed.client_secret;
const client_id = GoogleDriveCredentials.installed.client_id;
const redirect_uris = "http://localhost:1932/SaveToken"
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
fs.readFile(PathToToken, async (err, user_cred) => {
if (err) {
const app = express();
app.use(require("body-parser").json());
app.use(require("body-parser").urlencoded({ extended: true }));
app.use(require("express-rate-limit")({windowMs: 1 * 60 * 1000, max: 100}));
app.use(require("cors")());
const port = RandomPort()
ip_andress.internal_ip.forEach(ips => {
let { ipv4, ipv6 } = ips.Interna_IP;
console.log(`Open: http://${ipv4}:${port}/request`);
if (ipv6) console.log(`Open: http://[${ipv6}]:${port}/request`);
});
// Return auth
const AuthToken = await LoadExpress(GoogleDriveCredentials, app, app.listen(port));
resolve(AuthToken);
} else {
oAuth2Client.setCredentials(JSON.parse(user_cred));
resolve(oAuth2Client);
}
});
});
}
module.exports = {
authorize,
}

View File

@ -1,23 +1,28 @@
const { resolve } = require("path");
const path = require("path");
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
const NewBdsSettings = require("../../lib/BdsSettings");
const Uploadbackups = async function (object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) {
const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure");
const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey);
const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container)
if (!(blobClient.exists())) await blobClient.create();
const containerClient = blobClient.getBlockBlobClient(resolve(object))
try {
await containerClient.uploadFile(fileLocation, {
blockSize: 4 * 1024 * 1024,
concurrency: 20,
onProgress: (env) => console.log(env)
})
console.log("Upload Sucess")
if (typeof callback === "function") callback()
} catch (err) {
console.log(`uploadFile failed, requestId - ${err.details.requestId}, statusCode - ${err.statusCode}, errorCode - ${err.details.errorCode}`);
}
// Upload Function
async function Uploadbackups(object = "Backup.zip", fileLocation = "Backup.zip", callback = function (){}) {
return new Promise(async function(resolve, reject){
try {
const { Account, AccountKey, Container } = NewBdsSettings.GetCloudConfig("Azure");
const sharedKeyCredential = new StorageSharedKeyCredential(Account, AccountKey);
const blobClient = new BlobServiceClient(`https://${Account}.blob.core.windows.net`, sharedKeyCredential).getContainerClient(Container)
if (!(blobClient.exists())) await blobClient.create();
const containerClient = blobClient.getBlockBlobClient(path.resolve(object));
const Reponse = await containerClient.uploadFile(fileLocation, {
blockSize: 4 * 1024 * 1024,
concurrency: 20,
onProgress: (env) => console.log(env)
})
if (typeof callback === "function") callback(Reponse);
resolve(Reponse);
} catch (err) {
console.log(`uploadFile failed, requestId - ${err.details.requestId}, statusCode - ${err.statusCode}, errorCode - ${err.details.errorCode}`);
reject(err);
}
})
}
module.exports = {

View File

@ -3,10 +3,9 @@ const { google } = require("googleapis");
const { authorize } = require("./Auth/Google");
const { GetCloudConfig } = require("../../lib/BdsSettings");
module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation = "Backup.zip", BackupCallback){
const parent_id = GetCloudConfig("Driver").RootID
return authorize(function (auth) {
const drive = google.drive({version: "v3", auth});
module.exports.Uploadbackups = async function (file_name = "Backup.zip", fileLocation = "Backup.zip", BackupCallback){
return new Promise(async function (resolve, reject){
const parent_id = GetCloudConfig("Driver").RootID
const UploadFile = {
resource: {
name: file_name
@ -20,14 +19,16 @@ module.exports.Uploadbackups = function (file_name = "Backup.zip", fileLocation
// Driver Root ID Backups
if (parent_id) UploadFile.resource.parents = [parent_id];
// Request
const auth = await authorize();
const drive = google.drive({version: "v3", auth});
drive.files.create(UploadFile, (err, file) => {
if (err) throw Error(err)
if (err) reject(err)
else {
console.log(`File URL: https://drive.google.com/file/d/${file.data.id}/`);
if (typeof BackupCallback === "function") BackupCallback(file);
resolve(`https://drive.google.com/file/d/${file.data.id}/`);
}
});
});
// End Upload Backup
};

View File

@ -4,38 +4,36 @@ const fs = require("fs");
const { resolve } = require("path");
const { CloudConfig } = require("../../lib/BdsSettings");
const Uploadbackups = async function (
object = "Backup.zip",
fileLocation = resolve(__dirname, "../Backup.zip"),
callback = function (data){console.log(data)}
){
const bucket = CloudConfig.Oracle().Bucket;
const provider = new oci_common.ConfigFileAuthenticationDetailsProvider();
const client = new oci_storage.ObjectStorageClient({
authenticationDetailsProvider: provider
async function Uploadbackups(object = "Backup.zip", fileLocation = resolve(__dirname, "../Backup.zip"), callback = function (data){console.log(data)}){
return new Promise(async function (resolve, reject){
try {
const bucket = CloudConfig.Oracle().Bucket;
const provider = new oci_common.ConfigFileAuthenticationDetailsProvider();
const client = new oci_storage.ObjectStorageClient({
authenticationDetailsProvider: provider
});
const request = {};
const response = await client.getNamespace(request);
const namespace = response.value;
const stats = fs.statSync(fileLocation);
const nodeFsBlob = new oci_storage.NodeFSBlob(fileLocation, stats.size);
const objectData = await nodeFsBlob.getData();
const putObjectRequest = {
namespaceName: namespace,
bucketName: bucket,
putObjectBody: objectData,
objectName: object,
contentLength: stats.size
};
const putObjectResponse = await client.putObject(putObjectRequest);
console.log("File upload successful");
if (typeof callback === "function") return callback(putObjectResponse);
resolve(putObjectResponse);
} catch (error) {
console.log("Error ", error);
reject(error)
}
});
try {
const request = {};
const response = await client.getNamespace(request);
const namespace = response.value;
const stats = fs.statSync(fileLocation);
const nodeFsBlob = new oci_storage.NodeFSBlob(fileLocation, stats.size);
const objectData = await nodeFsBlob.getData();
const putObjectRequest = {
namespaceName: namespace,
bucketName: bucket,
putObjectBody: objectData,
objectName: object,
contentLength: stats.size
};
const putObjectResponse = await client.putObject(putObjectRequest);
console.log("File upload successful");
if (typeof callback === "function") return callback(putObjectResponse);
return putObjectResponse;
} catch (error) {
console.log("Error ", error);
}
}
module.exports = {

View File

@ -1,12 +1,12 @@
var AdmZip = require("adm-zip");
const { writeFileSync, existsSync, readFileSync, readdirSync } = require("fs");
const { join, resolve } = require("path");
const bds = require("../../index")
const { valid_platform } = require("../../lib/BdsSystemInfo");
const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../../lib/BdsSettings");
const { GitClone } = require("../../lib/git_simples");
const bds = require("../index")
const { valid_platform } = require("../lib/BdsSystemInfo");
const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../lib/BdsSettings");
const { GitClone } = require("../lib/git_simples");
const { execSync } = require("child_process");
const Extra = require("../../BdsManegerInfo.json");
const Extra = require("../BdsManegerInfo.json");
const
bds_dir_bedrock = GetServerPaths("bedrock"),

View File

@ -5,7 +5,7 @@ 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("../../Scripts/check");
const { token_verify } = require("../../check");
// Backup
app.get("/backup", (req, res) => {

View File

@ -2,7 +2,7 @@ const express = require("express");
const app = express.Router();
const { GetPlatform } = require("../../../lib/BdsSettings")
const bds = require("../../../index");
const { token_verify, CheckPlayer } = require("../../Scripts/check");
const { token_verify, CheckPlayer } = require("../../check");
const { readFileSync } = require("fs");
const docs = require("../../../BdsManegerInfo.json").docs;