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 apt update
# Install Necessary Packages # 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 # 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) 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 mkdir /tmp/Node
tar -xJf /tmp/node.tar.xz -C /tmp/Node tar -xJf /tmp/node.tar.xz -C /tmp/Node
rm -rf /tmp/node.tar.xz 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 # Update npm
npm -g install npm@$(curl -sL https://api.github.com/repos/npm/cli/releases/latest | grep tag_name | cut -d '"' -f 4) 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 # Install Dependencies to diferent architectures
if ! [ "$(uname -m)" == "x86_64" ];then if ! [ "$(uname -m)" == "x86_64" ];then
mkdir -p /lib64 mkdir -p /lib64
@ -39,16 +39,17 @@ if ! [ "$(uname -m)" == "x86_64" ];then
fi fi
# Install openjdk # Install openjdk
case "$(uname -m)" in case "$(apt search openjdk)" in
x86_64 | aarch64 ) apt install -y openjdk-17*;; *openjdk-17* ) apt install -y openjdk-17*;;
* ) apt install -y openjdk-11*;; *openjdk-11* ) apt install -y openjdk-11*;;
* ) echo "No openjdk version found, skipping";;
esac esac
# Setup non root user # Setup non root user
useradd -m -p "$(perl -e 'print crypt($ARGV[0], "password")' "LucaA1113ba21")" "thebds" useradd -m -p "$(perl -e 'print crypt($ARGV[0], "password")' "LucaA1113ba21")" "thebds"
addgroup thebds sudo addgroup thebds sudo
addgroup thebds root addgroup thebds root
usermod --shell /bin/bash thebds; usermod --shell /usr/bin/zsh thebds;
echo "thebds ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers echo "thebds ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
# Remove Unnecessary Packages # Remove Unnecessary Packages

View File

@ -50,15 +50,14 @@ if (options.system || options.S) {
} }
// nexe options // 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 = {}
const nexeCopiler = {
name: "Bds Maneger Core",
build: true,
// loglevel: "verbose",
input: resolve(__dirname, "bds_maneger.js"),
output: fileout,
resources: files,
}
if (options.v || options.verbose) nexeCopiler.loglevel = "verbose" if (options.v || options.verbose) nexeCopiler.loglevel = "verbose"
// Build Binarie // 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 ()=>{ (async ()=>{
try { try {
const bds = require("../../index"); const bds = require("../../index");
await bds.download("latest", true) await bds.download("latest", true);
console.log("Date:", await bds.BdsDate());
console.log("Api:", await bds.api()); console.log("Api:", await bds.api());
console.log("Backup:", await bds.backup()); console.log("Backup:", await bds.backup());
console.log("Detect Server:", await bds.detect()); 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: push:
branches: branches:
- main - main
paths-ignore:
- 'README.md' env:
- '.github/*/**' DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7
- 'package-lock.json'
- '.devcontainer/**'
jobs: jobs:
npm: npm:
@ -20,16 +18,11 @@ jobs:
with: with:
node-version: 16.x node-version: 16.x
registry-url: https://registry.npmjs.org/ registry-url: https://registry.npmjs.org/
- name: Edit Version - name: Edit Version
run: | env:
id_run1=$(echo ${{ github.run_id }} |cut -b 1-2) RunID: ${{ github.run_id }}
id_run2=$(echo ${{ github.run_id }} |cut -b 3-6) run: node .github/ChangeVersion.js
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
- name: Install Packages - name: Install Packages
run: npm install run: npm install
@ -37,9 +30,10 @@ jobs:
- name: NPM Publish - name: NPM Publish
run: npm publish --tag dev run: npm publish --tag dev
env: env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }} NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}"
docker: docker_core:
needs: [npm]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Set up QEMU - name: Set up QEMU
@ -63,5 +57,35 @@ jobs:
with: with:
push: true push: true
target: bdscore target: bdscore
tags: bdsmaneger/core:nightly tags: bdsmaneger/core:main
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:main
bdsmaneger/node_image:main
platforms: ${{ env.DOCKER_ARCH }}

View File

@ -1,5 +1,5 @@
name: Test - The Bds Maneger Core name: Test - The Bds Maneger Core
on: [push, pull_request] on: [pull_request]
jobs: jobs:
Test: Test:
@ -9,10 +9,38 @@ jobs:
node-version: [14.x, 15.x, 16.x] node-version: [14.x, 15.x, 16.x]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2.4.0 uses: actions/setup-node@v2.4.0
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm install -d --no-save - name: Edit Version
- run: npm test 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**
- V** - V**
env:
DOCKER_ARCH: linux/amd64,linux/arm64,linux/arm/v7
jobs: jobs:
npm: npm:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ github.actor }} == ${{ github.repository_owner }}
steps: steps:
- uses: actions/checkout@master - uses: actions/checkout@master
- uses: actions/setup-node@v2.4.0 - uses: actions/setup-node@v2.4.0
@ -21,9 +25,10 @@ jobs:
- name: Publish - name: Publish
run: npm publish run: npm publish
env: env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ORG_TOKEN }} NODE_AUTH_TOKEN: "${{ secrets.NPM_ORG_TOKEN }}"
docker: docker_core:
needs: [npm]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Set up QEMU - name: Set up QEMU
@ -48,4 +53,36 @@ jobs:
push: true push: true
target: bdscore target: bdscore
tags: bdsmaneger/core:latest 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/ node_modules/
*-Test/
*teste/
debug.log
Bds_Maneger Bds_Maneger
.dccache .dccache
docs/ docs/
run.log
build.log # Bds Maneger Core Binaries
Docker.js.log
Docker.js
bds_maneger bds_maneger
BdsManager-bin* BdsManager-bin*
Bds-Maneger-Core Bds-Maneger-Core
# Docker Build
Docker.exe
# Bin Ignores
bin/*
!bin/bds_maneger.js
!bin/telegram_bot.js
# ** # **
.husky .husky
Servers Servers

View File

@ -1,5 +1,5 @@
terminal: terminal:
image: bdsmaneger/node_image:latest image: bdsmaneger/core:latest
services: services:
- docker:dind - docker:dind
before_script: 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 image: ubuntu:latest
only:
- v*
- V*
variables: variables:
DOCKER_TLS_CERTDIR: "" DOCKER_TLS_CERTDIR: ""
DOCKER_DRIVER: overlay2 DOCKER_DRIVER: overlay2
@ -18,6 +15,5 @@ Docker_Stable:
docker run --privileged --rm multiarch/qemu-user-static --reset -p yes docker run --privileged --rm multiarch/qemu-user-static --reset -p yes
docker buildx create --name multiarch --driver docker-container --use docker buildx create --name multiarch --driver docker-container --use
docker buildx inspect --bootstrap docker buildx inspect --bootstrap
docker login --username="$DOCKER_USER" --password="$DOCKER_TOKEN" &> /dev/null
script: 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/ # Log
.docker* *.log
.github/
.devconatiner/ # test files
.vscode/ *.test
node_modules/ *test*.js*
*-Test/ test/
*teste/ Test/
debug.log
Bds_Maneger # Git
.dccache git*
run.log .git*
build.log
Docker.js.log # Docker
Docker.js .dockerignore
bds_maneger Docker*
BdsManager-bin*

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), server = (argv.p || argv.platform),
version = (argv.v || argv.version), version = (argv.v || argv.version),
SystemCheck = (argv.S || argv.system_info), 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), start = (argv.s || argv.server_version),
help = (argv.h || argv.help), help = (argv.h || argv.help),
kill = (argv.k || argv.kill); 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"); console.log("Send a \"@stop\" command to stop the server and exit\nUse CTRL + C to force exit\n");
// Start Server // Start Server
const bds_server = bds.start(); const bds_server = bds.start();
bds_server.log(echo) bds_server.log(data => process.stdout.write(data));
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.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 // CLI Commands
const rl = readline.createInterface({input: process.stdin,output: process.stdout}); const rl = readline.createInterface({input: process.stdin,output: process.stdout});
@ -89,7 +93,7 @@ if (help) {
" -s --start Start Server", " -s --start Start Server",
" -k --kill Detect and kill bds servers", " -k --kill Detect and kill bds servers",
" -p --platform Select server platform", " -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", " --interactive Install the server interactively",
" -S --system_info System info and test", " -S --system_info System info and test",
" -h --help Print this list and exit.", " -h --help Print this list and exit.",
@ -154,22 +158,31 @@ if (SystemCheck) {
if (bds_version){ if (bds_version){
try { try {
if (argv.interactive) { 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) const Version = Object.getOwnPropertyNames(LoadVersion)
// List Version
for (let version in Version) console.log(`${version}: ${GetPlatform()} version ${Version[version]}`); // deepscan-disable-line FORIN_ARRAY const StartQuestion = (Readline) => {
// deepcode ignore MissingClose: <please specify a reason of ignoring this> Readline.question("Select a version to download: ", input => {
const DownloadOptions = readline.createInterface({input: process.stdin,output: process.stdout}); if (Version[parseInt(input) - 1]) {
console.log("\nSelect Option"); Readline.close();
DownloadOptions.on("line", (input) => { download(Version[parseInt(input) - 1], true, function(){
download(Version[parseInt(input)], true, function(){ if (start) return StartServer();
console.log("Installation was successful, so start the server with the -s option"); console.log("Installation was successful, so start the server with the -s option");
if (start) StartServer(); process.exit(0);
else 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(){ else bds.download(bds_version, true, function(){
if (start) StartServer(); if (start) StartServer();
}) })
@ -178,8 +191,4 @@ if (bds_version){
} }
// Start server // 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(); 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"); 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") const bds_core_package = resolve(__dirname, "package.json")
module.exports.package_path = bds_core_package module.exports.package_path = bds_core_package
module.exports.package_json = require("./package.json"); module.exports.package_json = require("./package.json");
@ -66,10 +49,11 @@ module.exports.telegram_token_save = UpdateTelegramToken
*/ */
module.exports.api = require("./src/rest/api"); 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"); const bds_token_path = path.join(bds_dir, "bds_tokens.json");
if (!(fs.existsSync(bds_token_path))) fs.writeFileSync(bds_token_path, "[]"); let tokens = []
const tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8")); if (fs.existsSync(bds_token_path)) tokens = JSON.parse(fs.readFileSync(bds_token_path, "utf8"));
// Get UUID // Get UUID
const getBdsUUId = randomUUID().split("-"); const getBdsUUId = randomUUID().split("-");
@ -79,7 +63,7 @@ function token_register() {
tokens.push({ tokens.push({
token: bdsuid, token: bdsuid,
date: new Date(), date: new Date(),
scopers: ["admin"] scopers: Admin_Scoper
}); });
fs.writeFileSync(bds_token_path, JSON.stringify(tokens, null, 4), "utf8"); fs.writeFileSync(bds_token_path, JSON.stringify(tokens, null, 4), "utf8");
console.log(`Bds Maneger API REST token: "${bdsuid}"`); console.log(`Bds Maneger API REST token: "${bdsuid}"`);
@ -93,6 +77,13 @@ function token_register() {
*/ */
module.exports.token_register = 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 * 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 download = require("./src/BdsServersDownload");
const { start, stop, BdsCommand, CronBackups } = require("./src/BdsManegerServer") 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 * sending commands more simply to the server
* *
@ -165,7 +151,7 @@ module.exports.kill = Kill
* *
* java: download("1.16.5") * 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 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 { existsSync, writeFileSync, mkdirSync, readFileSync } = require("fs");
const { homedir } = require("os"); const { homedir } = require("os");
const { valid_platform } = require("./BdsSystemInfo"); const { valid_platform } = require("./BdsSystemInfo");
@ -17,7 +17,7 @@ var default_platformConfig;
if (valid_platform["bedrock"]) default_platformConfig = "bedrock"; if (valid_platform["bedrock"]) default_platformConfig = "bedrock";
else if (valid_platform["java"]) default_platformConfig = "java"; else if (valid_platform["java"]) default_platformConfig = "java";
else if (valid_platform["pocketmine"]) default_platformConfig = "pocketmine"; 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 // Config Base to Bds Maneger Core and others Projects
var Config = { var Config = {
@ -46,6 +46,7 @@ var Config = {
java: null, java: null,
pocketmine: null, pocketmine: null,
jsprismarine: null, jsprismarine: null,
spigot: null,
}, },
Settings: { Settings: {
java: { java: {
@ -75,6 +76,7 @@ var Config = {
java: true, java: true,
pocketmine: true, pocketmine: true,
jsprismarine: true, jsprismarine: true,
spigot: true,
}, },
{ {
username: "Alex", username: "Alex",
@ -83,6 +85,7 @@ var Config = {
java: true, java: true,
pocketmine: true, pocketmine: true,
jsprismarine: true, jsprismarine: true,
spigot: true,
}, },
{ {
username: "steve", username: "steve",
@ -91,6 +94,7 @@ var Config = {
java: true, java: true,
pocketmine: true, pocketmine: true,
jsprismarine: true, jsprismarine: true,
spigot: true,
}, },
{ {
username: "alex", username: "alex",
@ -99,6 +103,7 @@ var Config = {
java: true, java: true,
pocketmine: true, pocketmine: true,
jsprismarine: true, jsprismarine: true,
spigot: true,
} }
], ],
telegram: { telegram: {
@ -127,18 +132,15 @@ const ServersPaths = {
java: join(Config.paths.servers, "Java"), java: join(Config.paths.servers, "Java"),
pocketmine: join(Config.paths.servers, "Pocketmine-MP"), pocketmine: join(Config.paths.servers, "Pocketmine-MP"),
jsprismarine: join(Config.paths.servers, "JSPrismarine"), 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)) { Object.getOwnPropertyNames(ServersPaths).map(Servers => ServersPaths[Servers]).forEach(Servers => {
if (!(existsSync(ServersPaths[Servers]))) { if (!(existsSync(Servers))) {
console.log(`Creating the ${Servers} Folder`); console.log(`Creating the ${basename(Servers)} Folder`);
mkdirSync(ServersPaths[Servers], {recursive: true}) mkdirSync(Servers, {recursive: true})
}
}
// return settings by function
function GetJsonConfig(){
return Config
} }
});
// get the path from the settings and return by function // get the path from the settings and return by function
function GetPaths(path = null){ function GetPaths(path = null){
@ -155,11 +157,6 @@ function GetServerPaths(path = null){
return ServersPaths[path] 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 // 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){ function UpdateServerVersion(version = null, platform = Config.server.platform){
if (Config.server.versions[platform] || Config.server.versions[platform] === null) { 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") } 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 // Update the entire Bds Manager Core platform
function UpdatePlatform(platform = Config.server.platform){ function UpdatePlatform(platform = Config.server.platform){
platform = platform.toLocaleLowerCase(); platform = platform.toLocaleLowerCase();
@ -196,6 +178,9 @@ function UpdatePlatform(platform = Config.server.platform){
} else if (/pocketmine/.test(platform)) { } else if (/pocketmine/.test(platform)) {
Config.server.platform = "pocketmine"; Config.server.platform = "pocketmine";
SaveConfig() SaveConfig()
} else if (/spigot/.test(platform)) {
Config.server.platform = "spigot";
SaveConfig()
} else if (/jsprismarine/.test(platform)) { } else if (/jsprismarine/.test(platform)) {
Config.server.platform = "jsprismarine"; Config.server.platform = "jsprismarine";
SaveConfig() SaveConfig()
@ -203,11 +188,6 @@ function UpdatePlatform(platform = Config.server.platform){
return platform return platform
} }
// Return to platform
function GetPlatform(){
return Config.server.platform
}
// Telegram // Telegram
function UpdateTelegramToken(token = null){ function UpdateTelegramToken(token = null){
if (!(token)) throw new Error("Telegram Token invalid") if (!(token)) throw new Error("Telegram Token invalid")
@ -216,18 +196,20 @@ function UpdateTelegramToken(token = null){
return token return token
} }
function GetTelegramToken(){ const GetJsonConfig = () => Config;
return Config.telegram.token
}
function GetTelegramAdmins(){ const GetCronBackup = () => Config.server.BackupCron;
return Config.telegram.admins 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. // Get a temporary host to connect to the server.
function GetTempHost(){ const GetTempHost = () => Config.bds.enable_tmp_host
return Config.bds.enable_tmp_host
}
// Enable and/or disable pick up temporary host. // Enable and/or disable pick up temporary host.
function UpdateTempHost(enable = false){ function UpdateTempHost(enable = false){
@ -236,7 +218,8 @@ function UpdateTempHost(enable = false){
// Save // Save
Config.bds.enable_tmp_host = enable Config.bds.enable_tmp_host = enable
return SaveConfig(); SaveConfig();
return true;
} }
// Get the server settings // Get the server settings

View File

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

View File

@ -1,4 +1,3 @@
const bds = require("../index")
const { join, resolve } = require("path"); const { join, resolve } = require("path");
const { readdirSync, existsSync, readFileSync, statSync } = require("fs") const { readdirSync, existsSync, readFileSync, statSync } = require("fs")
const AdmZip = require("adm-zip"); const AdmZip = require("adm-zip");
@ -14,7 +13,8 @@ function Backup() {
pocketmine: GetServerPaths("pocketmine"), pocketmine: GetServerPaths("pocketmine"),
jsprismarine: GetServerPaths("jsprismarine") 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); const PathBackup = join(GetPaths("backups"), name);
// Bedrock // 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"); 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"); } else console.info("Skipping the pocketmine as it was not installed");
// JSPrismarine
// The Bds Maneger Core Backup // 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)); 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"); SetupCommands.cwd = GetServerPaths("pocketmine");
} }
// Minecraft Bedrock (JSPrismarine) // Show Error platform
else if (GetPlatform() === "jsprismarine") { else throw Error("Bds Config Error")
// 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 // Setup commands
const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, { const ServerExec = child_process.execFile(SetupCommands.command, SetupCommands.args, {
@ -99,8 +94,7 @@ function start() {
} }
// Log file // Log file
const LogFile = path.join(GetPaths("log"), `${GetPlatform()}_${new Date().toString()}_Bds_log.log`);
const LogFile = path.join(GetPaths("log"), `${bds.date()}_${GetPlatform()}_Bds_log.log`);
const LatestLog_Path = path.join(GetPaths("log"), "latest.log"); const LatestLog_Path = path.join(GetPaths("log"), "latest.log");
const LogSaveFunction = data => { const LogSaveFunction = data => {
fs.appendFileSync(LogFile, data); fs.appendFileSync(LogFile, data);
@ -121,15 +115,8 @@ function start() {
global.bds_log_string = "" 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}); 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 (){}) {
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) => { return new Promise((resolve) => {
ServerExec.stdin.write(`${command}\n`); ServerExec.stdin.write(`${command}\n`);
if (typeof callback === "function") { if (typeof callback === "function") {
@ -143,62 +130,63 @@ function start() {
}, 2500); }, 2500);
} }
}); });
}, };
log: function (logCallback = function(data = ""){data.split("\n").filter(d=>{return (d !== "")}).forEach(l=>console.log(l))}){ const log = function (logCallback = data => process.stdout.write(data)){
if (typeof logCallback !== "function") { if (typeof logCallback !== "function") throw new Error("Log Callback is not a 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.stdout.on("data", data => logCallback(data));
ServerExec.stderr.on("data", data => logCallback(data)); ServerExec.stderr.on("data", data => logCallback(data));
}, };
exit: function (exitCallback = process.exit){if ( const exit = function (exitCallback = process.exit){if (
typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code)); typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code));
}, };
on: function(action = String(), callback = Function) { const on = function(action = String, callback = Function) {
if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect"); if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect");
// Functions // Functions
const data = data => Player_Json(data, function (array_status){ const data = data => Player_Json(data, function (array_status){
for (let _player of array_status) { array_status.filter(On => {if ("all" === action || On.Action === action) return true; else return false;}).forEach(_player => callback(_player))
if (_player.Action === action) callback(_player);
if (action === "all") callback(_player);
}
}); });
ServerExec.stdout.on("data", data); ServerExec.stdout.on("data", data);
ServerExec.stderr.on("data", data); ServerExec.stderr.on("data", data);
}, };
op: function (player = "Steve") { 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); let command = BdsInfo.Servers[GetPlatform()].op.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n"); ServerExec.stdin.write(command+"\n");
return command; return command;
}, };
deop: function (player = "Steve") { const deop = function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player); let command = BdsInfo.Servers[GetPlatform()].deop.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n"); ServerExec.stdin.write(command+"\n");
return command; return command;
}, };
ban: function (player = "Steve") { const ban = function (player = "Steve") {
let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player); let command = BdsInfo.Servers[GetPlatform()].ban.replace("{{Player}}", player);
ServerExec.stdin.write(command+"\n"); ServerExec.stdin.write(command+"\n");
return command; return command;
}, };
kick: function (player = "Steve", text = "you got kicked") { const kick = function (player = "Steve", text = "you got kicked") {
let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text); let command = BdsInfo.Servers[GetPlatform()].kick.replace("{{Player}}", player).replace("{{Text}}", text);
ServerExec.stdin.write(command+"\n"); ServerExec.stdin.write(command+"\n");
return command; return command;
}, };
tp: function (player = "Steve", cord = {x: 0, y: 128, z: 0}) { const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) {
let command = BdsInfo.Servers[GetPlatform()].tp.replace("{{Player}}", player); 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.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("{{Y}}", cord.y); else command = command.replace("{{Y}}", 128);
if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0); if (cord.y) command = command.replace("{{Z}}", cord.y); else command = command.replace("{{Z}}", 0);
ServerExec.stdin.write(command+"\n"); ServerExec.stdin.write(command+"\n");
return command; return command;
}, };
say, const say = (text = "") => ServerExec.stdin.write(BdsInfo.Servers.bedrock.say.replace("{{Text}}", text));
const returnFuntion = {
uuid: randomUUID(),
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; global.BdsExecs[returnFuntion.uuid] = returnFuntion;
return returnFuntion; return returnFuntion;
} }
@ -348,6 +336,7 @@ module.exports = {
start, start,
BdsCommand, BdsCommand,
stop, stop,
GetSessions,
CronBackups: CurrentBackups, CronBackups: CurrentBackups,
Player_Search, Player_Search,
} }

View File

@ -1,64 +1,26 @@
var AdmZip = require("adm-zip");
const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = require("fs"); const { writeFileSync, existsSync, readFileSync, readdirSync, rmSync } = require("fs");
const { join, resolve, basename } = require("path"); const { join, resolve, basename } = require("path");
const bds = require("../index") var AdmZip = require("adm-zip");
const { valid_platform } = require("../lib/BdsSystemInfo"); const { valid_platform } = require("../lib/BdsSystemInfo");
const { GetServerPaths, GetServerVersion, UpdateServerVersion, GetPlatform } = require("../lib/BdsSettings"); 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 = require("../index");
async function php_download() { const { execSync } = require("child_process");
const bds_dir_pocketmine = GetServerPaths("pocketmine"),
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");
// Check Php Binary
let urlPHPBin = PHPBin[process.platform]
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.");
rmSync(phpFolder, { recursive: true });
}
console.log(`Downloading ${urlPHPBin}`);
const ZipBuffer = Buffer.from((await (await fetch(urlPHPBin)).arrayBuffer()));
console.log(`${basename(urlPHPBin)} downloaded`);
console.log(`Extracting ${basename(urlPHPBin)}`);
const zipExtractBin = new AdmZip(ZipBuffer);
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
console.log("Successfully extracting the binaries")
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf-8");
if (!(existsSync(phpExtensiosnsDir))) return true;
const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => {
if (!(FileFolder.includes("debug-zts"))) return false;
return resolve(phpExtensiosnsDir, FileFolder);
}).filter(a=>a);
if (phpConfigInit.includes("extension_dir")) console.log("Skipping php.ini configuration");
else {
phpConfigInit = (`extension_dir="${phpExtensiosns.join()}"\n${phpConfigInit}`);
writeFileSync(join(phpFolder, "php7", "bin", "php.ini"), phpConfigInit);
}
return true;
}
module.exports = async function (version, force_install, callback) { module.exports = async function (version, force_install, callback) {
return new Promise(async (promise_resolve, promise_reject) => {
try { try {
// Server Paths
const bds_dir_bedrock = GetServerPaths("bedrock"), const bds_dir_bedrock = GetServerPaths("bedrock"),
bds_dir_java = GetServerPaths("java"), bds_dir_java = GetServerPaths("java"),
bds_dir_pocketmine = GetServerPaths("pocketmine"), bds_dir_pocketmine = GetServerPaths("pocketmine"),
bds_dir_jsprismarine = GetServerPaths("jsprismarine"); bds_dir_spigot = GetServerPaths("spigot"),
bds_dir_dragonfly = GetServerPaths("dragonfly");
// JSON Configs and others
const Servers = (await (await fetch(Extra.download.servers)).json()); const Servers = (await (await fetch(Extra.download.servers)).json());
const ServerVersion = GetServerVersion() const ServerVersion = GetServerVersion();
const CurrentPlatform = GetPlatform() const CurrentPlatform = GetPlatform();
if (force_install === true) { if (force_install === true) {
ServerVersion.java = "latest"; ServerVersion.java = "latest";
ServerVersion.bedrock = "latest" ServerVersion.bedrock = "latest"
@ -72,10 +34,10 @@ module.exports = async function (version, force_install, callback) {
if (CurrentPlatform === "bedrock") { if (CurrentPlatform === "bedrock") {
if (valid_platform.bedrock === true){ if (valid_platform.bedrock === true){
if (version === "latest") version = Servers.latest.bedrock if (version === "latest") version = Servers.latest.bedrock
if (ServerVersion.bedrock === version) { if (!(force_install === true) && ServerVersion.bedrock === version) {
console.warn("Jumping, installed version") console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true);
} else { } else {
if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`) if (Servers.bedrock[version].data) console.log(`Server data publish: ${Servers.bedrock[version].data}`)
url = Servers.bedrock[version][bds.arch][process.platform] url = Servers.bedrock[version][bds.arch][process.platform]
@ -93,20 +55,21 @@ module.exports = async function (version, force_install, callback) {
if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs); if (server_configs) writeFileSync(join(bds_dir_bedrock, "server.properties"), server_configs);
if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions) if (permissions) writeFileSync(join(bds_dir_bedrock, "permissions.json"), permissions)
if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist) if (whitelist) writeFileSync(join(bds_dir_bedrock, "whitelist.json"), whitelist)
UpdateServerVersion(version) UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true);
} }
} else throw Error("Bedrock Not suported") } else throw Error("Bedrock Not suported")
} }
// java Installer Script
// Java
else if (CurrentPlatform === "java") { else if (CurrentPlatform === "java") {
if (valid_platform.java === true){ if (valid_platform.java === true){
if (version === "latest") version = Servers.latest.java if (version === "latest") version = Servers.latest.java
if (version === ServerVersion.java) { if (!(force_install === true) && version === ServerVersion.java) {
console.warn("Jumping, installed version") console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true)
} else { } else {
url = Servers.java[version].url url = Servers.java[version].url
console.log(`Server data publish: ${Servers.java[version].data}`) console.log(`Server data publish: ${Servers.java[version].data}`)
@ -115,18 +78,19 @@ module.exports = async function (version, force_install, callback) {
console.log("Success when downloading and saving Minecraft Server java"); console.log("Success when downloading and saving Minecraft Server java");
UpdateServerVersion(version); UpdateServerVersion(version);
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true);
} }
} else throw Error("Java is not supported or required software is not installed") } else throw Error("Java is not supported or required software is not installed")
} }
// Pocketmine-MP Installer Script
// Pocketmine-MP
else if (CurrentPlatform === "pocketmine") { else if (CurrentPlatform === "pocketmine") {
if (valid_platform.pocketmine === true) { if (valid_platform.pocketmine === true) {
if (version === "latest") version = Servers.latest.pocketmine if (version === "latest") version = Servers.latest.pocketmine
if (version === ServerVersion.pocketmine) { if (!(force_install === true) && version === ServerVersion.pocketmine) {
console.warn("Jumping, installed version") console.warn("Jumping, installed version")
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true)
} else { } else {
const PocketMineJson = Servers.pocketmine[version] const PocketMineJson = Servers.pocketmine[version]
console.log(`Server data publish: ${PocketMineJson.data}`); console.log(`Server data publish: ${PocketMineJson.data}`);
@ -140,32 +104,89 @@ module.exports = async function (version, force_install, callback) {
UpdateServerVersion(version) UpdateServerVersion(version)
// Callback // Callback
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true);
} }
} else throw Error("Pocketmine not suported") } else throw Error("Pocketmine not suported")
} }
// JSPrismarine // Spigot
else if (CurrentPlatform === "jsprismarine") { else if (CurrentPlatform === "spigot") {
if (valid_platform.jsprismarine === true) { if (valid_platform.java) {
console.log("Downloading the JSPrismarine repository."); if (version === "latest") version = Servers.latest.spigot;
const commit_sha = GitClone("https://github.com/JSPrismarine/JSPrismarine.git", bds_dir_jsprismarine, 1); if (!(force_install === true) && version === ServerVersion.spigot) {
for (let command of ["npm install", "npx -y lerna bootstrap", "npm run build"]) console.log(execSync(command, {cwd: bds_dir_jsprismarine}).toString("ascii")); console.warn("Jumping, installed version")
console.log(commit_sha);
UpdateServerVersion(commit_sha, "jsprismarine")
if (typeof callback === "function") await callback(undefined, true); if (typeof callback === "function") await callback(undefined, true);
return true promise_resolve(true)
} else throw Error("jsprismarine not suported") } 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 // dragonfly
else if (CurrentPlatform === "dragonfly") { else if (CurrentPlatform === "dragonfly") {
throw "Bds maneger Config file error"; 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 // Unidentified platform
else throw Error("Bds maneger Config file error") else throw Error("Bds maneger Config file error")
} catch (err) { } catch (err) {
if (typeof callback === "function") await callback(err, false); if (typeof callback === "function") await callback(err, false);
return err; return promise_reject(err);
} }
});
}
async function php_download() {
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");
// Check Php Binary
let urlPHPBin = PHPBin[process.platform]
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.");
rmSync(phpFolder, { recursive: true });
}
console.log(`Downloading ${urlPHPBin}`);
const ZipBuffer = Buffer.from((await (await fetch(urlPHPBin)).arrayBuffer()));
console.log(`${basename(urlPHPBin)} downloaded`);
console.log(`Extracting ${basename(urlPHPBin)}`);
const zipExtractBin = new AdmZip(ZipBuffer);
zipExtractBin.extractAllTo(bds_dir_pocketmine, false)
console.log("Successfully extracting the binaries")
let phpConfigInit = readFileSync(join(phpFolder, "php7", "bin", "php.ini"), "utf8");
if (!(existsSync(phpExtensiosnsDir))) return true;
const phpExtensiosns = readdirSync(phpExtensiosnsDir).map(FileFolder => {
if (!(FileFolder.includes("debug-zts"))) return false;
return resolve(phpExtensiosnsDir, FileFolder);
}).filter(a=>a);
if (phpConfigInit.includes("extension_dir")) console.log("Skipping php.ini configuration");
else {
phpConfigInit = (`extension_dir="${phpExtensiosns.join()}"\n${phpConfigInit}`);
writeFileSync(join(phpFolder, "php7", "bin", "php.ini"), phpConfigInit);
}
return true;
} }

View File

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

View File

@ -73,7 +73,6 @@ app.get("/info", ({ res }) => {
const config = bds.get_config(); const config = bds.get_config();
var info = { var info = {
server: { server: {
platform: GetPlatform(),
world_name: config.world, world_name: config.world,
running: bds.detect(), running: bds.detect(),
port: config.portv4, port: config.portv4,
@ -85,12 +84,13 @@ app.get("/info", ({ res }) => {
arch: bds.arch, arch: bds.arch,
system: process.platform, system: process.platform,
Kernel: GetKernel(), Kernel: GetKernel(),
QEMU_STATIC: commandExist("qemu-x86_64-static") || commandExist("qemu-x86_64"),
IS_CLI: JSON.parse(process.env.IS_BDS_CLI || false), IS_CLI: JSON.parse(process.env.IS_BDS_CLI || false),
IS_DOCKER: JSON.parse(process.env.BDS_DOCKER_IMAGE || false), IS_DOCKER: JSON.parse(process.env.BDS_DOCKER_IMAGE || false),
IS_NPX: (process.env.npm_lifecycle_event === "npx"), IS_NPX: (process.env.npm_lifecycle_event === "npx"),
QEMU_STATIC: commandExist("qemu-x86_64-static")
}, },
bds_maneger_core: { bds_maneger_core: {
platform: GetPlatform(),
version: bds.package_json.version, version: bds.package_json.version,
server_versions: GetServerVersion(), server_versions: GetServerVersion(),
} }

View File

@ -5,6 +5,7 @@ const bds = require("../../../index");
const { token_verify, CheckPlayer } = require("../../UsersAndtokenChecks"); const { token_verify, CheckPlayer } = require("../../UsersAndtokenChecks");
const { readFileSync } = require("fs"); const { readFileSync } = require("fs");
const docs = require("../../../BdsManegerInfo.json").docs; const docs = require("../../../BdsManegerInfo.json").docs;
const { GetSessions } = require("../../BdsManegerServer");
// Players info and maneger // Players info and maneger
app.get("/", (req, res) => { app.get("/", (req, res) => {
@ -35,13 +36,17 @@ app.get("/actions/:TYPE/:TOKEN/:PLAYER*", (req, res) => {
const { text } = req.query; const { text } = req.query;
// Pre Check // Pre Check
if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters"); if (!(token_verify(TOKEN) || CheckPlayer(PLAYER))) return res.status(401).send("Check your parameters");
const bds = GetSessions()
// Post Check // Post Check
if (TYPE === "ban") res.json({ok: bds.command(`ban ${PLAYER}`)}); if (TYPE === "ban") res.json({
else if (TYPE === "kick") res.json({ok: bds.command(`kick ${PLAYER} ${text}`)}); ok: bds.ban(PLAYER)
else if (TYPE === "op") res.json({ok: bds.command(`op ${PLAYER}`)}); }); else if (TYPE === "kick") res.json({
else if (TYPE === "deop") res.json({ok: bds.command(`deop ${PLAYER}`)}); ok: bds.kick(PLAYER, text)
else res.sendStatus(422) }); 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 // Actions Redirect