Sirherobrine23 Dev #157

Merged
Sirherobrine23 merged 14 commits from Sirherobrine23_dev into main 2021-08-16 03:55:17 +00:00
26 changed files with 629 additions and 788 deletions

View File

@ -4,7 +4,7 @@ set -ex
apt update
# Install Necessary Packages
apt install -y curl wget git zsh sudo unzip zip jq python python3 screen
apt -qq install -y curl wget git zsh sudo unzip zip jq python python3 screen
# Install nodejs from github release
get_current_node_version=$(curl -sL https://api.github.com/repos/nodejs/node/releases/latest | grep tag_name | cut -d '"' -f 4)
@ -21,14 +21,14 @@ esac
mkdir /tmp/Node
tar -xJf /tmp/node.tar.xz -C /tmp/Node
rm -rf /tmp/node.tar.xz
cp -rfv /tmp/Node/*/* /usr
cp -rf /tmp/Node/*/* /usr
# Install Build Dependencies and others Packages
apt -qq install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libatomic1 libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev
# Update npm
npm -g install npm@$(curl -sL https://api.github.com/repos/npm/cli/releases/latest | grep tag_name | cut -d '"' -f 4)
# Install Build Dependencies and others Packages
apt install -y ca-certificates make build-essential procps lsb-release xdg-utils g++ libnss3 libatk-bridge2.0-0 gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxrender1 libxss1 libxtst6 fonts-liberation libnss3 libgbm-dev
# Install Dependencies to diferent architectures
if ! [ "$(uname -m)" == "x86_64" ];then
mkdir -p /lib64
@ -39,16 +39,17 @@ if ! [ "$(uname -m)" == "x86_64" ];then
fi
# Install openjdk
case "$(uname -m)" in
x86_64 | aarch64 ) apt install -y openjdk-17*;;
* ) apt install -y openjdk-11*;;
case "$(apt search openjdk)" in
*openjdk-17* ) apt install -y openjdk-17*;;
*openjdk-11* ) apt install -y openjdk-11*;;
* ) echo "No openjdk version found, skipping";;
esac
# Setup non root user
useradd -m -p "$(perl -e 'print crypt($ARGV[0], "password")' "LucaA1113ba21")" "thebds"
addgroup thebds sudo
addgroup thebds root
usermod --shell /bin/bash thebds;
usermod --shell /usr/bin/zsh thebds;
echo "thebds ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
# Remove Unnecessary Packages

View File

@ -50,15 +50,14 @@ if (options.system || options.S) {
}
// nexe options
var files = readdirSync(resolve(__dirname, "..")).filter(retu => {if (/[Dd]ocker*.js/gi.test(retu) || retu.includes("docker_config.json", ".log")) return false; else if (retu.includes(".js")) return true; else if (retu === "rest" || retu === "scripts") return true; else return false;});
const nexeCopiler = {
name: "Bds Maneger Core",
build: true,
// loglevel: "verbose",
input: resolve(__dirname, "bds_maneger.js"),
output: fileout,
resources: files,
}
const nexeCopiler = {}
if (options.v || options.verbose) nexeCopiler.loglevel = "verbose"
// Build Binarie
compile(nexeCopiler).then(() => {console.log("success")})
compile({
name: "Bds Maneger Core",
build: true,
input: resolve(__dirname, "bds_maneger.js"),
output: fileout,
resources: readdirSync(resolve(__dirname, "..")).filter(retu => !/[Dd]ocker*.js|docker_config.json|*\.log/gi.test(retu)),
...nexeCopiler
}).then(() => process.exit(0)).catch(() => process.exit(1));

View File

@ -1,8 +1,7 @@
(async ()=>{
try {
const bds = require("../../index");
await bds.download("latest", true)
console.log("Date:", await bds.BdsDate());
await bds.download("latest", true);
console.log("Api:", await bds.api());
console.log("Backup:", await bds.backup());
console.log("Detect Server:", await bds.detect());

6
.github/ChangeVersion.js vendored Normal file
View File

@ -0,0 +1,6 @@
const fs = require('fs');
const Package_JSon = JSON.parse(fs.readFileSync(process.cwd()+'/package.json', 'utf8'));
const run_ID = process.env.RunID || "1111111111111111111111111111111111111";
Package_JSon.version = `${run_ID.slice(0, 2)}.${run_ID.slice(3, 6)}.${run_ID.slice(7, 11)}`;
fs.writeFileSync(process.cwd()+'/package.json', JSON.stringify(Package_JSon, null, 2));
console.log(Package_JSon.version);

View File

@ -1,42 +0,0 @@
name: Bds Maneger - Docker Base
on:
push:
tags:
- v*
- V*
# schedule:
# - cron: 0 0 * * */6
env:
DOCKER_ARCHS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6
jobs:
base:
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_ORG_USER }}
password: ${{ secrets.DOCKER_ORG_PASS }}
- name: checkout
uses: actions/checkout@master
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
push: true
target: bdsbase
tags: |
bdsmaneger/node_image:latest
bdsmaneger/node_image:${{ github.run_id }}
platforms: ${{ env.DOCKER_ARCHS }}

View File

@ -3,11 +3,9 @@ on:
push:
branches:
- main
paths-ignore:
- 'README.md'
- '.github/*/**'
- 'package-lock.json'
- '.devcontainer/**'
env:
DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7
jobs:
npm:
@ -20,16 +18,11 @@ jobs:
with:
node-version: 16.x
registry-url: https://registry.npmjs.org/
- name: Edit Version
run: |
id_run1=$(echo ${{ github.run_id }} |cut -b 1-2)
id_run2=$(echo ${{ github.run_id }} |cut -b 3-6)
id_run3=$(echo ${{ github.run_id }} |cut -b 7-)
old="$(cat package.json |grep "version"|head -1)"
new_version="$id_run1.$id_run2.$id_run3"
sed "s|$old|\"version\": \"$new_version\",|g" package.json > package2.json
cat package2.json > package.json
rm -rfv package2.json
env:
RunID: ${{ github.run_id }}
run: node .github/ChangeVersion.js
- name: Install Packages
run: npm install
@ -37,9 +30,10 @@ jobs:
- name: NPM Publish
run: npm publish --tag dev
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }}
NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}"
docker:
docker_core:
needs: [npm]
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
@ -63,5 +57,35 @@ jobs:
with:
push: true
target: bdscore
tags: bdsmaneger/core:nightly
platforms: linux/amd64,linux/arm64,linux/arm/v7
tags: bdsmaneger/core:main
platforms: ${{ env.DOCKER_ARCH }}
docker_base:
needs: [npm]
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_ORG_USER }}
password: ${{ secrets.DOCKER_ORG_PASS }}
- name: checkout
uses: actions/checkout@master
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
push: true
target: bdsbase
tags: |
bdsmaneger/base:main
bdsmaneger/node_image:main
platforms: ${{ env.DOCKER_ARCH }}

View File

@ -1,5 +1,5 @@
name: Test - The Bds Maneger Core
on: [push, pull_request]
on: [pull_request]
jobs:
Test:
@ -9,10 +9,38 @@ jobs:
node-version: [14.x, 15.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2.4.0
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm install -d --no-save
- run: npm test
- name: Edit Version
env:
RunID: ${{ github.run_id }}
run: node .github/ChangeVersion.js
- name: Install node depedencies
run: npm install -d --no-save
- name: Run test
run: npm run ci
Test_Docker:
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: checkout
uses: actions/checkout@master
- name: Build Docker Image
uses: docker/build-push-action@v2
with:
target: bdscore
tags: coretest:latest
platforms: linux/amd64,linux/arm64,linux/arm/v7

View File

@ -1,50 +0,0 @@
name: Bds Core Release Candidate
on:
push:
tags:
- rc**
jobs:
npm:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: actions/setup-node@v2.4.0
with:
node-version: 16.x
registry-url: https://registry.npmjs.org/
- name: Install Depedencies
run: npm install --no-save
- name: Publish
run: npm publish --tag rc
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }}
docker:
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_ORG_USER }}
password: ${{ secrets.DOCKER_ORG_PASS }}
- name: checkout
uses: actions/checkout@master
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
push: true
target: bdscore
tags: bdsmaneger/core:rc_${{ github.run_id }}
platforms: linux/amd64,linux/arm64,linux/arm/v7

View File

@ -5,9 +5,13 @@ on:
- v**
- V**
env:
DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7
jobs:
npm:
runs-on: ubuntu-latest
if: ${{ github.actor }} == ${{ github.repository_owner }}
steps:
- uses: actions/checkout@master
- uses: actions/setup-node@v2.4.0
@ -21,9 +25,10 @@ jobs:
- name: Publish
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }}
NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}"
docker:
docker_core:
needs: [npm]
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
@ -48,4 +53,36 @@ jobs:
push: true
target: bdscore
tags: bdsmaneger/core:latest
platforms: linux/amd64,linux/arm64,linux/arm/v7
platforms: ${{ env.DOCKER_ARCH }}
docker_base:
needs: [npm]
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_ORG_USER }}
password: ${{ secrets.DOCKER_ORG_PASS }}
- name: checkout
uses: actions/checkout@master
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
push: true
target: bdsbase
tags: |
bdsmaneger/base:latest
bdsmaneger/base:${{ github.run_id }}
bdsmaneger/node_image:latest
bdsmaneger/node_image:${{ github.run_id }}
platforms: ${{ env.DOCKER_ARCH }}

27
.gitignore vendored
View File

@ -1,26 +1,23 @@
# Log
*.log
# test files
*.test
*test*.js*
test/
Test/
# Node
node_modules/
*-Test/
*teste/
debug.log
Bds_Maneger
.dccache
docs/
run.log
build.log
Docker.js.log
Docker.js
# Bds Maneger Core Binaries
bds_maneger
BdsManager-bin*
Bds-Maneger-Core
# Docker Build
Docker.exe
# Bin Ignores
bin/*
!bin/bds_maneger.js
!bin/telegram_bot.js
# **
.husky
Servers

View File

@ -1,5 +1,5 @@
terminal:
image: bdsmaneger/node_image:latest
image: bdsmaneger/core:latest
services:
- docker:dind
before_script:

View File

@ -1,21 +0,0 @@
Docker_Nightly:
image: ubuntu:latest
variables:
DOCKER_TLS_CERTDIR: ""
DOCKER_DRIVER: overlay2
DOCKER_HOST: tcp://docker:2375
services:
- docker:dind
before_script:
- |
apt update && apt install -y curl &> /dev/null
curl https://get.docker.com | bash - &> /dev/null
docker info
docker run --privileged --rm tonistiigi/binfmt --install all
docker run --privileged --rm multiarch/qemu-user-static --reset -p yes
docker buildx create --name multiarch --driver docker-container --use
docker buildx inspect --bootstrap
docker login --username="$DOCKER_USER" --password="$DOCKER_TOKEN" &> /dev/null
script:
- docker pull bdsmaneger/maneger:nightly
- docker buildx build -t bdsmaneger/maneger:nightly --platform=linux/amd64,linux/arm64/v8,linux/arm/v7 .

View File

@ -1,8 +1,5 @@
Docker_Stable:
Docker:
image: ubuntu:latest
only:
- v*
- V*
variables:
DOCKER_TLS_CERTDIR: ""
DOCKER_DRIVER: overlay2
@ -18,6 +15,5 @@ Docker_Stable:
docker run --privileged --rm multiarch/qemu-user-static --reset -p yes
docker buildx create --name multiarch --driver docker-container --use
docker buildx inspect --bootstrap
docker login --username="$DOCKER_USER" --password="$DOCKER_TOKEN" &> /dev/null
script:
- docker buildx build -t bdsmaneger/maneger:latest --platform=linux/amd64,linux/arm64/v8,linux/arm/v7 .
- docker buildx build -t bdsmaneger/maneger:latest --platform=linux/amd64,linux/arm64,linux/arm/v7 .

View File

@ -1,17 +1,16 @@
Docker/
.docker*
.github/
.devconatiner/
.vscode/
node_modules/
*-Test/
*teste/
debug.log
Bds_Maneger
.dccache
run.log
build.log
Docker.js.log
Docker.js
bds_maneger
BdsManager-bin*
# Log
*.log
# test files
*.test
*test*.js*
test/
Test/
# Git
git*
.git*
# Docker
.dockerignore
Docker*

View File

@ -1,201 +0,0 @@
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json",
"contentVersion": "1.50.0.0",
"parameters": {
"containerName": {
"type": "string",
"maxLength": 63,
"defaultValue": "bds-maneger"
},
"TelegramBotToken": {
"type": "string",
"defaultValue": "null"
},
"WorldName": {
"type": "string",
"defaultValue": "Minecraft Bedrock"
},
"ServerDescription": {
"type": "string",
"defaultValue": "The Bds Maneger in Docker"
},
"ServerGameMode": {
"type": "string",
"defaultValue": "survival",
"allowedValues": ["survival","creative","hardcore"]
},
"ServerDifficulty": {
"type": "string",
"defaultValue": "normal",
"allowedValues": ["normal","easy"]
},
"ServerPlayers": {
"type": "string",
"defaultValue": "30",
"metadata": {
"description": "The more players, the more CPU, the more RAM will be needed."
},
"allowedValues": ["5","10","15","20","25","30","35","40","45","50","70","100","200"]
},
"ServerPlatform": {
"type": "string",
"defaultValue": "bedrock",
"allowedValues": ["bedrock", "java", "pocketmine", "jsprismarine"],
"metadata": {
"description": "Bedrock: Phones, Xbox, Nintendo switch, etc. Java: Desktops"
}
},
"numberCpuCores": {
"type": "string",
"defaultValue": "2",
"allowedValues": ["1","2","3","4"]
},
"RamMemory": {
"type": "string",
"allowedValues": ["1","2","4","6","8","10"],
"defaultValue": "4"
}
},
"variables": {
"bdsstorage": "bdssave",
"StorageName": "[concat('bdssave', uniqueString(resourceGroup().id))]",
"DnsName": "[concat('bdsdns-', uniqueString(resourceGroup().id))]",
"bds_ports": [
{
"port": "1932",
"protocol": "TCP"
},
{
"port": "6565",
"protocol": "TCP"
},
{
"port": "19132",
"protocol": "UDP"
},
{
"port": "19133",
"protocol": "UDP"
}
]
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-06-01",
"name": "[variables('StorageName')]",
"location": "[resourceGroup().location]",
"kind": "StorageV2",
"sku": {
"name": "Standard_LRS",
"tier": "Standard"
},
"properties": {
"accessTier": "Hot",
"allowBlobPublicAccess": true,
"allowSharedKeyAccess": true,
"largeFileSharesState": "Enabled"
}
},
{
"type": "Microsoft.Storage/storageAccounts/fileServices/shares",
"apiVersion": "2019-06-01",
"name": "[concat(variables('StorageName'), '/default/', variables('bdsstorage'))]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', variables('StorageName'))]"
]
},
// Docker Bds Manegerg Image
{
"location": "[resourceGroup().location]",
"name": "[parameters('containerName')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/fileServices/shares', variables('StorageName'), 'default', variables('bdsstorage') )]"
],
"type": "Microsoft.ContainerInstance/containerGroups",
"apiVersion": "2019-12-01",
"properties": {
"containers": [
{
"name": "[parameters('containerName')]",
"properties": {
"image": "bdsmaneger/core:latest",
"resources": {
"requests": {
"cpu": "[int(parameters('numberCpuCores'))]",
"memoryInGB": "[float(parameters('RamMemory'))]"
}
},
"ports": "[variables('bds_ports')]",
"environmentVariables": [
{
"name": "TELEGRAM_TOKEN",
"value": "[parameters('TelegramBotToken')]"
},
{
"name": "WORLD_NAME",
"value": "[parameters('WorldName')]"
},
{
"name": "DESCRIPTION",
"value": "[parameters('ServerDescription')]"
},
{
"name": "GAMEMODE",
"value": "[parameters('ServerGameMode')]"
},
{
"name": "DIFFICULTY",
"value": "[parameters('ServerDifficulty')]"
},
{
"name": "PLAYERS",
"value": "[parameters('ServerPlayers')]"
},
{
"name": "SERVER",
"value": "[parameters('ServerPlatform')]"
},
{
"name": "BDS_VERSION",
"value": "latest"
}
],
"volumeMounts": [
{
"name": "save",
"mountPath": "/home/bds"
}
]
}
}
],
"restartPolicy": "OnFailure",
"osType": "Linux",
"ipAddress": {
"type": "Public",
"ports": "[variables('bds_ports')]",
"dnsNameLabel": "[variables('DnsName')]"
},
"volumes": [
{
"name": "save",
"azureFile": {
"shareName": "[variables('bdsstorage')]",
"StorageAccountName": "[variables('StorageName')]",
// https://stackoverflow.com/a/33227123
"storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('StorageName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[1].value]"
}
}
]
},
"tags": {}
}
],
"outputs": {
"containerIPv4Address": {
"type": "string",
"value": "[reference(resourceId('Microsoft.ContainerInstance/containerGroups/', parameters('containerName'))).ipAddress.ip]"
}
}
}

100
bin/Docker.js Normal file
View File

@ -0,0 +1,100 @@
#!/usr/bin/env node
const BdsCore = require("../index");
const { GetPlatform } = require("../lib/BdsSettings");
const { Servers } = require("../lib/ServerURL");
const { CronJob } = require("cron");
const BdsInfo = require("../BdsManegerInfo.json");
process.env.BDS_DOCKER_IMAGE = true;
function StartServer(){
console.log("The entire log can be accessed via the api and/or the docker log");
const ServerStarted = BdsCore.start();
ServerStarted.log(a => process.stdout.write(a));
ServerStarted.exit(process.exit);
BdsCore.api();
new CronJob("0 */1 * * *", async () => {
try {
const CurrentLocalVersion = BdsCore.getBdsConfig().server.versions[GetPlatform()],
CurrentRemoteVersion = Object.getOwnPropertyNames((await (await fetch(BdsInfo.download.servers)).json())[GetPlatform()])[0];
if (CurrentLocalVersion !== CurrentRemoteVersion) {
let currenttime = `Hello we are starting the server upgrade from version ${CurrentLocalVersion} to version ${CurrentRemoteVersion}, you have 20 seconds to exit the server`
console.log("Update Server:", currenttime);
ServerStarted.say(currenttime);
let countdown = 20;
while (countdown > 1) {
currenttime = `${countdown} seconds remaining to stop Server!`;
console.log(currenttime);
ServerStarted.say(currenttime);
countdown--;
await new Promise(resolve => setTimeout(resolve, 1000));
}
currenttime = "Stopping the server"
console.log(currenttime);
ServerStarted.say(currenttime);
await new Promise(resolve => setTimeout(resolve, 600));
ServerStarted.stop();
}
} catch (err) {
console.log(err);
}
});
}
// Check Installed Server
const AllVersions = BdsCore.BdsSettigs.GetJsonConfig().server.versions;
if (Object.getOwnPropertyNames(AllVersions).filter(platform => AllVersions[platform]).length >= 1) {
if (process.env.UPDATE_SERVER === "true") {
BdsCore.download(true, true, (err) => {
if (err) {
console.log(err);
process.exit(1);
}
StartServer();
});
} else {
// Check for Update
if (AllVersions[GetPlatform()] === Object.getOwnPropertyNames(Servers[GetPlatform()])[0]) {
console.log("The entire log can be accessed via the api and/or the docker log");
const ServerStarted = BdsCore.start();
ServerStarted.log(a => process.stdout.write(a));
ServerStarted.exit(process.exit);
BdsCore.api();
} else {
BdsCore.download(true, true, (err) => {
if (err) {
console.log(err);
process.exit(1);
}
StartServer();
});
}
}
} else {
console.log("Server is not installed, starting server implementation");
// Import ENV to Settings Server
const { DESCRIPTION, WORLD_NAME, GAMEMODE, DIFFICULTY, ACCOUNT, PLAYERS, SERVER, ENABLE_COMMANDS } = process.env;
// Update Platform
BdsCore.change_platform(SERVER || "bedrock");
BdsCore.download(true, true, (err) => {
if (err) {
console.log(err);
process.exit(1);
}
// Create JSON Config
const ServerConfig = {
world: WORLD_NAME,
description: DESCRIPTION,
gamemode: GAMEMODE,
difficulty: DIFFICULTY,
players: parseInt(PLAYERS),
commands: ENABLE_COMMANDS === "true",
account: ACCOUNT === "true",
whitelist: false,
port: 19132,
portv6: 19133,
}
BdsCore.set_config(ServerConfig);
StartServer();
});
}

View File

@ -18,7 +18,7 @@ const
server = (argv.p || argv.platform),
version = (argv.v || argv.version),
SystemCheck = (argv.S || argv.system_info),
bds_version = (argv.d || argv.server_download),
bds_version = (argv.d || argv.download),
start = (argv.s || argv.server_version),
help = (argv.h || argv.help),
kill = (argv.k || argv.kill);
@ -52,8 +52,12 @@ function StartServer(){
console.log("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(echo)
bds_server.exit(function (code){if (code === 3221225781) return open("https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll");console.log("leaving the server, status code: ", code);process.exit(code)});
bds_server.log(data => process.stdout.write(data));
bds_server.exit(function (code){
if (code === 3221225781 && process.platform === "win32") return open("https://docs.the-bds-maneger.org/Bds Maneger core/WindowsFixDll");
console.log("leaving the server, status code:", code);
process.exit(code)
});
// CLI Commands
const rl = readline.createInterface({input: process.stdin,output: process.stdout});
@ -89,7 +93,7 @@ if (help) {
" -s --start Start Server",
" -k --kill Detect and kill bds servers",
" -p --platform Select server platform",
" -d --server_download server version to install, default \"latest\"",
" -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.",
@ -154,21 +158,30 @@ if (SystemCheck) {
if (bds_version){
try {
if (argv.interactive) {
console.log(`Geting versions to ${GetPlatform()}`);
const LoadVersion = require("../../lib/ServerURL").Servers[GetPlatform()]
const LoadVersion = require("../lib/ServerURL").Servers[GetPlatform()]
const Version = Object.getOwnPropertyNames(LoadVersion)
// List Version
for (let version in Version) console.log(`${version}: ${GetPlatform()} version ${Version[version]}`); // deepscan-disable-line FORIN_ARRAY
// deepcode ignore MissingClose: <please specify a reason of ignoring this>
const DownloadOptions = readline.createInterface({input: process.stdin,output: process.stdout});
console.log("\nSelect Option");
DownloadOptions.on("line", (input) => {
download(Version[parseInt(input)], true, function(){
console.log("Installation was successful, so start the server with the -s option");
if (start) StartServer();
else process.exit(0)
})
});
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("Option Version");
for (let option in Version) console.log(`${parseInt(option) + 1} -------- ${Version[option]}`);
StartQuestion(readline.createInterface({input: process.stdin,output: process.stdout}));
}
else bds.download(bds_version, true, function(){
if (start) StartServer();
@ -178,8 +191,4 @@ if (bds_version){
}
// Start server
function echo(data = ""){
data = data.split("\n").filter(data => {return (data !== "")})
data.forEach(data => console.log(data))
}
if (start && !(server || version || SystemCheck || bds_version || help)) StartServer();

View File

@ -7,23 +7,6 @@ const { bds_dir } = require("./lib/BdsSettings");
if (typeof fetch === "undefined") global.fetch = require("node-fetch");
function date(format) {
const today = new Date(),
yaer = today.getFullYear(),
day = String(today.getDate()).padStart(2, "0"),
month = String(today.getMonth() + 1).padStart(2, "0"),
hour = today.getHours(),
minute = today.getMinutes();
// ---------------------------------------------------------
if (format === "year") return yaer
else if (format === "day") return day
else if (format === "month") return month
else if (format === "hour") return hour
else if (format === "minute") return minute
else if (format === "hour_minu") return `${hour}-${minute}`
else return `${day}-${month}-${yaer}_${hour}-${minute}`
}
const bds_core_package = resolve(__dirname, "package.json")
module.exports.package_path = bds_core_package
module.exports.package_json = require("./package.json");
@ -66,10 +49,11 @@ module.exports.telegram_token_save = UpdateTelegramToken
*/
module.exports.api = require("./src/rest/api");
function token_register() {
function token_register(Admin_Scoper = ["web_admin", "admin"]) {
Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper));
const bds_token_path = path.join(bds_dir, "bds_tokens.json");
if (!(fs.existsSync(bds_token_path))) fs.writeFileSync(bds_token_path, "[]");
const tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8"));
let tokens = []
if (fs.existsSync(bds_token_path)) tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8"));
// Get UUID
const getBdsUUId = randomUUID().split("-");
@ -79,7 +63,7 @@ function token_register() {
tokens.push({
token: bdsuid,
date: new Date(),
scopers: ["admin"]
scopers: Admin_Scoper
});
fs.writeFileSync(bds_token_path, JSON.stringify(tokens, null, 4), "utf8");
console.log(`Bds Maneger API REST token: "${bdsuid}"`);
@ -93,6 +77,13 @@ function token_register() {
*/
module.exports.token_register = token_register
/**
* Register tokens to use in Bds Maneger REST and other supported applications
*
* @example token_register()
*/
module.exports.bds_maneger_token_register = token_register
/**
* Update, Get and more to Modifications Bds Settings File
*/
@ -104,11 +95,6 @@ const { config, get_config } = require("./src/ServerSettings");
const download = require("./src/BdsServersDownload");
const { start, stop, BdsCommand, CronBackups } = require("./src/BdsManegerServer")
/**
* Take the current date
*/
module.exports.BdsDate = module.exports.date = date
/**
* sending commands more simply to the server
*
@ -165,7 +151,7 @@ module.exports.kill = Kill
*
* java: download("1.16.5")
*
* any platform: download("latest") // It will download the latest version available for download
* any platform: download("latest") || download(true) // It will download the latest version available for download
*/
module.exports.download = download

View File

@ -1,4 +1,4 @@
const { join, resolve } = require("path");
const { join, resolve, basename } = require("path");
const { existsSync, writeFileSync, mkdirSync, readFileSync } = require("fs");
const { homedir } = require("os");
const { valid_platform } = require("./BdsSystemInfo");
@ -17,7 +17,7 @@ var default_platformConfig;
if (valid_platform["bedrock"]) default_platformConfig = "bedrock";
else if (valid_platform["java"]) default_platformConfig = "java";
else if (valid_platform["pocketmine"]) default_platformConfig = "pocketmine";
else default_platformConfig = "jsprismarine"
else throw new Error("We cannot run any platforms on this system/device");
// Config Base to Bds Maneger Core and others Projects
var Config = {
@ -46,6 +46,7 @@ var Config = {
java: null,
pocketmine: null,
jsprismarine: null,
spigot: null,
},
Settings: {
java: {
@ -75,6 +76,7 @@ var Config = {
java: true,
pocketmine: true,
jsprismarine: true,
spigot: true,
},
{
username: "Alex",
@ -83,6 +85,7 @@ var Config = {
java: true,
pocketmine: true,
jsprismarine: true,
spigot: true,
},
{
username: "steve",
@ -91,6 +94,7 @@ var Config = {
java: true,
pocketmine: true,
jsprismarine: true,
spigot: true,
},
{
username: "alex",
@ -99,6 +103,7 @@ var Config = {
java: true,
pocketmine: true,
jsprismarine: true,
spigot: true,
}
],
telegram: {
@ -114,7 +119,7 @@ if (existsSync(ConfigPath)) Config = {
...Config,
...yaml.parse(readFileSync(ConfigPath, "utf8"))
}; else writeFileSync(ConfigPath, yaml.stringify(Config))
process.on("exit", ()=>SaveConfig())
process.on("exit", () => SaveConfig())
// Paths
if (!(existsSync(Config.paths["backups"]))) mkdirSync(Config.paths["backups"], {recursive: true})
@ -127,18 +132,15 @@ const ServersPaths = {
java: join(Config.paths.servers, "Java"),
pocketmine: join(Config.paths.servers, "Pocketmine-MP"),
jsprismarine: join(Config.paths.servers, "JSPrismarine"),
dragonfly: join(Config.paths.servers, "Dragonfly_go"),
spigot: join(Config.paths.servers, "Spigot")
}
for (let Servers of Object.getOwnPropertyNames(ServersPaths)) {
if (!(existsSync(ServersPaths[Servers]))) {
console.log(`Creating the ${Servers} Folder`);
mkdirSync(ServersPaths[Servers], {recursive: true})
Object.getOwnPropertyNames(ServersPaths).map(Servers => ServersPaths[Servers]).forEach(Servers => {
if (!(existsSync(Servers))) {
console.log(`Creating the ${basename(Servers)} Folder`);
mkdirSync(Servers, {recursive: true})
}
}
// return settings by function
function GetJsonConfig(){
return Config
}
});
// get the path from the settings and return by function
function GetPaths(path = null){
@ -155,11 +157,6 @@ function GetServerPaths(path = null){
return ServersPaths[path]
}
// Get the server settings for now it's only being used in Java
function GetServerSettings(platform = Config.server.platform){
return Config.server.Settings[platform]
}
// Update the settings and save at the same time so as not to lose any information from the Bds Maneger settings
function UpdateServerVersion(version = null, platform = Config.server.platform){
if (Config.server.versions[platform] || Config.server.versions[platform] === null) {
@ -169,21 +166,6 @@ function UpdateServerVersion(version = null, platform = Config.server.platform){
} else throw new Error("Platform invalid")
}
// Return an Object with all server versions installed
function GetServerVersion(){
return Config.server.versions
}
// Catch Players/People from Servers/Telegram to be banned or removed from Server/Minecraft
function GetServerBan(){
return Config.ban
}
// Cron for Backup
function GetCronBackup(){
return Config.server.BackupCron
}
// Update the entire Bds Manager Core platform
function UpdatePlatform(platform = Config.server.platform){
platform = platform.toLocaleLowerCase();
@ -196,6 +178,9 @@ function UpdatePlatform(platform = Config.server.platform){
} else if (/pocketmine/.test(platform)) {
Config.server.platform = "pocketmine";
SaveConfig()
} else if (/spigot/.test(platform)) {
Config.server.platform = "spigot";
SaveConfig()
} else if (/jsprismarine/.test(platform)) {
Config.server.platform = "jsprismarine";
SaveConfig()
@ -203,11 +188,6 @@ function UpdatePlatform(platform = Config.server.platform){
return platform
}
// Return to platform
function GetPlatform(){
return Config.server.platform
}
// Telegram
function UpdateTelegramToken(token = null){
if (!(token)) throw new Error("Telegram Token invalid")
@ -216,18 +196,20 @@ function UpdateTelegramToken(token = null){
return token
}
function GetTelegramToken(){
return Config.telegram.token
}
const GetJsonConfig = () => Config;
function GetTelegramAdmins(){
return Config.telegram.admins
}
const GetCronBackup = () => Config.server.BackupCron;
const GetPlatform = () => Config.server.platform;
const GetServerBan = () => Config.ban;
const GetServerVersion = () => Config.server.versions;
const GetServerSettings = (platform = Config.server.platform) => Config.server.Settings[platform];
const GetTelegramToken = () => Config.telegram.token;
const GetTelegramAdmins = () => Config.telegram.admins;
// Get a temporary host to connect to the server.
function GetTempHost(){
return Config.bds.enable_tmp_host
}
const GetTempHost = () => Config.bds.enable_tmp_host
// Enable and/or disable pick up temporary host.
function UpdateTempHost(enable = false){
@ -236,7 +218,8 @@ function UpdateTempHost(enable = false){
// Save
Config.bds.enable_tmp_host = enable
return SaveConfig();
SaveConfig();
return true;
}
// Get the server settings

View File

@ -1,40 +1,39 @@
const commadExist = require("./commandExist");
const { execSync } = require("child_process");
const { readdirSync } = require("fs");
const { release } = require("os");
const { readdirSync } = require("fs");
const commadExist = require("./commandExist");
const { PHPBin, Servers } = require("./ServerURL");
// System Architect (x64, aarch64 and others)
var arch;
if (process.arch === "arm64") arch = "aarch64"; else arch = process.arch
if (process.arch === "arm64") arch = "aarch64";
else arch = process.arch
module.exports.arch = arch
var system,
require_qemu = false,
valid_platform = {
bedrock: true,
pocketmine: true,
java: commadExist("java"),
jsprismarine: commadExist("node")
}
require_qemu = false,
valid_platform = {
bedrock: true,
pocketmine: true,
java: commadExist("java"),
dragonfly: commadExist("go"),
}
// check php bin
if (PHPBin[process.platform]) {
if (PHPBin[process.platform][arch]) valid_platform["pocketmine"] = true; else valid_platform["pocketmine"] = false
} else valid_platform["pocketmine"] = false
if ((PHPBin[process.platform] || {})[arch]) valid_platform["pocketmine"] = true;
else valid_platform["pocketmine"] = false;
// SoSystem X
if (process.platform == "win32") {
system = "Windows";
// arm64 and X64
// if (!(arch === "x64" || arch === "aarch64")) valid_platform["bedrock"] = false;
} else if (process.platform == "linux") {
system = "Linux";
if (Servers.bedrock[Servers.latest.bedrock][arch]) {
if (Servers.bedrock[Servers.latest.bedrock][arch][process.platform]) valid_platform["bedrock"] = true; else valid_platform["bedrock"] = false;
} else valid_platform["bedrock"] = false
if (PHPBin[process.platform][arch]) valid_platform["pocketmine"] = true; else valid_platform["pocketmine"] = false
// Bedrock Check
if (Servers.bedrock[Servers.latest.bedrock][arch]) {
if (Servers.bedrock[Servers.latest.bedrock][arch][process.platform]) valid_platform["bedrock"] = true;
else valid_platform["bedrock"] = false;
} else valid_platform["bedrock"] = false;
if (valid_platform["bedrock"] === false) {
if (commadExist("qemu-x86_64-static")) {
@ -49,13 +48,9 @@ if (process.platform == "win32") {
} else if (process.platform === "android") {
system = "Android";
valid_platform["bedrock"] = false
valid_platform["java"] = false
} else {
console.log(`The Bds Maneger Core does not support ${process.platform} systems, as no tests have been done.`);
system = "Other";
valid_platform["bedrock"] = false
valid_platform["pocketmine"] = false
process.exit(254)
process.exit(127);
}
function GetKernel() {
@ -66,43 +61,32 @@ function GetKernel() {
else if (kernelVersion <= 6.3) return "Windows 8.1";
else if (kernelVersion <= 10.0) return "Windows 10";
else return "Other Windows or Windows 11";
}
else if (process.platform === "android") return `${release()}, CPU Core ${readdirSync("/sys/devices/system/cpu/").filter(data=>{return /cpu[0-9]/.test(data)}).length}`;
else if (commadExist("uname")){
} else if (process.platform === "android") return `Android: ${release()}, CPU Core ${readdirSync("/sys/devices/system/cpu/").filter(data => /cpu[0-9]/.test(data)).length}`;
else if (commadExist("uname")) {
const str = execSync("uname -rv").toString("ascii");
switch (true) {
// amazon aws EC2
case /aws/.test(str):
if (process.arch === "arm64" || process.arch === "aarch64") return "Amazon AWS Cloud arm64: AWS Graviton";
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";
// Azure Virtual Machinime (VM)
case /[aA]zure/.test(str):
return "Microsoft Azure";
// Google Cloud Virtual Machinime (VM)
case /[gG]cp/.test(str):
return "Google Cloud Platform";
// Oracle cloud Virtual Machinime (VM)
case /[oO]racle/.test(str):
return "Oracle Cloud infrastructure";
// Darwin
case /[dD]arwin/.test(str):
return "Apple MacOS";
// Others Kernels
default:
return str.split("\n").join("");
// Amazon web services
if (/aws/.test(str)) {
if (/arm64|aarch64/.test(process.arch)) return "Amazon AWS Cloud arm64: AWS Graviton Serie";
else return `Amazon AWS Cloud ${process.arch}: ${require("os").cpus()[0].model}`;
}
// Windows subsystem for Linux
else if (/WSL2|microsft/.test(str)) return "Microsoft WSL";
// Azure Virtual Machinime (VM)
else if (/[aA]zure/.test(str)) return "Microsoft Azure";
// Google Cloud Virtual Machinime (VM)
else if (/[gG]cp/.test(str)) return "Google Cloud Platform";
// Oracle cloud Virtual Machinime (VM)
else if (/[oO]racle/.test(str)) return "Oracle Cloud infrastructure";
// Darwin
else if (/[dD]arwin/.test(str)) return "Apple MacOS";
// Others Kernels
else return str.replace(/\n|\t|\r/gi, "");
} else return "Not identified";
}

View File

@ -1,4 +1,3 @@
const bds = require("../index")
const { join, resolve } = require("path");
const { readdirSync, existsSync, readFileSync, statSync } = require("fs")
const AdmZip = require("adm-zip");
@ -14,7 +13,8 @@ function Backup() {
pocketmine: GetServerPaths("pocketmine"),
jsprismarine: GetServerPaths("jsprismarine")
}
const name = `Bds_Maneger-Backups_${bds.date()}.zip`
const CurrentDate = new Date();
const name = `Bds_Maneger_Core_Backups_${CurrentDate.getDate()}-${CurrentDate.getMonth()}-${CurrentDate.getFullYear()}.zip`
const PathBackup = join(GetPaths("backups"), name);
// Bedrock
@ -35,9 +35,6 @@ function Backup() {
for (let index of ["pocketmine.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine");
} else console.info("Skipping the pocketmine as it was not installed");
// JSPrismarine
// The Bds Maneger Core Backup
for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index));

View File

@ -74,13 +74,8 @@ function start() {
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")
// Show Error platform
else throw Error("Bds Config Error")
// Setup commands
const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, {
@ -99,8 +94,7 @@ function start() {
}
// Log file
const LogFile = path.join(GetPaths("log"), `${bds.date()}_${GetPlatform()}_Bds_log.log`);
const LogFile = path.join(GetPaths("log"), `${GetPlatform()}_${new Date().toString()}_Bds_log.log`);
const LatestLog_Path = path.join(GetPaths("log"), "latest.log");
const LogSaveFunction = data => {
fs.appendFileSync(LogFile, data);
@ -121,84 +115,78 @@ function start() {
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 say = (text = "") => ServerExec.stdin.write(BdsInfo.Servers.bedrock.say.replace("{{Text}}", text));
// sets bds core commands
const command = async function (command = "list", callback = function (){}) {
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);
}
});
};
const log = function (logCallback = data => process.stdout.write(data)){
if (typeof logCallback !== "function") throw new Error("Log Callback is not a function");
ServerExec.stdout.on("data", data => logCallback(data));
ServerExec.stderr.on("data", data => logCallback(data));
};
const exit = function (exitCallback = process.exit){if (
typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code));
};
const on = function(action = String, callback = Function) {
if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect");
// Functions
const data = data => Player_Json(data, function (array_status){
array_status.filter(On => {if ("all" === action || On.Action === action) return true; else return false;}).forEach(_player => callback(_player))
});
ServerExec.stdout.on("data", data);
ServerExec.stderr.on("data", data);
};
const stop = function (){
ServerExec.stdin.write(BdsInfo.Servers[GetPlatform()].stop+"\n");
return BdsInfo.Servers[GetPlatform()].stop;
};
const op = function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].op.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
};
const deop = function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
};
const ban = function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
};
const kick = function (player = "Steve", text = "you got kicked") {
let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text);
ServerExec.stdin.write(command+"\n");
return command;
};
const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) {
let command = BdsInfo.Servers[GetPlatform()].tp.replace("{{Player}}", player);
if (cord.x) command = command.replace("{{X}}", cord.x); else command = command.replace("{{X}}", 0);
if (cord.y) command = command.replace("{{Y}}", cord.y); else command = command.replace("{{Y}}", 128);
if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0);
ServerExec.stdin.write(command+"\n");
return command;
};
const say = (text = "") => ServerExec.stdin.write(BdsInfo.Servers.bedrock.say.replace("{{Text}}", text));
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 (_player.Action === action) callback(_player);
if (action === "all") callback(_player);
}
});
ServerExec.stdout.on("data", data);
ServerExec.stderr.on("data", data);
},
op: function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].op.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
},
deop: function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
},
ban: function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n");
return command;
},
kick: function (player = "Steve", text = "you got kicked") {
let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text);
ServerExec.stdin.write(command+"\n");
return command;
},
tp: function (player = "Steve", cord = {x: 0, y: 128, z: 0}) {
let command = BdsInfo.Servers[GetPlatform()].tp.replace("{{Player}}", player);
if (cord.x) command = command.replace("{{X}}", cord.x); else command = command.replace("{{X}}", 0);
if (cord.y) command = command.replace("{{Y}}", cord.y); else command = command.replace("{{Y}}", 128);
if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0);
ServerExec.stdin.write(command+"\n");
return command;
},
say,
command, log, exit, on, stop, op, deop, ban, kick, tp, say
}
ServerExec.on("exit", ()=>{delete global.BdsExecs[returnFuntion.uuid]});
ServerExec.on("exit", () => delete global.BdsExecs[returnFuntion.uuid]);
global.BdsExecs[returnFuntion.uuid] = returnFuntion;
return returnFuntion;
}
@ -348,6 +336,7 @@ module.exports = {
start,
BdsCommand,
stop,
GetSessions,
CronBackups: CurrentBackups,
Player_Search,
}

View File

@ -1,16 +1,158 @@
var AdmZip = require("adm-zip");
const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = require("fs");
const { join, resolve, basename } = require("path");
const bds = require("../index")
var AdmZip = require("adm-zip");
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 bds = require("../index");
const { execSync } = require("child_process");
module.exports = async function (version, force_install, callback) {
return new Promise(async (promise_resolve, promise_reject) => {
try {
// Server Paths
const bds_dir_bedrock = GetServerPaths("bedrock"),
bds_dir_java = GetServerPaths("java"),
bds_dir_pocketmine = GetServerPaths("pocketmine"),
bds_dir_spigot = GetServerPaths("spigot"),
bds_dir_dragonfly = GetServerPaths("dragonfly");
// JSON Configs and others
const Servers = (await (await fetch(Extra.download.servers)).json());
const ServerVersion = GetServerVersion();
const CurrentPlatform = GetPlatform();
if (force_install === true) {
ServerVersion.java = "latest";
ServerVersion.bedrock = "latest"
ServerVersion.pocketmine = "latest"
}
if (!(version) || version === true || version === "true" || version === "latest") version = Servers.latest[CurrentPlatform]
var url;
console.log(`Installing version ${version}`);
// Bedrock Installer Script
if (CurrentPlatform === "bedrock") {
if (valid_platform.bedrock === true){
if (version === "latest") version = Servers.latest.bedrock
if (!(force_install === true) && ServerVersion.bedrock === version) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
} else {
if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`)
url = Servers.bedrock[version][bds.arch][process.platform]
var server_configs, permissions, whitelist;
if (existsSync(join(bds_dir_bedrock, "server.properties"))) server_configs = readFileSync(join(bds_dir_bedrock, "server.properties"), "utf8");
if (existsSync(join(bds_dir_bedrock, "permissions.json"))) permissions = readFileSync(join(bds_dir_bedrock, "permissions.json"), "utf8");
if (existsSync(join(bds_dir_bedrock, "whitelist.json"))) whitelist = readFileSync(join(bds_dir_bedrock, "whitelist.json"), "utf8");
// Download and Add to Adm_Zip
const zip = new AdmZip(Buffer.from((await (await fetch(url)).arrayBuffer())))
console.log("Download Sucess")
zip.extractAllTo(bds_dir_bedrock, true)
console.log("Extract Sucess")
if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs);
if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions)
if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist)
UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
}
} else throw Error("Bedrock Not suported")
}
// Java
else if (CurrentPlatform === "java") {
if (valid_platform.java === true){
if (version === "latest") version = Servers.latest.java
if (!(force_install === true) && version === ServerVersion.java) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true)
} else {
url = Servers.java[version].url
console.log(`Server data publish: ${Servers.java[version].data}`)
writeFileSync(join(bds_dir_java, "MinecraftServerJava.jar"), Buffer.from((await (await fetch(url)).arrayBuffer())), "binary")
console.log("Success when downloading and saving Minecraft Server java");
UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
}
} else throw Error("Java is not supported or required software is not installed")
}
// Pocketmine-MP
else if (CurrentPlatform === "pocketmine") {
if (valid_platform.pocketmine === true) {
if (version === "latest") version = Servers.latest.pocketmine
if (!(force_install === true) && version === ServerVersion.pocketmine) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true)
} else {
const PocketMineJson = Servers.pocketmine[version]
console.log(`Server data publish: ${PocketMineJson.data}`);
writeFileSync(join(bds_dir_pocketmine, "PocketMine-MP.phar"), Buffer.from((await (await fetch(PocketMineJson.url)).arrayBuffer())), "binary")
console.log("Success downloading and saving PocketMine-MP php");
await php_download();
// Update server Version
UpdateServerVersion(version)
// Callback
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
}
} else throw Error("Pocketmine not suported")
}
// Spigot
else if (CurrentPlatform === "spigot") {
if (valid_platform.java) {
if (version === "latest") version = Servers.latest.spigot;
if (!(force_install === true) && version === ServerVersion.spigot) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true)
} else {
const SpigotURL = Servers.spigot[version].url;
if (Servers.spigot[version].data) console.log(`Server data publish: ${Servers.spigot[version].data}`);
writeFileSync(join(bds_dir_spigot, "spigot.jar"), Buffer.from((await (await fetch(SpigotURL)).arrayBuffer())), "binary");
console.log("Success when downloading and saving Spigot");
UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
}
} else throw Error("Java is not supported or required software is not installed")
}
// dragonfly
else if (CurrentPlatform === "dragonfly") {
if (valid_platform.dragonfly) {
console.info("Dragonfly does not support versions");
execSync("git clone https://github.com/df-mc/dragonfly ./", {
cwd: bds_dir_dragonfly
});
if (typeof callback === "function") await callback(undefined, true);
promise_resolve(true);
} else throw Error("Dragonfly not suported")
}
// Unidentified platform
else throw Error("Bds maneger Config file error")
} catch (err) {
if (typeof callback === "function") await callback(err, false);
return promise_reject(err);
}
});
}
async function php_download() {
const bds_dir_pocketmine = GetServerPaths("pocketmine"),
PHPBin = (await (await fetch(Extra.download.php)).json());
const bds_dir_pocketmine = GetServerPaths("pocketmine");
const PHPBin = (await (await fetch(Extra.download.php)).json());
const phpFolder = resolve(bds_dir_pocketmine, "bin");
const phpExtensiosnsDir = resolve(bds_dir_pocketmine, "bin/php7/lib/php/extensions");
@ -19,7 +161,6 @@ async function php_download() {
if (!(urlPHPBin)) throw new Error("unsupported system")
urlPHPBin = urlPHPBin[bds.arch]
// Remove Old php Binary if it exists
if (existsSync(phpFolder)) {
console.log("Removing old PHP files.");
@ -34,7 +175,7 @@ async function php_download() {
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
console.log("Successfully extracting the binaries")
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf-8");
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8");
if (!(existsSync(phpExtensiosnsDir))) return true;
const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => {
@ -49,123 +190,3 @@ async function php_download() {
}
return true;
}
module.exports = async function (version, force_install, callback) {
try {
const bds_dir_bedrock = GetServerPaths("bedrock"),
bds_dir_java = GetServerPaths("java"),
bds_dir_pocketmine = GetServerPaths("pocketmine"),
bds_dir_jsprismarine = GetServerPaths("jsprismarine");
const Servers = (await (await fetch(Extra.download.servers)).json());
const ServerVersion = GetServerVersion()
const CurrentPlatform = GetPlatform()
if (force_install === true) {
ServerVersion.java = "latest";
ServerVersion.bedrock = "latest"
ServerVersion.pocketmine = "latest"
}
if (!(version) || version === true || version === "true" || version === "latest") version = Servers.latest[CurrentPlatform]
var url;
console.log(`Installing version ${version}`);
// Bedrock Installer Script
if (CurrentPlatform === "bedrock") {
if (valid_platform.bedrock === true){
if (version === "latest") version = Servers.latest.bedrock
if (ServerVersion.bedrock === version) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
return true
} else {
if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`)
url = Servers.bedrock[version][bds.arch][process.platform]
var server_configs, permissions, whitelist;
if (existsSync(join(bds_dir_bedrock, "server.properties"))) server_configs = readFileSync(join(bds_dir_bedrock, "server.properties"), "utf8");
if (existsSync(join(bds_dir_bedrock, "permissions.json"))) permissions = readFileSync(join(bds_dir_bedrock, "permissions.json"), "utf8");
if (existsSync(join(bds_dir_bedrock, "whitelist.json"))) whitelist = readFileSync(join(bds_dir_bedrock, "whitelist.json"), "utf8");
// Download and Add to Adm_Zip
const zip = new AdmZip(Buffer.from((await (await fetch(url)).arrayBuffer())))
console.log("Download Sucess")
zip.extractAllTo(bds_dir_bedrock, true)
console.log("Extract Sucess")
if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs);
if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions)
if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist)
UpdateServerVersion(version)
if (typeof callback === "function") await callback(undefined, true);
return true
}
} else throw Error("Bedrock Not suported")
}
// java Installer Script
else if (CurrentPlatform === "java") {
if (valid_platform.java === true){
if (version === "latest") version = Servers.latest.java
if (version === ServerVersion.java) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
return true
} else {
url = Servers.java[version].url
console.log(`Server data publish: ${Servers.java[version].data}`)
writeFileSync(join(bds_dir_java, "MinecraftServerJava.jar"), Buffer.from((await (await fetch(url)).arrayBuffer())), "binary")
console.log("Success when downloading and saving Minecraft Server java");
UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true);
return true
}
} else throw Error("Java is not supported or required software is not installed")
}
// Pocketmine-MP Installer Script
else if (CurrentPlatform === "pocketmine") {
if (valid_platform.pocketmine === true) {
if (version === "latest") version = Servers.latest.pocketmine
if (version === ServerVersion.pocketmine) {
console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true);
return true
} else {
const PocketMineJson = Servers.pocketmine[version]
console.log(`Server data publish: ${PocketMineJson.data}`);
writeFileSync(join(bds_dir_pocketmine, "PocketMine-MP.phar"), Buffer.from((await (await fetch(PocketMineJson.url)).arrayBuffer())), "binary")
console.log("Success downloading and saving PocketMine-MP php");
await php_download();
// Update server Version
UpdateServerVersion(version)
// Callback
if (typeof callback === "function") await callback(undefined, true);
return true
}
} else throw Error("Pocketmine not suported")
}
// JSPrismarine
else if (CurrentPlatform === "jsprismarine") {
if (valid_platform.jsprismarine === true) {
console.log("Downloading the JSPrismarine repository.");
const commit_sha = GitClone("https://github.com/JSPrismarine/JSPrismarine.git", bds_dir_jsprismarine, 1);
for (let command of ["npm install", "npx -y lerna bootstrap", "npm run build"]) console.log(execSync(command, {cwd: bds_dir_jsprismarine}).toString("ascii"));
console.log(commit_sha);
UpdateServerVersion(commit_sha, "jsprismarine")
if (typeof callback === "function") await callback(undefined, true);
return true
} else throw Error("jsprismarine not suported")
}
// dragonfly
else if (CurrentPlatform === "dragonfly") {
throw "Bds maneger Config file error";
}
// Unidentified platform
else throw Error("Bds maneger Config file error")
} catch (err) {
if (typeof callback === "function") await callback(err, false);
return err;
}
}

View File

@ -56,7 +56,6 @@ function Detect(){
if (/MinecraftServerJava.jar/.test(check.command)) return true;
if (/bedrock_server/.test(check.command)) return true;
if (/PocketMine-MP.phar/.test(check.command)) return true;
if (/packages\/server\/dist\/Server.js/.test(check.command)) return true;
}
return false
}
@ -77,10 +76,6 @@ function Kill(){
console.log("Killing Pocketmine-MP");
killWithPid(check.pid);
}
if (/packages\/server\/dist\/Server.js/.test(check.command)) {
console.log("Killing JSPrismarine");
killWithPid(check.pid)
}
}
return true
}

View File

@ -73,7 +73,6 @@ app.get("/info", ({ res }) => {
const config = bds.get_config();
var info = {
server: {
platform: GetPlatform(),
world_name: config.world,
running: bds.detect(),
port: config.portv4,
@ -85,12 +84,13 @@ app.get("/info", ({ res }) => {
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"),
QEMU_STATIC: commandExist("qemu-x86_64-static")
},
bds_maneger_core: {
platform: GetPlatform(),
version: bds.package_json.version,
server_versions: GetServerVersion(),
}

View File

@ -5,6 +5,7 @@ const bds = require("../../../index");
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) => {
@ -35,13 +36,17 @@ app.get("/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => {
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.command(`ban ${PLAYER}`)});
else if (TYPE === "kick") res.json({ok: bds.command(`kick ${PLAYER} ${text}`)});
else if (TYPE === "op") res.json({ok: bds.command(`op ${PLAYER}`)});
else if (TYPE === "deop") res.json({ok: bds.command(`deop ${PLAYER}`)});
else res.sendStatus(422)
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