Update server platforms to v2 paths #465

Merged
Sirherobrine23 merged 4 commits from multi-server-installs into main 2022-09-27 23:29:33 +00:00
18 changed files with 244 additions and 285 deletions
Showing only changes of commit e4ec216583 - Show all commits

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@the-bds-maneger/core",
"version": "4.5.2",
"version": "4.5.3",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@the-bds-maneger/core",
"version": "4.5.2",
"version": "4.5.3",
"license": "GPL-3.0",
"dependencies": {
"@the-bds-maneger/server_versions": "^4.2.0",

View File

@@ -1,15 +1,14 @@
import * as path from "node:path";
import * as fsOld from "node:fs";
import * as fs from "node:fs/promises";
import path from "node:path";
import fsOld from "node:fs";
import fs from "node:fs/promises";
import admZip from "adm-zip";
import * as Proprieties from "./Proprieties";
import { promisify } from "node:util";
import { platformManeger } from "@the-bds-maneger/server_versions";
import admZip from "adm-zip";
import { execAsync } from "./childPromisses";
import { actions, actionConfig } from "./globalPlatfroms";
import { serverRoot, logRoot } from './pathControl';
import * as Proprieties from "./Proprieties";
import { saveFile } from "./httpRequest";
export const serverPath = path.join(serverRoot, "Bedrock");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
// RegExp
export const saveFileFolder = /^(worlds|server\.properties|config|((permissions|allowlist|valid_known_packs)\.json)|(development_.*_packs))$/;
@@ -17,7 +16,8 @@ export const portListen = /\[.*\]\s+(IPv[46])\s+supported,\s+port:\s+([0-9]+)/;
export const started = /\[.*\]\s+Server\s+started\./;
export const player = /\[.*\]\s+Player\s+((dis|)connected):\s+(.*),\s+xuid:\s+([0-9]+)/;
export async function installServer(version: string|boolean) {
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("bedrock", platformOptions);
const bedrockData = await platformManeger.bedrock.find(version);
const zip = new admZip(await saveFile(bedrockData.url[process.platform]));
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
@@ -67,7 +67,8 @@ const serverConfig: actionConfig[] = [
},
];
export async function startServer() {
export async function startServer(platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath, logsPath } = await pathControl("bedrock", platformOptions);
if (!fsOld.existsSync(serverPath)) throw new Error("Install server fist");
const args: string[] = [];
let command = path.join(serverPath, "bedrock_server");
@@ -83,13 +84,13 @@ export async function startServer() {
// execAsync(`echo "deb http://security.ubuntu.com/ubuntu focal-security main" | sudo tee /etc/apt/sources.list.d/focal-security.list && sudo apt update && sudo apt install libssl1.1`, {stdio: "inherit"});
// }
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_bedrock_${process.platform}_${process.arch}.stdout.log`);
return new actions({command, args, options: {cwd: serverPath, maxBuffer: Infinity, env: {LD_LIBRARY_PATH: process.platform === "win32"?undefined:serverPath}, logPath: {stdout: logFileOut}}}, serverConfig);
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.log`);
return new actions({
processConfig: {command, args, options: {cwd: serverPath, maxBuffer: Infinity, env: {LD_LIBRARY_PATH: process.platform === "win32"?undefined:serverPath}, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}
// File config
export const fileProperties = path.join(serverPath, "server.properties");
// Update file config
export type keyConfig = "serverName"|"gamemode"|"forceGamemode"|"difficulty"|"allowCheats"|"maxPlayers"|"onlineMode"|"allowList"|"serverPort"|"serverPortv6"|"viewDistance"|"tickDistance"|"playerIdleTimeout"|"maxThreads"|"levelName"|"levelSeed"|"defaultPlayerPermissionLevel"|"texturepackRequired"|"chatRestriction";
export async function updateConfig(key: "serverName", value: string): Promise<string>;
@@ -111,7 +112,9 @@ export async function updateConfig(key: "levelSeed", value?: string): Promise<st
export async function updateConfig(key: "defaultPlayerPermissionLevel", value: "visitor"|"member"|"operator"): Promise<string>;
export async function updateConfig(key: "texturepackRequired", value: boolean): Promise<string>;
export async function updateConfig(key: "chatRestriction", value: "None"|"Dropped"|"Disabled"): Promise<string>;
export async function updateConfig(key: keyConfig, value: string|number|boolean): Promise<string> {
export async function updateConfig(key: keyConfig, value: string|number|boolean, platformOptions: bdsPlatformOptions = {id: "default"}): Promise<string> {
const { serverPath } = await pathControl("bedrock", platformOptions);
const fileProperties = path.join(serverPath, "server.properties");
if (!fsOld.existsSync(fileProperties)) throw new Error("Install server fist!");
let fileConfig = await fs.readFile(fileProperties, "utf8");
if (key === "serverName") fileConfig = fileConfig.replace(/server-name=.*/, `server-name=${value}`);
@@ -200,7 +203,9 @@ type rawConfig = {
"emit-server-telemetry"?: boolean
}
export async function getConfig(): Promise<bedrockConfig> {
export async function getConfig(platformOptions: bdsPlatformOptions = {id: "default"}): Promise<bedrockConfig> {
const { serverPath } = await pathControl("bedrock", platformOptions);
const fileProperties = path.join(serverPath, "server.properties");
if (!fsOld.existsSync(fileProperties)) throw new Error("Install server fist");
const config = Proprieties.parse<rawConfig>(await fs.readFile(fileProperties, "utf8"));
const configBase: bedrockConfig = {};

View File

@@ -1,6 +1,5 @@
import type { ObjectEncodingOptions } from "node:fs";
import * as child_process from "node:child_process";
export const execFile = child_process.execFile;
export type ExecFileOptions = ObjectEncodingOptions & child_process.ExecFileOptions & {stdio?: "ignore"|"inherit"};
export function execFileAsync(command: string): Promise<{stdout: string, stderr: string}>;
@@ -15,7 +14,7 @@ export function execFileAsync(command: string, args?: ExecFileOptions|(string|nu
childOptions.maxBuffer = Infinity;
if (childOptions?.env) childOptions.env = {...process.env, ...childOptions.env};
return new Promise<{stdout: string, stderr: string}>((resolve, rejectExec) => {
const child = execFile(command, childArgs.map(String), childOptions, (err, out, err2) => {if (err) return rejectExec(err);resolve({stdout: out, stderr: err2});});
const child = child_process.execFile(command, childArgs.map(String), childOptions, (err, out, err2) => {if (err) return rejectExec(err);resolve({stdout: out, stderr: err2});});
if (options?.stdio === "inherit") {
child.stdout.on("data", data => process.stdout.write(data));
child.stderr.on("data", data => process.stderr.write(data));

View File

@@ -2,7 +2,7 @@ import net from "node:net";
import crypto from "node:crypto";
import fs from "node:fs/promises";
import tar from "tar";
import { bdsRoot } from "./pathControl";
import { bdsRoot } from "./platformPathManeger";
export type payload = {
httpVersion?: string,

View File

@@ -2,20 +2,13 @@ import fs from "node:fs";
import readline from "node:readline";
import child_process from "node:child_process";
import { EventEmitter } from "node:events";
import type {pluginManeger as globalPluginManeger} from "./plugin/main";
import type { pluginManeger } from "./plugin/plugin";
import type { script_hook } from "./plugin/hook";
export type playerClass = {[player: string]: {action: "connect"|"disconnect"|"unknown"; date: Date; history: Array<{action: "connect"|"disconnect"|"unknown"; date: Date}>}};
export type playerBase = {playerName: string, connectTime: Date, xuid?: string, action?: string};
/**
* @deprecated Please use playerAction now
*/
export type actionsPlayer = {
name: "playerConnect"|"playerDisconnect"|"playerUnknown",
callback: (data: string, done: (player: playerBase) => void) => void
}
export type newPlayerAction = {
name: "playerAction",
callback: (data: string, playerConnect: (player: playerBase) => void, playerDisconnect: (player: playerBase) => void, playerUnknown: (player: playerBase) => void) => void
};
@@ -44,7 +37,7 @@ export type actionTp = {
export type actionPlugin = {
name: "pluginManeger",
class: () => Promise<globalPluginManeger>
class: () => Promise<pluginManeger>
};
export type actionHooks = {
@@ -53,7 +46,7 @@ export type actionHooks = {
}
export type actionRun = actionsServerStop|actionTp;
export type actionCallback = actionsPlayer|newPlayerAction|actionsPort|actionsServerStarted|actionsServerStarted;
export type actionCallback = actionsPlayer|actionsPort|actionsServerStarted|actionsServerStarted;
export type actionConfig = actionCallback|actionRun|actionPlugin|actionHooks;
export declare interface actions {
@@ -62,6 +55,7 @@ export declare interface actions {
on(act: "serverStarted", fn: (data: serverStarted) => void): this;
on(act: "log_stderr", fn: (data: string) => void): this;
on(act: "log_stdout", fn: (data: string) => void): this;
on(act: "log", fn: (data: string) => void): this;
on(act: "exit", fn: (data: {code: number, signal: NodeJS.Signals}) => void): this;
once(act: "playerConnect"|"playerDisconnect"|"playerUnknown", fn: (data: playerBase) => void): this;
@@ -69,6 +63,7 @@ export declare interface actions {
once(act: "serverStarted", fn: (data: serverStarted) => void): this;
once(act: "log_stderr", fn: (data: string) => void): this;
once(act: "log_stdout", fn: (data: string) => void): this;
once(act: "log", fn: (data: string) => void): this;
once(act: "exit", fn: (data: {code: number, signal: NodeJS.Signals}) => void): this;
}
@@ -84,7 +79,7 @@ export class actions extends EventEmitter {
return this.#childProcess?.kill(signal);
}
public plugin?: globalPluginManeger;
public plugin?: pluginManeger;
public hooks?: script_hook;
public platform?: string;
@@ -114,16 +109,16 @@ export class actions extends EventEmitter {
}
public processConfig: actionCommandOption;
constructor(processConfig: actionCommandOption, config: actionConfig[]) {
constructor(platformConfig: {processConfig: actionCommandOption, hooks: actionConfig[]}) {
super({captureRejections: false});
if (!processConfig.args) processConfig.args = [];
if (!processConfig.options) processConfig.options = {};
processConfig.options.maxBuffer = Infinity;
this.processConfig = processConfig;
this.#childProcess = child_process.execFile(processConfig.command, processConfig.args, processConfig.options);
if (processConfig.options.logPath) {
this.#childProcess.stdout.pipe(fs.createWriteStream(processConfig.options.logPath.stdout));
if (processConfig.options.logPath.stderr) this.#childProcess.stderr.pipe(fs.createWriteStream(processConfig.options.logPath.stderr));
if (!platformConfig?.processConfig.args) platformConfig.processConfig.args = [];
if (!platformConfig?.processConfig.options) platformConfig.processConfig.options = {};
platformConfig.processConfig.options.maxBuffer = Infinity;
this.processConfig = platformConfig?.processConfig;
this.#childProcess = child_process.execFile(platformConfig?.processConfig.command, platformConfig?.processConfig.args, platformConfig?.processConfig.options);
if (platformConfig?.processConfig.options.logPath) {
this.#childProcess.stdout.pipe(fs.createWriteStream(platformConfig?.processConfig.options.logPath.stdout));
if (platformConfig?.processConfig.options.logPath.stderr) this.#childProcess.stderr.pipe(fs.createWriteStream(platformConfig?.processConfig.options.logPath.stderr));
}
this.#childProcess.on("error", data => this.emit("error", data));
@@ -132,11 +127,11 @@ export class actions extends EventEmitter {
const readlineStderr = readline.createInterface(this.#childProcess.stderr);
readlineStdout.on("line", data => this.emit("log_stdout", data));
readlineStderr.on("line", data => this.emit("log_stderr", data));
readlineStdout.on("line", data => this.emit("data", data));
readlineStderr.on("line", data => this.emit("data", data));
readlineStdout.on("line", data => this.emit("log", data));
readlineStderr.on("line", data => this.emit("log", data));
const plug = config.find((a: actionPlugin) => a?.name === "pluginManeger") as actionPlugin;
const hooks = config.find((a: actionHooks) => a?.name === "pluginHooks") as actionHooks;
const plug = platformConfig?.hooks?.find((a: actionPlugin) => a?.name === "pluginManeger") as actionPlugin;
const hooks = platformConfig?.hooks?.find((a: actionHooks) => a?.name === "pluginHooks") as actionHooks;
if (!!hooks) Promise.resolve().then(() => hooks.class(this)).then(res => this.hooks = res);
if (!!plug) plug.class().then(res => this.plugin = res).catch(err => this.emit("error", err));
@@ -177,20 +172,20 @@ export class actions extends EventEmitter {
});
// Callbacks
(config.filter((a: actionCallback) => typeof a?.callback === "function") as actionCallback[]).forEach(fn => {
(platformConfig?.hooks?.filter((a: actionCallback) => typeof a?.callback === "function") as actionCallback[]).forEach(fn => {
// Use new player actions
if (fn.name === "playerAction") {
const playerConnect = (data: playerBase) => this.emit("playerConnect", data), playerDisonnect = (data: playerBase) => this.emit("playerDisconnect", data), playerUnknown = (data: playerBase) => this.emit("playerUnknown", data);
this.on("log_stdout", data => fn.callback(data, playerConnect, playerDisonnect, playerUnknown));
this.on("log_stderr", data => fn.callback(data, playerConnect, playerDisonnect, playerUnknown));
return;
} else if (fn.name === "playerConnect"||fn.name === "playerDisconnect"||fn.name === "playerUnknown") console.warn("Migrate %s to playerAction", fn.name);
}
this.on("log_stdout", data => fn.callback(data, (...args: any[]) => this.emit(fn.name, ...args)));
this.on("log_stderr", data => fn.callback(data, (...args: any[]) => this.emit(fn.name, ...args)));
});
// Set backend run function
(config.filter((a: actionRun) => typeof a?.run === "function") as actionRun[]).forEach(action => {
(platformConfig?.hooks?.filter((a: actionRun) => typeof a?.run === "function") as actionRun[]).forEach(action => {
if (action.name === "serverStop") this.#stopServerFunction = action.run;
else if (action.name === "tp") this.#tpfunction = action.run;
});

View File

@@ -1,5 +1,7 @@
export { exportBds, importBds, payloadError } from "./export_import";
export { pluginManeger } from "./plugin/main";
export * as platformPathManeger from "./platformPathManeger"
export * as pluginManeger from "./plugin/plugin";
export * as pluginHooks from "./plugin/hook";
export * as globalPlatfroms from "./globalPlatfroms";
export * as Bedrock from "./bedrock";
export * as PocketmineMP from "./pocketmine";

View File

@@ -3,14 +3,14 @@ import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { serverRoot, logRoot } from "./pathControl";
import { actions, actionConfig } from "./globalPlatfroms";
import { saveFile } from "./httpRequest";
export const serverPath = path.join(serverRoot, "java");
const jarPath = path.join(serverPath, "server.jar");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
// export const serverPath = path.join(serverRoot, "java");
export async function installServer(version: string|boolean) {
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("java", platformOptions);
const jarPath = path.join(serverPath, "server.jar");
return platformManeger.java.find(version).then(release => saveFile(release.url, {filePath: jarPath}).then(() => release));
}
@@ -58,7 +58,9 @@ const serverConfig: actionConfig[] = [
},
];
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean}) {
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, platformOptions: bdsPlatformOptions}) {
const { serverPath, logsPath } = await pathControl("java", Config?.platformOptions||{id: "default"});
const jarPath = path.join(serverPath, "server.jar");
if (!fsOld.existsSync(jarPath)) throw new Error("Install server fist.");
const command = "java";
const args = ["-jar"];
@@ -75,6 +77,9 @@ export async function startServer(Config?: {maxMemory?: number, minMemory?: numb
args.push(jarPath, "nogui");
const eula = path.join(serverPath, "eula.txt");
await fs.writeFile(eula, (await fs.readFile(eula, "utf8").catch(() => "eula=false")).replace("eula=false", "eula=true"));
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_java_${process.platform}_${process.arch}.stdout.log`);
return new actions({command, args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}}, serverConfig);
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.log`);
return new actions({
processConfig: {command, args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}

View File

@@ -2,19 +2,14 @@ import path from "node:path";
import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import { pluginManeger as plugin_maneger } from "./plugin/main";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { serverRoot, logRoot } from "./pathControl";
import { actions, actionConfig } from "./globalPlatfroms";
import { saveFile } from "./httpRequest";
import { script_hook } from "./plugin/hook";
export const serverPath = path.join(serverRoot, "Papermc");
const jarPath = path.join(serverPath, "server.jar");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
export const pluginManger = () => (new plugin_maneger("paper", false)).loadPlugins();
export async function installServer(version: string|boolean) {
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
return platformManeger.paper.find(version).then(release => saveFile(release.url, {filePath: jarPath}).then(() => release));
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("paper", platformOptions);
return platformManeger.paper.find(version).then(release => saveFile(release.url, {filePath: path.join(serverPath, "paper.jar")}).then(() => release));
}
export const started = /\[.*\].*\s+Done\s+\(.*\)\!.*/;
@@ -27,14 +22,6 @@ const serverConfig: actionConfig[] = [
childProcess.runCommand("stop");
},
},
{
name: "pluginManeger",
class: () => (new plugin_maneger("paper", false)).loadPlugins()
},
{
name: "pluginHooks",
class: (actions) => new script_hook("paper", actions)
},
{
name: "serverStarted",
callback(data, done) {
@@ -71,8 +58,9 @@ const serverConfig: actionConfig[] = [
},
];
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, pluginList?: string[]}) {
if (!fsOld.existsSync(jarPath)) throw new Error("Install server fist.");
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, platformOptions?: bdsPlatformOptions}) {
const { serverPath, logsPath } = await pathControl("paper", Config?.platformOptions||{id: "default"});
if (!fsOld.existsSync(path.join(serverPath, "paper.jar"))) throw new Error("Install server fist.");
const args = [];
if (Config) {
if (Config.maxFreeMemory) {
@@ -83,15 +71,14 @@ export async function startServer(Config?: {maxMemory?: number, minMemory?: numb
if (Config.minMemory) args.push(`-Xms${Config.minMemory}m`);
if (Config.maxMemory) args.push(`-Xmx${Config.maxMemory}m`);
}
if (Config.pluginList) {
const pluginManeger = await (new plugin_maneger("paper")).loadPlugins();
await Promise.all(Config.pluginList.map(pluginName => pluginManeger.installPlugin(pluginName)));
}
}
args.push("-jar", jarPath, "nogui");
args.push("-jar", path.join(serverPath, "paper.jar"), "nogui");
const eula = path.join(serverPath, "eula.txt");
await fs.writeFile(eula, (await fs.readFile(eula, "utf8").catch(() => "eula=false")).replace("eula=false", "eula=true"));
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_spigot_${process.platform}_${process.arch}.stdout.log`);
return new actions({command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}}, serverConfig);
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.log`);
return new actions({
processConfig: {command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}

View File

@@ -1,32 +0,0 @@
import fs from "node:fs/promises";
import fsOld from "node:fs";
import path from "node:path";
import os from "node:os";
// bds Root
export const bdsRoot = process.env.BDS_HOME||path.join(os.homedir(), ".bdsManeger");
if (!fsOld.existsSync(bdsRoot)) fs.mkdir(bdsRoot, {recursive: true}).then(() => console.log("Bds Root created"));
// Server Folder
export const serverRoot = path.join(bdsRoot, "Servers");
if (!fsOld.existsSync(serverRoot)) fs.mkdir(serverRoot, {recursive: true});
// Build Folder
export const BuildRoot = path.join(bdsRoot, "build");
if (!fsOld.existsSync(BuildRoot)) fs.mkdir(BuildRoot, {recursive: true});
// Logs Folder
export const logRoot = path.join(bdsRoot, "logFolder");
if (!fsOld.existsSync(logRoot)) fs.mkdir(logRoot, {recursive: true});
// Worlds Folder
export const worldFolder = path.join(bdsRoot, "Worlds");
if (!fsOld.existsSync(worldFolder)) fs.mkdir(serverRoot, {recursive: true});
// Plugins hooks
export const pluginHooksFolder = path.join(bdsRoot, "pluginHooks");
if (!fsOld.existsSync(pluginHooksFolder)) fs.mkdir(pluginHooksFolder, {recursive: true});
// Bds backup
export const backupFolder = path.join(bdsRoot, "Backup");
if (!fsOld.existsSync(backupFolder)) fs.mkdir(backupFolder, {recursive: true});

View File

@@ -0,0 +1,96 @@
import crypto from "node:crypto";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
export const bdsRoot = process.env.BDS_HOME||path.join(os.homedir(), ".bdsManeger");
async function exists(filePath: string) {
return fs.access(filePath).then(() => true).catch((() => false));
}
export type bdsPlatform = "bedrock"|"java"|"pocketmine"|"spigot"|"powernukkit"|"paper";
export type bdsPlatformOptions = {
newId?: boolean,
id?: "default"|string,
withBuildFolder?: boolean
};
// This array to valida platform imput!
const platformArray: bdsPlatform[] = [
"bedrock",
"java",
"pocketmine",
"spigot",
"powernukkit",
"paper"
];
/**
* Register or get folder to Servers, this is to create and maneger folders
* @param platform - Select platform to maneger folders
* @param options - ?
*/
export async function pathControl(platform: bdsPlatform, options?: bdsPlatformOptions) {
if (!platformArray.includes(platform)) throw new Error("Invalid platform");
if (!options) options = {};
if (!await exists(path.join(bdsRoot, platform))) await fs.mkdir(path.join(bdsRoot, platform), {recursive: true});
// Create if not exists
const foldersAndLink = await fs.readdir(path.join(bdsRoot, platform));
if (foldersAndLink.length === 0) options.newId = true;
if (options.newId) {
options.id = crypto.randomBytes(12).toString("hex");
fs.mkdir(path.join(bdsRoot, platform, options.id), {recursive: true});
if (await exists(path.join(bdsRoot, platform, "default"))) await fs.unlink(path.join(bdsRoot, platform, "default"));
await fs.symlink(path.join(bdsRoot, platform, options.id), path.join(bdsRoot, platform, "default"));
}
// Create folder if not exists
const serverRoot = path.join(bdsRoot, platform, options.id);
if (!(await exists(serverRoot))) await fs.mkdir(serverRoot, {recursive: true});
const serverPath = path.join(serverRoot, "server");
if (!(await exists(serverPath))) await fs.mkdir(serverPath, {recursive: true});
const hooksPath = path.join(serverRoot, "hooks");
if (!(await exists(hooksPath))) await fs.mkdir(hooksPath, {recursive: true});
const backupPath = path.join(serverRoot, "backup");
if (!(await exists(backupPath))) await fs.mkdir(backupPath, {recursive: true});
const logsPath = path.join(serverRoot, "logs");
if (!(await exists(logsPath))) await fs.mkdir(logsPath, {recursive: true});
let buildFolder: string;
if (options?.withBuildFolder) {
const buildFolder = path.join(serverRoot, "build");
if (!(await exists(buildFolder))) await fs.mkdir(buildFolder, {recursive: true});
}
return {
id: options?.id,
serverRoot,
serverPath,
hooksPath,
backupPath,
logsPath,
buildFolder,
};
}
/**
* Change default folder to Platform
* @param platform
* @param id
* @returns
*/
export async function changeDefault(platform: bdsPlatform, id: bdsPlatformOptions["id"]) {
if (!platformArray.includes(platform)) throw new Error("Invalid platform");
const serverPlatform = path.join(bdsRoot, platform);
if (!await exists(serverPlatform)) throw new Error("Install server fist!");
const ids = (await fs.readdir(serverPlatform)).filter(folder => folder.toLowerCase() !== "default");
if (!ids.includes(id)) throw new Error("Id not exists to Platform");
const oldPath = fs.realpath(path.join(bdsRoot, platform, "default"));
if (await exists(path.join(bdsRoot, platform, "default"))) await fs.unlink(path.join(bdsRoot, platform, "default"));
await fs.symlink(path.join(bdsRoot, platform, id), path.join(bdsRoot, platform, "default"));
return {
oldPath,
newPath: path.join(bdsRoot, platform, id)
};
}

View File

@@ -2,7 +2,6 @@ import path from "node:path";
import fs from "node:fs/promises";
import { execFileAsync } from "../childPromisses";
import { actions } from "../globalPlatfroms";
import { pluginHooksFolder } from "../pathControl";
import { saveFile } from "../httpRequest";
export type hooksPlatform = "bedrock"|"java"|"pocketmine"|"spigot"|"powernukkit"|"paper";
@@ -23,7 +22,6 @@ export class script_hook {
#serverActions: actions;
#currentPlatform: hooksPlatformGeneric;
#localFolder: string;
#localGericFolder = path.join(pluginHooksFolder, "Generic");
async #registerScript(filePath: string) {
const lo_script = (await(eval(`import("${filePath}")`))) as hooksRegister|{default: hooksRegister};
@@ -42,11 +40,8 @@ export class script_hook {
async #loadLocalScript() {
if (!this.#serverActions) throw new Error("Server actions (globalPlatform) is undefined");
if (!await exists(this.#localFolder)) await fs.mkdir(this.#localFolder, {recursive: true});
if (!await exists(this.#localGericFolder)) await fs.mkdir(this.#localGericFolder, {recursive: true});
const localFiles = (await fs.readdir(this.#localFolder)).map(file => path.join(this.#localFolder, file));
const genericLocalFiles = (await fs.readdir(this.#localGericFolder)).map(file => path.join(this.#localGericFolder, file));
console.log(([...localFiles, ...genericLocalFiles]));
for (const localFile of ([...localFiles, ...genericLocalFiles])) {
for (const localFile of localFiles) {
await fs.lstat(localFile).then(async stat => {
if (stat.isFile()) return this.#registerScript(localFile);
if (await exists(path.join(localFile, "package.json"))) {
@@ -66,30 +61,23 @@ export class script_hook {
}
}
public async installHook(urlHost: string, fileName?: string, isGeneric?: boolean) {
public async installHook(urlHost: string, fileName?: string) {
if (!await exists(this.#localFolder)) await fs.mkdir(this.#localFolder, {recursive: true});
if (!await exists(this.#localGericFolder)) await fs.mkdir(this.#localGericFolder, {recursive: true});
if (!fileName) fileName = path.basename(urlHost);
const onSave = path.join(isGeneric?this.#localGericFolder:this.#localFolder, fileName);
const onSave = path.join(this.#localFolder, fileName);
// Git
if (gitUrlDetect.test(urlHost)) {
await execFileAsync("git", ["clone", urlHost, "--depth", 1, onSave], {cwd: pluginHooksFolder});
await execFileAsync("git", ["clone", urlHost, "--depth", 1, onSave], {cwd: this.#localFolder});
if (await exists(path.join(onSave, "package.json"))) await execFileAsync("npm", ["install", "--no-save"], {cwd: onSave, stdio: "inherit"});
} else await saveFile(urlHost, {filePath: onSave});
if (!!this.#serverActions) await this.#registerScript(onSave);
return;
}
constructor(targetPlatform: hooksPlatform, platformActions?: actions) {
constructor(hookFolder: string, targetPlatform: hooksPlatform, platformActions?: actions) {
this.#serverActions = platformActions;
this.#currentPlatform = targetPlatform;
if (targetPlatform === "spigot") this.#localFolder = path.join(pluginHooksFolder, "Spigot");
else if (targetPlatform === "paper") this.#localFolder = path.join(pluginHooksFolder, "Spigot");
else if (targetPlatform === "pocketmine") this.#localFolder = path.join(pluginHooksFolder, "PocketmineMP");
else if (targetPlatform === "powernukkit") this.#localFolder = path.join(pluginHooksFolder, "Powernukkit");
else if (targetPlatform === "bedrock") this.#localFolder = path.join(pluginHooksFolder, "Bedrock");
else if (targetPlatform === "java") this.#localFolder = path.join(pluginHooksFolder, "Java");
else throw new Error("Invalid platform");
this.#localFolder = hookFolder;
if (platformActions) this.#loadLocalScript();
}
}

View File

@@ -1,85 +0,0 @@
import path from "node:path/posix";
import fs from "node:fs/promises";
import admZip from "adm-zip";
import { existsSync } from "node:fs";
import { saveFile, githubTree, getJSON } from "../httpRequest";
import { serverPath as spigotServerPath } from "../spigot";
import { serverPath as papertServerPath } from "../paper";
import { serverPath as pocketmineServerPath } from "../pocketmine";
import { serverPath as powernukkittServerPath } from "../pwnuukit";
import { actions } from "../globalPlatfroms";
import { script_hook } from "./hook";
export type pluginPlatform = "spigot"|"paper"|"pocketmine"|"powernukkit";
export type pluginFunctions = {
platforms: pluginPlatform[],
scriptName?: string,
register: (actions: actions) => void,
};
export type pluginConfig = {
name: string,
fileName?: string,
url: string,
type?: "zip"|"jar"|"raw",
platforms: pluginPlatform[],
dependes?: (string|pluginConfig)[],
scripts?: string[]
};
export class pluginManeger {
#platform: pluginPlatform;
#hook: script_hook;
pluginList: pluginConfig[] = [];
scriptList: pluginFunctions[] = [];
#mountRepoRaw(...args: string[]) {
const ufixPath = path.join("/The-Bds-Maneger/plugin_list/main", path.resolve("/", ...args));
return {
url: "https://raw.githubusercontent.com"+ufixPath,
addPluginStyle: ufixPath.replace(/\/The\-Bds\-Maneger\/plugin_list\/main\/|\.\//, "")
};
}
async #addPlugin (file?: string): Promise<pluginConfig|void> {
const config = await getJSON<pluginConfig>(this.#mountRepoRaw(file).url);
if (this.pluginList.some(plugin => plugin.name === config.name)) return config;
if (!config.platforms?.includes(this.#platform)) return;
this.pluginList.push(config);
if (config.dependes) {
config.dependes = await Promise.all(config.dependes.map((depend: string) => this.#addPlugin(this.#mountRepoRaw(path.dirname(file), depend).addPluginStyle))) as pluginConfig[];
}
};
async installPlugin(name: string) {
const plugin = this.pluginList.find(plugin => plugin.name === name);
if (!plugin) throw new Error(`${name} plugin not avaible to install`);
console.log("Installing %s plugin", plugin.name);
let pluginFolder: string;
if (this.#platform === "paper") pluginFolder = path.join(papertServerPath, "plugins");
else if (this.#platform === "spigot") pluginFolder = path.join(spigotServerPath, "plugins");
else if (this.#platform === "pocketmine") pluginFolder = path.join(pocketmineServerPath, "plugins");
else if (this.#platform === "powernukkit") pluginFolder = path.join(powernukkittServerPath, "plugins");
else throw new Error("Invalid platform");
if (!existsSync(pluginFolder)) await fs.mkdir(pluginFolder, {recursive: true});
const saveOut = path.join(pluginFolder, plugin.fileName||`${plugin.name}.${path.extname(plugin.fileName||plugin.url)}`);
await saveFile(plugin.url, {filePath: saveOut});
if (plugin.type === "zip") {
const zip = new admZip(saveOut);
zip.extractAllTo(pluginFolder, true);
await fs.rm(saveOut, {force: true});
}
if (plugin.scripts && !!this.#hook) await Promise.all(plugin.scripts.map(file => this.#hook.installHook(this.#mountRepoRaw(file).url)));
if (plugin.dependes) await Promise.all(plugin.dependes.map((depend: pluginConfig) => this.installPlugin(depend.name)));
}
async loadPlugins() {
for (const file of (await githubTree("The-Bds-Maneger", "plugin_list", "main")).tree.filter(file => file.path.endsWith(".json"))) await this.#addPlugin(file.path);
return this;
}
constructor(platform: pluginPlatform, autloadPLugins: boolean = true) {
this.#platform = platform;
this.#hook = new script_hook(platform);
if (autloadPLugins) this.loadPlugins();
}
};

10
src/plugin/plugin.ts Normal file
View File

@@ -0,0 +1,10 @@
import path from "node:path/posix";
import fs from "node:fs/promises";
import admZip from "adm-zip";
import * as globalPlatfroms from "../globalPlatfroms";
import { saveFile, githubTree, getJSON } from "../httpRequest";
// Ingore
export {path, fs, admZip, globalPlatfroms, saveFile, githubTree, getJSON};
export class pluginManeger {};

View File

@@ -1,24 +1,22 @@
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
import { existsSync as fsExistsSync, Stats } from "node:fs";
import AdmZip from "adm-zip";
import { existsSync as fsExistsSync, Stats } from "node:fs";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { execFileAsync, execAsync } from './childPromisses';
import { logRoot, serverRoot } from "./pathControl";
import { getBuffer, githubRelease, GithubRelease, saveFile, tarExtract } from "./httpRequest";
import { actionConfig, actions } from './globalPlatfroms';
import AdmZip from "adm-zip";
import { promisify } from 'node:util';
export const serverPath = path.join(serverRoot, "pocketmine");
export const serverPhar = path.join(serverPath, "pocketmine.phar");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
async function findPhp(extraPath?: string): Promise<string> {
async function findPhp(serverPath: string, extraPath?: string): Promise<string> {
if (!extraPath) extraPath = path.join(serverPath, "bin");
const files = await Promise.all((await fs.readdir(extraPath)).map(file => fs.lstat(path.join(extraPath, file)).then(stat => ({stat, file, fullPath: path.join(extraPath, file)})).catch(() => {})));
let folderFF = "";
for (const file of (files.filter(a=>!!a) as {file: string, fullPath: string, stat: Stats}[]).sort(a => a.stat.isDirectory() ? 1:-1)) {
if (file.stat.isDirectory()) {
folderFF = await findPhp(file.fullPath).catch(() => "");
folderFF = await findPhp(serverPath, file.fullPath).catch(() => "");
if (folderFF) return folderFF;
} else if (file.file === "php"||file.file === "php.exe") return file.fullPath;
}
@@ -50,7 +48,7 @@ if (!filter) filter = [/.*/];
return files;
}
async function buildPhp() {
async function buildPhp(serverPath: string) {
if (fsExistsSync(path.resolve(serverPath, "bin"))) await fs.rm(path.resolve(serverPath, "bin"), {recursive: true});
const tempFolder = path.join(os.tmpdir(), "bdsPhp_"+(Math.random()*19999901).toString(16).replace(".", "").replace(/[0-9]/g, (_, a) =>a=="1"?"a":a=="2"?"b":a=="3"?"S":"k"));
if (!fsExistsSync(tempFolder)) fs.mkdir(tempFolder, {recursive: true});
@@ -70,7 +68,7 @@ async function buildPhp() {
console.log("PHP Build success!");
}
async function installPhp(): Promise<void> {
async function installPhp(serverPath: string): Promise<void> {
const releases: (githubRelease["assets"][0])[] = [];
(await GithubRelease("The-Bds-Maneger", "Build-PHP-Bins")).map(re => re.assets).forEach(res => releases.push(...res));
if (fsExistsSync(path.resolve(serverPath, "bin"))) await fs.rm(path.resolve(serverPath, "bin"), {recursive: true});
@@ -100,17 +98,17 @@ async function installPhp(): Promise<void> {
}
}
// test it's works php
await execFileAsync(await findPhp(), ["-v"]).catch(err => {
await execFileAsync(await findPhp(serverPath), ["-v"]).catch(err => {
console.warn(String(err));
return buildPhp()
return buildPhp(serverPath)
});
}
export async function installServer(version: string|boolean) {
if (!fsExistsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
await installPhp();
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("pocketmine", platformOptions);
await installPhp(serverPath);
const info = await platformManeger.pocketmine.find(version);
await saveFile(info?.url, {filePath: serverPhar});
await saveFile(info?.url, {filePath: path.join(serverPath, "")});
return info;
}
@@ -152,8 +150,13 @@ const serverConfig: actionConfig[] = [
},
];
export async function startServer() {
if (!fsExistsSync(serverPath)) throw new Error("Install server fist!");
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_pocketmine_${process.platform}_${process.arch}.stdout.log`);
return new actions({command: await findPhp(), args: [serverPhar, "--no-wizard", "--enable-ansi"], options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}}, serverConfig);
export async function startServer(platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath, logsPath } = await pathControl("pocketmine", platformOptions);
const serverPhar = path.join(serverPath, "pocketmine.phar");
if (!fsExistsSync(serverPhar)) throw new Error("Install server fist!");
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.stdout.log`);
return new actions({
processConfig: {command: await findPhp(serverPath), args: [serverPhar, "--no-wizard", "--enable-ansi"], options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}

View File

@@ -1,16 +1,21 @@
import * as path from "node:path";
import * as fsOld from "node:fs";
import * as fs from "node:fs/promises";
import path from "node:path";
import fsOld from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import { serverRoot, logRoot } from './pathControl';
import { actions, actionConfig } from './globalPlatfroms';
import { actions, actionConfig } from "./globalPlatfroms";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { saveFile } from "./httpRequest";
export const serverPath = path.join(serverRoot, "power_nukkit");
const jarPath = path.join(serverPath, "pwnukkit.jar");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("powernukkit", platformOptions);
const jarPath = path.join(serverPath, "pwnukkit.jar");
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
return platformManeger.powernukkit.find(version).then(release => saveFile(release.url, {filePath: jarPath}).then(() => release));
}
export const playerAction = /^.*\[.*\]\s([\S\w]+|"[\S\w]+")\s+(left|joined)\s+the\s+game$/;
export const portListen = /Opening\s+server\s+on\s+(([A-Za-z0-9:\.]+):([0-9]+))/;
const serverConfig: actionConfig[] = [
{
name: "serverStop",
@@ -50,12 +55,9 @@ const serverConfig: actionConfig[] = [
}
];
export async function installServer(version: string|boolean) {
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
return platformManeger.powernukkit.find(version).then(release => saveFile(release.url, {filePath: jarPath}).then(() => release));
}
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean}) {
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, platformOptions?: bdsPlatformOptions}) {
const { serverPath, logsPath } = await pathControl("powernukkit", Config?.platformOptions||{id: "default"});
const jarPath = path.join(serverPath, "pwnukkit.jar");
if (!fsOld.existsSync(jarPath)) throw new Error("Install server fist.");
const args = [
"-XX:+UseG1GC",
@@ -90,6 +92,9 @@ export async function startServer(Config?: {maxMemory?: number, minMemory?: numb
}
}
args.push("-jar", jarPath, "--language", "eng");
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_pwnukkit_${process.platform}_${process.arch}.stdout.log`);
return new actions({command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}}, serverConfig);
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.log`);
return new actions({
processConfig: {command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}

View File

@@ -2,15 +2,9 @@ import path from "node:path";
import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import {pluginManeger as plugin_maneger} from "./plugin/main";
import { serverRoot, logRoot, BuildRoot } from './pathControl';
import { actions, actionConfig } from './globalPlatfroms';
import { actions, actionConfig } from "./globalPlatfroms";
import { getBuffer, getJSON, saveFile } from "./httpRequest";
import { script_hook } from "./plugin/hook";
export const serverPath = path.join(serverRoot, "spigot");
export const serverPathBuild = path.join(BuildRoot, "spigot");
const jarPath = path.join(serverPath, "server.jar");
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
async function listVersions() {
const data = (await getBuffer("https://hub.spigotmc.org/versions/")).toString("utf8").split("\r").filter(line => /\.json/.test(line)).map(line => {const [, data] = line.match(/>(.*)<\//); return data?.replace(".json", "");}).filter(ver => /^[0-9]+\./.test(ver));
@@ -25,15 +19,14 @@ async function listVersions() {
return data2.sort((b, a) => a.date.getTime() - b.date.getTime());
}
export async function installServer(version: string|boolean) {
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
if (!fsOld.existsSync(serverPathBuild)) await fs.mkdir(serverPathBuild, {recursive: true});
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("spigot", platformOptions);
const jarPath = path.join(serverPath, "server.jar");
if (typeof version === "boolean"||version === "latest") version = (await listVersions())[0].version;
await fs.cp(await saveFile(`https://github.com/The-Bds-Maneger/SpigotBuilds/releases/download/${version}/Spigot.jar`), jarPath, {force: true});
return;
}
export const pluginManger = () => (new plugin_maneger("spigot", false)).loadPlugins();
export const started = /\[.*\].*\s+Done\s+\(.*\)\!.*/;
export const portListen = /\[.*\]:\s+Starting\s+Minecraft\s+server\s+on\s+(([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[A-Za-z0-9]+|\*):([0-9]+))/;
@@ -43,14 +36,6 @@ const serverConfig: actionConfig[] = [
name: "serverStop",
run: (child) => child.runCommand("stop")
},
{
name: "pluginManeger",
class: () => (new plugin_maneger("spigot", false)).loadPlugins()
},
{
name: "pluginHooks",
class: (actions) => new script_hook("spigot", actions)
},
{
name: "serverStarted",
callback(data, done) {
@@ -89,7 +74,9 @@ const serverConfig: actionConfig[] = [
},
];
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, pluginList?: string[]}) {
export async function startServer(Config?: {maxMemory?: number, minMemory?: number, maxFreeMemory?: boolean, platformOptions?: bdsPlatformOptions}) {
const { serverPath, logsPath } = await pathControl("spigot", Config?.platformOptions||{id: "default"});
const jarPath = path.join(serverPath, "server.jar");
if (!fsOld.existsSync(jarPath)) throw new Error("Install server fist.");
const args = [];
if (Config) {
@@ -101,16 +88,14 @@ export async function startServer(Config?: {maxMemory?: number, minMemory?: numb
if (Config.minMemory) args.push(`-Xms${Config.minMemory}m`);
if (Config.maxMemory) args.push(`-Xmx${Config.maxMemory}m`);
}
if (Config.pluginList) {
const pluginManeger = await (new plugin_maneger("spigot")).loadPlugins();
await Promise.all(Config.pluginList.map(pluginName => pluginManeger.installPlugin(pluginName)));
}
}
args.push("-jar", jarPath, "nogui");
const eula = path.join(serverPath, "eula.txt");
await fs.readFile(eula, "utf8").catch(() => "eula=false").then(eulaFile => fs.writeFile(eula, eulaFile.replace("eula=false", "eula=true")));
const logFileOut = path.join(logRoot, `bdsManeger_${Date.now()}_spigot_${process.platform}_${process.arch}.stdout.log`);
return new actions({command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}}, serverConfig);
const logFileOut = path.join(logsPath, `${Date.now()}_${process.platform}_${process.arch}.log`);
return new actions({
processConfig: {command: "java", args, options: {cwd: serverPath, maxBuffer: Infinity, logPath: {stdout: logFileOut}}},
hooks: serverConfig
});
}

View File

@@ -4,8 +4,6 @@ describe("PaperMC", () => {
it("Install and Start", async function(){
this.timeout(Infinity);
await paper.installServer("latest");
const plugin = await paper.pluginManger();
await plugin.installPlugin("Geyser");
const serverManeger = await paper.startServer({maxFreeMemory: true});
serverManeger.on("log_stdout", console.log);
serverManeger.on("log_stderr", console.info);

View File

@@ -4,8 +4,6 @@ describe("Spigot", () => {
it("Install and Start", async function(){
this.timeout(Infinity);
await spigot.installServer("latest");
const plugin = await spigot.pluginManger();
await plugin.installPlugin("Geyser");
const serverManeger = await spigot.startServer();
serverManeger.on("log_stdout", console.log);
serverManeger.on("log_stderr", console.info);