From 33aab3c3ff990f8781af480200efb0a75321c057 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 18:36:44 -0300 Subject: [PATCH 1/7] Push --- src/BdsManegerServer.js | 235 +++---------------------- src/ManegerServer/BasicCommands.js | 127 ++++++++++++++ src/ManegerServer/Players_json.js | 114 +++++++++++++ src/api.js | 266 ++++++++++++----------------- 4 files changed, 375 insertions(+), 367 deletions(-) create mode 100644 src/ManegerServer/BasicCommands.js create mode 100644 src/ManegerServer/Players_json.js diff --git a/src/BdsManegerServer.js b/src/BdsManegerServer.js index 329ecb7..de339f5 100644 --- a/src/BdsManegerServer.js +++ b/src/BdsManegerServer.js @@ -6,6 +6,9 @@ const { Backup } = require("./BdsBackup"); const { CronJob } = require("cron"); const BdsSettings = require("../src/lib/BdsSettings"); +const PlayerJson = require("./ManegerServer/Players_json"); +const BasicCommands = require("./ManegerServer/BasicCommands"); + const ServerSessions = {}; module.exports.GetSessions = () => ServerSessions; @@ -117,10 +120,6 @@ module.exports.StartServer = function start() { } fs.writeFileSync(LatestLog_Path, ""); - // Player JSON File - ServerExec.stdout.on("data", data => Player_Json(data, UpdateUserJSON)); - ServerExec.stderr.on("data", data => Player_Json(data, UpdateUserJSON)); - // Log File ServerExec.stdout.on("data", LogSaveFunction); ServerExec.stderr.on("data", LogSaveFunction); @@ -142,7 +141,7 @@ module.exports.StartServer = function start() { if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect"); // Functions - const data = data => Player_Json(data, function (array_status){ + const data = data => PlayerJson.UpdateUserJSON(data, function (array_status){ array_status.filter(On => {if ("all" === action || On.Action === action) return true; else return false;}).forEach(_player => callback(_player)) }); ServerExec.stdout.on("data", data); @@ -152,134 +151,18 @@ module.exports.StartServer = function start() { ServerExec.stdin.write(`${command}\n`); return command; }; - const stop = function (){ - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write("stop\n"); - return "stop"; - } else if (CurrentBdsPlatform === "dragonfly") { - ServerExec.kill("SIGKILL"); - return "process"; - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write("stop\n"); - return "stop"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write("stop\n"); - return "stop"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write("stop\n"); - return "stop"; - } else throw new Error("Bds Core Bad Config Error"); - }; - const op = function (player = "Steve") { - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`op "${player}"\n`); - return "op"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`op ${player}\n`); - return "op"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`op ${player}\n`); - return "op"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`op ${player}\n`); - return "op"; - } else throw new Error("Bds Core Bad Config Error"); - }; - const deop = function (player = "Steve") { - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`deop "${player}"\n`); - return "deop"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`deop ${player}\n`); - return "deop"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`deop ${player}\n`); - return "deop"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`deop ${player}\n`); - return "deop"; - } else throw new Error("Bds Core Bad Config Error"); - }; - const ban = function (player = "Steve") { - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`kick "${player}"\n`); - return "kick"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`ban ${player}\n`); - return "ban"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`ban ${player}\n`); - return "ban"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`ban ${player}\n`); - return "ban"; - } else throw new Error("Bds Core Bad Config Error"); - }; - const kick = function (player = "Steve", text = "you got kicked") { - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`kick "${player}" ${text}\n`); - return "kick"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`kick ${player} ${text}\n`); - return "kick"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`kick ${player} ${text}\n`); - return "kick"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`kick ${player} ${text}\n`); - return "kick"; - } else throw new Error("Bds Core Bad Config Error"); - }; - const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) { - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); - return "tp"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); - return "tp"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); - return "tp"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); - return "tp"; - } else throw new Error("Bds Core Bad Config Error"); - }; - function say(text = ""){ - if (CurrentBdsPlatform === "bedrock") { - ServerExec.stdin.write(`say ${text}\n`); - return "say"; - } else if (CurrentBdsPlatform === "dragonfly") { - throw new Error("Dragonfly does not support commands"); - } else if (CurrentBdsPlatform === "java") { - ServerExec.stdin.write(`say ${text}\n`); - return "say"; - } else if (CurrentBdsPlatform === "pocketmine") { - ServerExec.stdin.write(`say ${text}\n`); - return "say"; - } else if (CurrentBdsPlatform === "spigot") { - ServerExec.stdin.write(`say ${text}\n`); - return "say"; - } else throw new Error("Bds Core Bad Config Error"); - } + + const BasicCo = BasicCommands.BasicCommands(ServerExec); // Mount commands to Return const returnFuntion = { uuid: randomUUID(), + LogPath: LogFile, pid: ServerExec.pid, uptime: 0, StartTime: (new Date()), - command, log, exit, on, stop, op, deop, ban, kick, tp, say + ...BasicCo, + command, log, exit, on } // Uptime Server @@ -291,15 +174,15 @@ module.exports.StartServer = function start() { // Socket.io io.on("connection", socket => { - socket.on("ServerCommand", (data, callback) => { - if (typeof data === "string") return returnFuntion.command(data); - else if (typeof data === "object") { - if (typeof data.uuid === "string") { - if (data.uuid === returnFuntion.uuid) return returnFuntion.command(data.command); + socket.on("ServerCommand", (data) => { + if (typeof data === "string") return returnFuntion.command(data); + else if (typeof data === "object") { + if (typeof data.uuid === "string") { + if (data.uuid === returnFuntion.uuid) return returnFuntion.command(data.command); + } } - } - return; - }); + return; + }); }); ServerExec.on("exit", code => io.emit("ServerExit", { UUID: returnFuntion.uuid, @@ -320,86 +203,22 @@ module.exports.StartServer = function start() { }); }); + // Player JSON File + ServerExec.stdout.on("data", data => PlayerJson.CreatePlayerJson(data, Actions => { + PlayerJson.UpdateUserJSON(Actions); + io.emit("PlayerAction", Actions); + })); + ServerExec.stderr.on("data", data => PlayerJson.CreatePlayerJson(data, Actions => { + PlayerJson.UpdateUserJSON(Actions); + io.emit("PlayerAction", Actions); + })); + // Return ServerSessions[returnFuntion.uuid] = returnFuntion; module.exports.BdsRun = returnFuntion; return returnFuntion; } -function Player_Json(data = "", callback = () => {}){ - const Current_platorm = BdsSettings.GetPlatform(); - // Bedrock - if (Current_platorm === "bedrock") { - // "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840", - // "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840", - const BedrockMap = data.split(/\n|\r/gi).map(line => { - if (line.includes("connected") || line.includes("disconnected")) { - let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi); - - // player - let Player = line.trim().replace(/\[.+\]\s+Player/gi, "").trim().replace(/disconnected:|connected:/, "").trim().split(/,\s+xuid:/).filter(a=>a).map(a=>a.trim()).filter(a=>a); - - // - let Actions = null; - if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect"; - else if (/^connected/.test(SplitLine[0].trim())) Actions = "connect"; - - // Object Map - const ObjectReturn = { - Player: Player[0], - Action: Actions, - xuid: Player[1] || null, - Date: new Date(), - } - - // Return - return ObjectReturn - } else return false; - }).filter(a=>a); - callback(BedrockMap); - } - // Java and Pocketmine-MP - else if (Current_platorm === "java" || Current_platorm === "pocketmine") { - const JavaMap = data.split(/\n|\r/gi).map(line => { - if (line.trim().includes("joined the game") || line.includes("left the game")) { - line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim(); - let Actions = null; - if (/joined/.test(line)) Actions = "connect"; - else if (/left/.test(line)) Actions = "disconnect"; - - // Player Object - const JavaObject = { - Player: line.replace(/joined the game|left the game/gi, "").trim(), - Action: Actions, - Date: new Date(), - } - - // Return JSON - return JavaObject - } else return false; - }).filter(a=>a); - callback(JavaMap); - } -} - -const UpdateUserJSON = function (New_Object = []){ - const Player_Json_path = BdsSettings.GetPaths("player"); - const Current_platorm = BdsSettings.GetPlatform(); - let Players_Json = { - bedrock: [], - java: [], - pocketmine: [], - jsprismarine: [], - } - if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8")); - - // Array - Players_Json[Current_platorm] = Players_Json[Current_platorm].concat(New_Object) - - fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2)); - return Players_Json -} - // Search player in JSON module.exports.Player_Search = function Player_Search(player = "dontSteve") { const Player_Json_path = BdsSettings.GetPaths("player"), Current_platorm = BdsSettings.GetPlatform(); diff --git a/src/ManegerServer/BasicCommands.js b/src/ManegerServer/BasicCommands.js new file mode 100644 index 0000000..9da716f --- /dev/null +++ b/src/ManegerServer/BasicCommands.js @@ -0,0 +1,127 @@ +const BdsSettings = require("../lib/BdsSettings"); +const child_process = require("child_process"); + +module.exports.BasicCommands = function BasicCommands(ServerExec = child_process.exec("exit 0")) { + const CurrentBdsPlatform = BdsSettings.GetPlatform(); + const stop = function (){ + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write("stop\n"); + return "stop"; + } else if (CurrentBdsPlatform === "dragonfly") { + ServerExec.kill("SIGKILL"); + return "process"; + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write("stop\n"); + return "stop"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write("stop\n"); + return "stop"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write("stop\n"); + return "stop"; + } else throw new Error("Bds Core Bad Config Error"); + }; + const op = function (player = "Steve") { + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`op "${player}"\n`); + return "op"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`op ${player}\n`); + return "op"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`op ${player}\n`); + return "op"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`op ${player}\n`); + return "op"; + } else throw new Error("Bds Core Bad Config Error"); + }; + const deop = function (player = "Steve") { + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`deop "${player}"\n`); + return "deop"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`deop ${player}\n`); + return "deop"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`deop ${player}\n`); + return "deop"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`deop ${player}\n`); + return "deop"; + } else throw new Error("Bds Core Bad Config Error"); + }; + const ban = function (player = "Steve") { + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`kick "${player}"\n`); + return "kick"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`ban ${player}\n`); + return "ban"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`ban ${player}\n`); + return "ban"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`ban ${player}\n`); + return "ban"; + } else throw new Error("Bds Core Bad Config Error"); + }; + const kick = function (player = "Steve", text = "you got kicked") { + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`kick "${player}" ${text}\n`); + return "kick"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`kick ${player} ${text}\n`); + return "kick"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`kick ${player} ${text}\n`); + return "kick"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`kick ${player} ${text}\n`); + return "kick"; + } else throw new Error("Bds Core Bad Config Error"); + }; + const tp = function (player = "Steve", cord = {x: 0, y: 128, z: 0}) { + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); + return "tp"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); + return "tp"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); + return "tp"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`tp ${player} ${cord.x} ${cord.y} ${cord.z}\n`); + return "tp"; + } else throw new Error("Bds Core Bad Config Error"); + }; + function say(text = ""){ + if (CurrentBdsPlatform === "bedrock") { + ServerExec.stdin.write(`say ${text}\n`); + return "say"; + } else if (CurrentBdsPlatform === "dragonfly") { + throw new Error("Dragonfly does not support commands"); + } else if (CurrentBdsPlatform === "java") { + ServerExec.stdin.write(`say ${text}\n`); + return "say"; + } else if (CurrentBdsPlatform === "pocketmine") { + ServerExec.stdin.write(`say ${text}\n`); + return "say"; + } else if (CurrentBdsPlatform === "spigot") { + ServerExec.stdin.write(`say ${text}\n`); + return "say"; + } else throw new Error("Bds Core Bad Config Error"); + } + return { stop, op, deop, ban, kick, tp, say }; +} diff --git a/src/ManegerServer/Players_json.js b/src/ManegerServer/Players_json.js new file mode 100644 index 0000000..8fc391c --- /dev/null +++ b/src/ManegerServer/Players_json.js @@ -0,0 +1,114 @@ +const fs = require("fs"); +const BdsSettings = require("../lib/BdsSettings"); + +function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => {d}){ + const Current_platorm = BdsSettings.GetPlatform(); + // Bedrock + if (Current_platorm === "bedrock") { + // "[INFO] Player connected: Sirherobrine, xuid: 2535413418839840", + // "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840", + const BedrockMap = data.split(/\n|\r/gi).map(line => { + if (line.includes("connected")) { + let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi); + let Actions = ""; + if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect"; else Actions = "connect"; + + // Object Map + const ObjectReturn = { + Player: line.replace(/^.*connected:/gi, "").replace(/, xuid:.*$/gi, "").trim(), + Action: Actions, + Platform: Current_platorm, + xuid: line.replace(/^.*,.*xuid:/gi, "").trim(), + Date: `${new Date()}`, + } + + // Return + return ObjectReturn + } else return false; + }).filter(a=>a); + return callback(BedrockMap); + } + // Java and Pocketmine-MP + else if (Current_platorm === "java" || Current_platorm === "pocketmine") { + const JavaMap = data.split(/\n|\r/gi).map(line => { + if (line.trim().includes("joined the game") || line.includes("left the game")) { + line = line.replace(/^\[.+\] \[.+\/.+\]:/, "").trim(); + let Actions = ""; + if (/joined/.test(line)) Actions = "connect"; + else if (/left/.test(line)) Actions = "disconnect"; + else Actions = null; + + // Player Object + const JavaObject = { + Player: line.replace(/joined the game|left the game/gi, "").trim(), + Action: Actions, + Platform: Current_platorm, + Date: `${new Date()}`, + } + + // Return JSON + return JavaObject + } else return false; + }).filter(a=>a); + return callback(JavaMap); + } +} +module.exports.CreatePlayerJson = CreatePlayerJson; + +function UpdateUserJSON(New_Object = []){ + const Player_Json_path = BdsSettings.GetPaths("player"); + const Current_platorm = BdsSettings.GetPlatform(); + let Players_Json = [ + { + Player: "Steve", + Action: "connect", + Platform: Current_platorm, + Date: `${new Date()}` + } + ]; + Players_Json = []; + if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8")); + if (Players_Json.version === undefined) { + Players_Json.version = 2; + let OldPlayers_Json = { + bedrock: [], + java: [], + pocketmine: [], + jsprismarine: [], + } + OldPlayers_Json.bedrock.forEach(a=>Players_Json.push({ + Player: a.Player, + Action: a.Action, + Platform: "bedrock", + Date: a.Date + })); + OldPlayers_Json.java.forEach(a=>Players_Json.push({ + Player: a.Player, + Action: a.Action, + Platform: "java", + Date: a.Date + })); + OldPlayers_Json.pocketmine.forEach(a=>Players_Json.push({ + Player: a.Player, + Action: a.Action, + Platform: "pocketmine", + Date: a.Date + })); + } + // Array + Players_Json = Players_Json.concat(New_Object) + + fs.writeFileSync(Player_Json_path, JSON.stringify(Players_Json, null, 2)); + return Players_Json; +} +module.exports.UpdateUserJSON = UpdateUserJSON; + +// Search player in JSON +module.exports.Player_Search = function Player_Search(player = "dontSteve") { + const Player_Json_path = BdsSettings.GetPaths("player"); + const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8")) + for (let Player of Players_Json) { + if (Player.Player === player.trim()) return Player; + } + return {}; +} \ No newline at end of file diff --git a/src/api.js b/src/api.js index 6fb43e7..bd0b621 100644 --- a/src/api.js +++ b/src/api.js @@ -55,6 +55,59 @@ app.all(["/v2", "/v2/*"], ({res}) => res.status(401).json({ Error: "v2 route moved to root routes" })); +// Check Token +function CheckToken (req, res, next) { + if (req.method === "GET") { + if (req.query.token) { + if (BdsChecks.token_verify(req.query.token)) { + req.token = req.query.token; + return next(); + } + } else if (req.headers.token) { + if (BdsChecks.token_verify(req.headers.token)) { + req.token = req.headers.token; + return next(); + } + } else if (req.query.Token) { + if (BdsChecks.token_verify(req.query.Token)) { + req.token = req.query.Token; + return next(); + } + } else if (req.headers.Token) { + if (BdsChecks.token_verify(req.headers.Token)) { + req.token = req.headers.token; + return next(); + } + } + } else { + if (req.body.token) { + if (BdsChecks.token_verify(req.body.token)) { + req.token = req.body.token; + return next(); + } + } else if (req.headers.token) { + if (BdsChecks.token_verify(req.headers.token)) { + req.token = req.headers.token; + return next(); + } + } else if (req.body.Token) { + if (BdsChecks.token_verify(req.body.Token)) { + req.token = req.body.Token; + return next(); + } + } else if (req.headers.Token) { + if (BdsChecks.token_verify(req.headers.Token)) { + req.token = req.headers.Token; + return next(); + } + } + } + return res.status(401).json({ + error: "Unauthorized", + message: "Token is not valid" + }); +} + // ? /bds/ app.get(["/bds/info", "/bds", "/"], ({res}) => { try { @@ -100,6 +153,24 @@ app.get(["/bds/info", "/bds", "/"], ({res}) => { } }); +// Get Server Log +app.get(["/bds/log", "/log"], CheckToken, (req, res) => { + const Sessions = BdsManegerCore.BdsManegerServer.GetSessions(); + return res.json(Object.keys(Sessions).map(session => { + try { + return { + UUID: session, + data: fs.readFileSync(Sessions[session].LogPath, "utf8").replaceAll("\r\n", "\n").split("\n") + }; + } catch (err) { + return { + UUID: session, + Error: String(err) + }; + } + })); +}); + // Server Info app.get("/bds/info/server", ({res}) => { let ServerRunner = require("./BdsManegerServer").BdsRun; @@ -132,128 +203,9 @@ app.get("/bds/info/server", ({res}) => { } }); -// Check Token -// app.all("*", (req, res, next) => { -// if (req.method === "GET") { -// if (req.query.token) { -// if (BdsChecks.token_verify(req.query.token)) { -// req.token = req.query.token; -// return next(); -// } -// } else if (req.headers.token) { -// if (BdsChecks.token_verify(req.headers.token)) { -// req.token = req.headers.token; -// return next(); -// } -// } else if (req.query.Token) { -// if (BdsChecks.token_verify(req.query.Token)) { -// req.token = req.query.Token; -// return next(); -// } -// } else if (req.headers.Token) { -// if (BdsChecks.token_verify(req.headers.Token)) { -// req.token = req.headers.token; -// return next(); -// } -// } -// } else { -// if (req.body.token) { -// if (BdsChecks.token_verify(req.body.token)) { -// req.token = req.body.token; -// return next(); -// } -// } else if (req.headers.token) { -// if (BdsChecks.token_verify(req.headers.token)) { -// req.token = req.headers.token; -// return next(); -// } -// } else if (req.body.Token) { -// if (BdsChecks.token_verify(req.body.Token)) { -// req.token = req.body.Token; -// return next(); -// } -// } else if (req.headers.Token) { -// if (BdsChecks.token_verify(req.headers.Token)) { -// req.token = req.headers.Token; -// return next(); -// } -// } -// } -// return res.status(401).json({ -// error: "Unauthorized", -// message: "Token is not valid" -// }); -// }); - -// Whitelist -app.get("/bds/info/server/whitelist", (req, res) => { - const ServerConfig = BdsManegerCore.BdsSettings.GetJsonConfig(); - if (ServerConfig.whitelist) { - const { Token = null , Action = null } = req.query; - const WgiteList = BdsSettings.get_whitelist(); - if (Action) { - if (Action === "add") { - if (WgiteList.findIndex(WL => WL.Token === Token) === -1) { - WgiteList.push({ - Token: Token, - Time: Date.now() - }); - fs.writeFileSync(BdsManegerCore.BdsSettings.GetPaths("whitelist"), JSON.stringify(WgiteList)); - res.json({ - success: true, - message: "Whitelist Added" - }); - } else { - res.json({ - success: false, - message: "Whitelist Already Exist" - }); - } - } else if (Action === "remove") { - if (WgiteList.findIndex(WL => WL.Token === Token) !== -1) { - WgiteList.splice(WgiteList.findIndex(WL => WL.Token === Token), 1); - fs.writeFileSync(BdsManegerCore.BdsSettings.GetPaths("whitelist"), JSON.stringify(WgiteList)); - res.json({ - success: true, - message: "Whitelist Removed" - }); - } else { - res.json({ - success: false, - message: "Whitelist Not Found" - }); - } - } else { - res.json({ - success: false, - message: "Invalid Action" - }); - } - } else { - res.json(WgiteList); - } - } else { - res.status(400).json({ - error: "Whitelist Not Enabled" - }); - } -}); - // Download Server -app.get("/bds/download_server", (req, res) => { - const { Token = null, Version = "latest" } = req.query; - - // Check is Token is String - if (!Token) return res.status(400).json({ - error: "Bad Request", - message: "Token is required" - }); - - // Check Token - if (!(BdsChecks.token_verify(Token))) return res.status(400).json({ - error: "Bad Request", - message: "Token is invalid" - }); +app.get("/bds/download_server", CheckToken, (req, res) => { + const { Version = "latest" } = req.query; // Download Server BdsManegerCore.download(Version, true).then(() => { @@ -269,8 +221,8 @@ app.get("/bds/download_server", (req, res) => { }); // Update/Set Server Settings -app.post("/bds/save_settings", (req, res) => { - const { Token = null, +app.post("/bds/save_settings", CheckToken, (req, res) => { + const { WorldName = "Bds Maneger", ServerDescription = "The Bds Maneger", DefaultGamemode = "creative", @@ -284,18 +236,6 @@ app.post("/bds/save_settings", (req, res) => { port_v6 = "19133", } = req.body; - // Check is Token is String - if (!Token) return res.status(400).json({ - error: "Bad Request", - message: "Token is required" - }); - - // Check Token - if (!(BdsChecks.token_verify(Token))) return res.status(400).json({ - error: "Bad Request", - message: "Token is invalid" - }); - // Save Settings try { BdsManegerCore.set_config({ @@ -347,7 +287,7 @@ app.get("/bds/bridge", (req, res) => { // ? /player const GetPlayerJson = (Platform = BdsManegerCore.BdsSettings.GetJsonConfig().server.platform) => ([...{...JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettings.GetPaths("player"), "utf8"))}[Platform]]); -app.get("/players", (req, res) => { +app.get("/players", CheckToken, (req, res) => { const { Platform = BdsSettings.GetPlatform(), Player = null, Action = null } = req.query; let PlayerList = GetPlayerJson(Platform); if (Player) PlayerList = PlayerList.filter(PLS => PLS.Player === Player); @@ -367,10 +307,8 @@ app.get("/players", (req, res) => { // Players Actions in Backside Manager // kick player -app.get("/players/kick", (req, res) => { - const { Token = null, Player = "Sirherobrine", Text = "You have been removed from the Server" } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); +app.get("/players/kick", CheckToken, (req, res) => { + const { Player = "Sirherobrine", Text = "You have been removed from the Server" } = req.query; // Kick player const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -386,10 +324,8 @@ app.get("/players/kick", (req, res) => { }); // Ban player -app.get("/players/ban", (req, res) => { - const { Token = null, Player = "Sirherobrine" } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); +app.get("/players/ban", CheckToken, (req, res) => { + const { Player = "Sirherobrine" } = req.query; // Ban player const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -405,10 +341,8 @@ app.get("/players/ban", (req, res) => { }); // Op player -app.get("/players/op", (req, res) => { - const { Token = null, Player = "Sirherobrine" } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); +app.get("/players/op", CheckToken, CheckToken, (req, res) => { + const { Player = "Sirherobrine" } = req.query; // Op player const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -425,9 +359,7 @@ app.get("/players/op", (req, res) => { // Deop player app.get("/players/deop", (req, res) => { - const { Token = null, Player = "Sirherobrine" } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); + const { Player = "Sirherobrine" } = req.query; // Deop player const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -443,10 +375,8 @@ app.get("/players/deop", (req, res) => { }); // Say to Server -app.get("/players/say", (req, res) => { - const { Token = null, Text = "Hello Server" } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); +app.get("/players/say", CheckToken, (req, res) => { + const { Text = "Hello Server" } = req.query; // Say to Server const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -463,9 +393,7 @@ app.get("/players/say", (req, res) => { // Tp player app.get("/players/tp", (req, res) => { - const { Token = null, Player = "Sirherobrine", X = 0, Y = 0, Z = 0 } = req.query; - if (!Token) return res.status(400).json({ error: "Token is required" }); - if (!BdsChecks.token_verify(Token)) return res.status(400).json({ error: "Token is invalid" }); + const { Player = "Sirherobrine", X = 0, Y = 0, Z = 0 } = req.query; // Tp player const RunnerServer = require("./BdsManegerServer").BdsRun; @@ -485,6 +413,12 @@ app.get("/players/tp", (req, res) => { }); // Export API Routes +/** + * @param {Number} port_api - Port of API, default is 1932 + * @callback {Function} callback - Callback function when API is ready + * + * Launch an API To manage the server Remotely, some features are limited. + */ function API(port_api = 1932, callback = port => {console.log("Bds Maneger Core REST API, http port", port)}){ const MapRoutes = app._router.stack.map(d => {if (d.route) {if (d.route.path) return d.route.path;else return d.route.regexp.source;} else return null;}).filter(d => d); app.all("*", (req, res) => { @@ -503,6 +437,13 @@ function API(port_api = 1932, callback = port => {console.log("Bds Maneger Core // Bds Maneger Core API token Register const path_tokens = path.join(BdsSettings.bds_dir, "bds_tokens.json"); +/** + * + * Register new Token to API and more features in the Bds Maneger Core. + * + * @param {Array} Admin_Scoper - Array of Admin Scoper (Soon will be implemented) + * @returns {String} Token - Token of the API + */ function token_register(Admin_Scoper = ["web_admin", "admin"]) { Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper)); let tokens = []; @@ -520,7 +461,14 @@ function token_register(Admin_Scoper = ["web_admin", "admin"]) { return bdsuid; } -// Bds Maneger Core API Delet token +// Bds Maneger Core API Delete token +/** + * + * Delete Token of the API + * + * @param {String} Token - Token of the API to delete + * @returns {Boolean} - True if the token is deleted + */ function delete_token(Token = "") { if (!Token) return false; if (typeof Token !== "string") return false; -- 2.49.0 From 16e90b3b3b75729d94bce00cd92d1763a18c6b65 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 19:01:26 -0300 Subject: [PATCH 2/7] Update Players_json.js --- src/ManegerServer/Players_json.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/ManegerServer/Players_json.js b/src/ManegerServer/Players_json.js index 8fc391c..de88c6a 100644 --- a/src/ManegerServer/Players_json.js +++ b/src/ManegerServer/Players_json.js @@ -68,14 +68,9 @@ function UpdateUserJSON(New_Object = []){ ]; Players_Json = []; if (fs.existsSync(Player_Json_path)) Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8")); - if (Players_Json.version === undefined) { - Players_Json.version = 2; - let OldPlayers_Json = { - bedrock: [], - java: [], - pocketmine: [], - jsprismarine: [], - } + if (typeof Players_Json.map !== "function") { + let OldPlayers_Json = Players_Json; + Players_Json = []; OldPlayers_Json.bedrock.forEach(a=>Players_Json.push({ Player: a.Player, Action: a.Action, @@ -111,4 +106,4 @@ module.exports.Player_Search = function Player_Search(player = "dontSteve") { if (Player.Player === player.trim()) return Player; } return {}; -} \ No newline at end of file +} -- 2.49.0 From 6dc048ddcd486f305c064b7d7af2ccbbeb5f5113 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 19:20:41 -0300 Subject: [PATCH 3/7] Update Players_json.js --- src/ManegerServer/Players_json.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ManegerServer/Players_json.js b/src/ManegerServer/Players_json.js index de88c6a..e4069d9 100644 --- a/src/ManegerServer/Players_json.js +++ b/src/ManegerServer/Players_json.js @@ -1,7 +1,7 @@ const fs = require("fs"); const BdsSettings = require("../lib/BdsSettings"); -function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => {d}){ +function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: new Date()},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: new Date()}]) => console.log(d)){ const Current_platorm = BdsSettings.GetPlatform(); // Bedrock if (Current_platorm === "bedrock") { @@ -19,7 +19,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Action: Actions, Platform: Current_platorm, xuid: line.replace(/^.*,.*xuid:/gi, "").trim(), - Date: `${new Date()}`, + Date: new Date() } // Return @@ -43,7 +43,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Player: line.replace(/joined the game|left the game/gi, "").trim(), Action: Actions, Platform: Current_platorm, - Date: `${new Date()}`, + Date: new Date() } // Return JSON @@ -63,7 +63,7 @@ function UpdateUserJSON(New_Object = []){ Player: "Steve", Action: "connect", Platform: Current_platorm, - Date: `${new Date()}` + Date: new Date() } ]; Players_Json = []; -- 2.49.0 From 32d7bd7defa34bb89e80fb51969fd75857246f5a Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 19:27:05 -0300 Subject: [PATCH 4/7] Revert "Update Players_json.js" This reverts commit 6dc048ddcd486f305c064b7d7af2ccbbeb5f5113. --- src/ManegerServer/Players_json.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ManegerServer/Players_json.js b/src/ManegerServer/Players_json.js index e4069d9..de88c6a 100644 --- a/src/ManegerServer/Players_json.js +++ b/src/ManegerServer/Players_json.js @@ -1,7 +1,7 @@ const fs = require("fs"); const BdsSettings = require("../lib/BdsSettings"); -function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: new Date()},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: new Date()}]) => console.log(d)){ +function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => {d}){ const Current_platorm = BdsSettings.GetPlatform(); // Bedrock if (Current_platorm === "bedrock") { @@ -19,7 +19,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Action: Actions, Platform: Current_platorm, xuid: line.replace(/^.*,.*xuid:/gi, "").trim(), - Date: new Date() + Date: `${new Date()}`, } // Return @@ -43,7 +43,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Player: line.replace(/joined the game|left the game/gi, "").trim(), Action: Actions, Platform: Current_platorm, - Date: new Date() + Date: `${new Date()}`, } // Return JSON @@ -63,7 +63,7 @@ function UpdateUserJSON(New_Object = []){ Player: "Steve", Action: "connect", Platform: Current_platorm, - Date: new Date() + Date: `${new Date()}` } ]; Players_Json = []; -- 2.49.0 From 0dd88af85a86d4901842053b999b9beb716c38de Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 19:42:35 -0300 Subject: [PATCH 5/7] Push --- src/ManegerServer/Players_json.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ManegerServer/Players_json.js b/src/ManegerServer/Players_json.js index de88c6a..54e0314 100644 --- a/src/ManegerServer/Players_json.js +++ b/src/ManegerServer/Players_json.js @@ -1,7 +1,7 @@ const fs = require("fs"); const BdsSettings = require("../lib/BdsSettings"); -function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => {d}){ +function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => console.log(d)){ const Current_platorm = BdsSettings.GetPlatform(); // Bedrock if (Current_platorm === "bedrock") { @@ -19,7 +19,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Action: Actions, Platform: Current_platorm, xuid: line.replace(/^.*,.*xuid:/gi, "").trim(), - Date: `${new Date()}`, + Date: (new Date()).toString() } // Return @@ -43,7 +43,7 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn Player: line.replace(/joined the game|left the game/gi, "").trim(), Action: Actions, Platform: Current_platorm, - Date: `${new Date()}`, + Date: (new Date()).toString() } // Return JSON @@ -63,7 +63,7 @@ function UpdateUserJSON(New_Object = []){ Player: "Steve", Action: "connect", Platform: Current_platorm, - Date: `${new Date()}` + Date: (new Date()).toString() } ]; Players_Json = []; -- 2.49.0 From c5de6e9869fb16baed5e21a0765c40eff72ceda5 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Tue, 23 Nov 2021 20:41:19 -0300 Subject: [PATCH 6/7] Update api.js --- src/api.js | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/api.js b/src/api.js index bd0b621..4f784e4 100644 --- a/src/api.js +++ b/src/api.js @@ -286,23 +286,15 @@ app.get("/bds/bridge", (req, res) => { }); // ? /player -const GetPlayerJson = (Platform = BdsManegerCore.BdsSettings.GetJsonConfig().server.platform) => ([...{...JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettings.GetPaths("player"), "utf8"))}[Platform]]); app.get("/players", CheckToken, (req, res) => { - const { Platform = BdsSettings.GetPlatform(), Player = null, Action = null } = req.query; - let PlayerList = GetPlayerJson(Platform); + let PlayerList = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettings.GetPaths("player"), "utf8")) + const { Platform = null, Player = null, Action = null } = req.query; + + if (Platform) PlayerList = PlayerList.filter(PLS => PLS.Platform === Platform); if (Player) PlayerList = PlayerList.filter(PLS => PLS.Player === Player); if (Action) PlayerList = PlayerList.filter(PLS => PLS.Action === Action); - - if (Player || Action) { - if (PlayerList.length > 0) res.json(PlayerList); - else res.status(404).json({ - Error: "Player not found", - querys: req.query - }); - return; - } - res.json(PlayerList); - return; + + return res.json(PlayerList); }); // Players Actions in Backside Manager @@ -490,4 +482,4 @@ module.exports.TokensFilePath = path_tokens; module.exports.BdsRoutes = { App: app, Server: Server -}; \ No newline at end of file +}; -- 2.49.0 From e312a1ad06598285f229fcd32ea9b7da93657df4 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Queiroga Date: Wed, 24 Nov 2021 18:16:34 -0300 Subject: [PATCH 7/7] More Changes --- bin/BdsManeger.js | 10 ++-- bin/Docker.js | 4 +- src/BdsBackup.js | 26 ++++----- src/BdsManegerServer.js | 124 ++++++++++++++++++++++------------------ src/BdsNetwork.js | 103 +++++++++++++++------------------ src/api.js | 61 +++++++++++--------- 6 files changed, 167 insertions(+), 161 deletions(-) diff --git a/bin/BdsManeger.js b/bin/BdsManeger.js index cd57724..86e6eae 100644 --- a/bin/BdsManeger.js +++ b/bin/BdsManeger.js @@ -169,17 +169,17 @@ async function Runner() { if (!(ProcessArgs.start || ProcessArgs.s)) return; const BdsManegerServer = BdsCore.BdsManegerServer.StartServer(); - BdsManegerServer.log(data => process.stdout.write(cli_color.blueBright(data))); + BdsManegerServer.on("log", data => process.stdout.write(cli_color.blueBright(data))); if (!(ProcessArgs["no-api"])) BdsCore.BdsManegerAPI.api(); const __readline = readline.createInterface({input: process.stdin, output: process.stdout}); - __readline.on("line", data => BdsManegerServer.command(data)); + __readline.on("line", data => BdsManegerServer.SendCommand(data)); __readline.on("close", () => BdsManegerServer.stop()); // Get Temporary External Domain if (ProcessArgs.get_domain) { try { const HostInfo = await BdsCore.BdsNetwork.GetHost(); console.log("Domain:", HostInfo.host); - BdsManegerServer.exit(async () => await HostInfo.delete_host()); + BdsManegerServer.on("exit", async () => await HostInfo.delete_host()) process.on("exit", async () => { await HostInfo.delete_host(); console.log("Sucess remove host"); @@ -188,8 +188,8 @@ async function Runner() { console.log("Cannot get domain"); } } - BdsManegerServer.exit(code => { - console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsManegerServer.uptime}`)); + BdsManegerServer.on("exit", code => { + console.log(cli_color.redBright(`Bds Core Exit with code ${code}, Uptimed: ${BdsManegerServer.Uptime}`)); process.exit(code); }); } diff --git a/bin/Docker.js b/bin/Docker.js index a55e6fd..3e843a4 100755 --- a/bin/Docker.js +++ b/bin/Docker.js @@ -36,9 +36,9 @@ async function StartServer(){ ShowToken(); console.log("The entire log can be accessed via the api and/or the docker log"); const ServerStarted = BdsCore.BdsManegerServer.StartServer(); - ServerStarted.log(a => process.stdout.write(a)); - ServerStarted.exit(code => process.exit(code)); BdsCore.BdsManegerAPI.api(); + ServerStarted.on("log", a => process.stdout.write(a)); + ServerStarted.on("exit", code => process.exit(code)); if (process.env.PULL_REQUEST === "true") { console.log((require("cli-color")).red("Pull Request Actived 1 Min to exit")); setTimeout(() => { diff --git a/src/BdsBackup.js b/src/BdsBackup.js index 3f7d155..75cbec0 100644 --- a/src/BdsBackup.js +++ b/src/BdsBackup.js @@ -1,11 +1,11 @@ -const { join, resolve } = require("path"); +const path = require("path"); +const { join, resolve } = path; const fs = require("fs"); const AdmZip = require("adm-zip"); const { GetServerPaths, GetPaths, bds_dir } = require("../src/lib/BdsSettings"); -function Backup() { +function CreateBackup() { const zip = new AdmZip(); - console.info("Starting Bds Core Backup Along with the server maps, please wait"); // Names And Path"s const Paths = { bedrock: GetServerPaths("bedrock"), @@ -19,28 +19,28 @@ function Backup() { const PathBackup = join(GetPaths("backups"), ZipName); // Bedrock - if (fs.readdirSync(Paths.bedrock).filter(a=>/worlds/.test(a)).length >= 1) { + if (fs.readdirSync(Paths.bedrock).filter(a => /worlds/.test(a)).length >= 1) { zip.addLocalFolder(join(Paths.bedrock, "worlds"), join("Servers", "Bedrock", "worlds")); for (let index of ["server.properties", "permissions.json", "whitelist.json"]) {if (fs.existsSync(join(Paths.bedrock, index))) zip.addLocalFile(join(Paths.bedrock, index), join("Servers", "Bedrock"));} - } else console.info("Skipping the bedrock as it was not installed"); + } // Java if (fs.existsSync(join(Paths.java, "MinecraftServerJava.jar"))) { for (let index of fs.readdirSync(Paths.java).filter(value => !/banned-ips.json|banned-players.json|eula.txt|logs|ops.json|server.jar|MinecraftServerJava.jar|server.properties|usercache.json|whitelist.json/.test(value))) zip.addLocalFolder(join(Paths.java, index), join("Servers", "Java", index)); for (let index of ["banned-ips.json", "banned-players.json", "ops.json", "server.properties", "whitelist.json"]) {if (fs.existsSync(join(Paths.java, index))) zip.addLocalFile(join(Paths.java, index), join("Servers", "Java"))} - } else console.info("Skipping the java as it was not installed"); + } // PocketMine if (fs.existsSync(join(Paths.pocketmine, "PocketMine-MP.phar"))) { if (fs.existsSync(join(Paths.pocketmine, "worlds"))) zip.addLocalFolder(join(Paths.pocketmine, "worlds"), join("Servers", "pocketmine", "worlds")); for (let index of ["pocketmine.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.pocketmine, index))) zip.addLocalFile(join(Paths.pocketmine, index), "pocketmine"); - } else console.info("Skipping the pocketmine as it was not installed"); + } // Spigot if (fs.existsSync(join(Paths.spigot, "spigot.jar"))) { if (fs.existsSync(join(Paths.spigot, "worlds"))) zip.addLocalFolder(join(Paths.spigot, "worlds"), join("Servers", "spigot", "worlds")); for (let index of ["spigot.yml", "server.properties", "white-list.txt", "ops.txt", "banned-players.txt", "banned-ips.txt"]) if (fs.existsSync(join(Paths.spigot, index))) zip.addLocalFile(join(Paths.spigot, index), "spigot"); - } else console.info("Skipping the spigot as it was not installed"); + } // Dragonfly if (fs.existsSync(join(Paths.dragonfly, "config.toml"))) { @@ -48,7 +48,7 @@ function Backup() { if (fs.lstatSync(index).isDirectory()) zip.addLocalFolder(index, join("Servers", "dragonfly")); else if (fs.lstatSync(index).isFile()) zip.addLocalFile(index, join("Servers", "dragonfly")); } - } else console.info("Skipping the dragonfly as it was not installed"); + } // The Bds Maneger Core Backup for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (fs.existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index)); @@ -65,7 +65,6 @@ function Backup() { // Zip Buffer const ZipBuffer = zip.toBuffer(); fs.writeFileSync(PathBackup, ZipBuffer, "binary"); - console.log("Backup Complete"); return { file_path: PathBackup, Buffer: ZipBuffer, @@ -74,7 +73,8 @@ function Backup() { } module.exports = { - World_BAckup: Backup, - Backup: Backup, - Cloud_backup: Backup + CreateBackup: CreateBackup, + Backup: CreateBackup, + World_BAckup: CreateBackup, + Cloud_backup: CreateBackup } \ No newline at end of file diff --git a/src/BdsManegerServer.js b/src/BdsManegerServer.js index de339f5..9fe355c 100644 --- a/src/BdsManegerServer.js +++ b/src/BdsManegerServer.js @@ -128,90 +128,102 @@ module.exports.StartServer = function start() { global.bds_log_string = "" ServerExec.stdout.on("data", data => {if (global.bds_log_string) global.bds_log_string = data; else global.bds_log_string += data}); - // sets bds core commands - const log = function (logCallback){ - if (typeof logCallback !== "function") throw new Error("Log Callback is not a function"); - ServerExec.stdout.on("data", data => logCallback(data)); - ServerExec.stderr.on("data", data => logCallback(data)); + /** + * Emit command in to the server + * + * @param {string} command + * @param {Array} command + */ + const ServerCommand = function (Command = "list") { + if (!(typeof Command === "string" || typeof Command === "object" && typeof Command.map === "function")) throw new Error("Command must be a string or an array"); + if (typeof Command === "string") { + ServerExec.stdin.write(`${Command}\n`); + } else if (typeof Command === "object" && typeof Command.map === "function") { + Command.filter(a => typeof a === "string").forEach(command => ServerExec.stdin.write(`${command}\n`)); + } + return; }; - const exit = function (exitCallback = process.exit){if ( - typeof exitCallback === "function") ServerExec.on("exit", code => exitCallback(code)); - }; - const on = function(action = String, callback = Function) { - if (!(action === "all" || action === "connect" || action === "disconnect")) throw new Error("Use some valid action: all, connect, disconnect"); - - // Functions - const data = data => PlayerJson.UpdateUserJSON(data, function (array_status){ - array_status.filter(On => {if ("all" === action || On.Action === action) return true; else return false;}).forEach(_player => callback(_player)) + /** + * When a player connects or disconnects, the server will issue an event. + * + * @param {string} Action - The event to listen for. + * @param {function} Callback - The callback to run when the event is triggered. + */ + const PlayerAction = function(Action = "all", callback = (PlayerActions = [{Player: "", Action: "connect", Platform: "", xuid: "", Date: ""},{Player: "", Action: "disconnect", Platform: "", xuid: "", Date: ""}]) => console.log(PlayerActions)){ + if (!(Action === "all" || Action === "connect" || Action === "disconnect")) throw new Error("Use some valid Action: all, connect, disconnect"); + const { CreatePlayerJson } = PlayerJson; + const RunON = data => CreatePlayerJson(data, (PlayerActions) => { + if (Action !== "all") PlayerActions = PlayerActions.filter(On => On.Action === Action); + return callback(PlayerActions); }); - ServerExec.stdout.on("data", data); - ServerExec.stderr.on("data", data); + ServerExec.stdout.on("data", RunON); + ServerExec.stderr.on("data", RunON); + return; }; - const command = function (command = "list") { - ServerExec.stdin.write(`${command}\n`); - return command; - }; - - const BasicCo = BasicCommands.BasicCommands(ServerExec); + /** + * Register a function to run when the server issues a log or when it exits. + * + * @param {string} FunctionAction - Action to Register to run callback + * @callback + */ + const ServerOn = function (FunctionAction = "log", callback = (data = FunctionAction === "log" ? "" : 0) => console.log(data)) { + if (!(FunctionAction === "log" || FunctionAction === "exit")) throw new Error("Use some valid FunctionAction: log, exit"); + if (FunctionAction === "log") { + ServerExec.stdout.on("data", data => callback(data)); + ServerExec.stderr.on("data", data => callback(data)); + } else if (FunctionAction === "exit") ServerExec.on("exit", code => callback(code)); + else throw new Error("Use some valid FunctionAction: log, exit"); + return; + } // Mount commands to Return const returnFuntion = { uuid: randomUUID(), LogPath: LogFile, - pid: ServerExec.pid, - uptime: 0, - StartTime: (new Date()), - ...BasicCo, - command, log, exit, on + PID: ServerExec.pid, + Uptime: 0, + StartTime: new Date(), + on: ServerOn, + PlayerAction: PlayerAction, + SendCommand: ServerCommand, + ...(BasicCommands.BasicCommands(ServerExec)) } // Uptime Server - const OnStop = setInterval(() => returnFuntion.uptime = (new Date().getTime() - returnFuntion.StartTime.getTime()) / 1000, 1000); - ServerExec.on("exit", () => { + const UptimeCount = setInterval(() => returnFuntion.Uptime++, 1000); + ServerExec.on("exit", code => { delete ServerSessions[returnFuntion.uuid] - clearInterval(OnStop); + io.emit("ServerExit", { + UUID: returnFuntion.uuid, + exitCode: code + }) + clearInterval(UptimeCount); }); // Socket.io io.on("connection", socket => { socket.on("ServerCommand", (data) => { - if (typeof data === "string") return returnFuntion.command(data); + if (typeof data === "string") return returnFuntion.SendCommand(data); else if (typeof data === "object") { if (typeof data.uuid === "string") { - if (data.uuid === returnFuntion.uuid) return returnFuntion.command(data.command); + if (data.uuid === returnFuntion.uuid) return returnFuntion.SendCommand(data.command); } } return; }); }); - ServerExec.on("exit", code => io.emit("ServerExit", { - UUID: returnFuntion.uuid, - exitCode: code - })); - ServerExec.stdout.on("data", (data = "") => { + + ServerOn("log", data => { io.emit("ServerLog", { UUID: returnFuntion.uuid, - data: data, - IsStderr: false + data: data + }); + PlayerJson.CreatePlayerJson(data, Actions => { + if (Actions.length === 0) return; + PlayerJson.UpdateUserJSON(Actions); + io.emit("PlayerAction", Actions); }); }); - ServerExec.stderr.on("data", (data = "") => { - io.emit("ServerLog", { - UUID: returnFuntion.uuid, - data: data, - IsStderr: true - }); - }); - - // Player JSON File - ServerExec.stdout.on("data", data => PlayerJson.CreatePlayerJson(data, Actions => { - PlayerJson.UpdateUserJSON(Actions); - io.emit("PlayerAction", Actions); - })); - ServerExec.stderr.on("data", data => PlayerJson.CreatePlayerJson(data, Actions => { - PlayerJson.UpdateUserJSON(Actions); - io.emit("PlayerAction", Actions); - })); // Return ServerSessions[returnFuntion.uuid] = returnFuntion; diff --git a/src/BdsNetwork.js b/src/BdsNetwork.js index ba2c277..e26ead1 100644 --- a/src/BdsNetwork.js +++ b/src/BdsNetwork.js @@ -6,59 +6,49 @@ function LocalInterfaces() { const interfaces = os.networkInterfaces(); const localInterfaces = []; for (const name of Object.getOwnPropertyNames(interfaces)) { - const Inter = { - interfaceName: name, - mac: "", - v4: { - addresses: "", - netmask: "", - cidr: "" - }, - v6: { - addresses: "", - netmask: "", - cidr: "" - }, - }; - for (let iface of interfaces[name]) { - if (!Inter.mac && iface.mac) Inter.mac = iface.mac; - if (iface.family === "IPv4") { - Inter.v4.addresses = iface.address; - Inter.v4.netmask = iface.netmask; - Inter.v4.cidr = iface.cidr; - } else if (iface.family === "IPv6") { - Inter.v6.addresses = iface.address; - Inter.v6.netmask = iface.netmask; - Inter.v6.cidr = iface.cidr; + const Inter = { + interfaceName: name, + mac: "", + v4: { + addresses: "", + netmask: "", + cidr: "" + }, + v6: { + addresses: "", + netmask: "", + cidr: "" + }, + }; + for (let iface of interfaces[name]) { + if (!Inter.mac && iface.mac) Inter.mac = iface.mac; + if (iface.family === "IPv4") { + Inter.v4.addresses = iface.address; + Inter.v4.netmask = iface.netmask; + Inter.v4.cidr = iface.cidr; + } else if (iface.family === "IPv6") { + Inter.v6.addresses = iface.address; + Inter.v6.netmask = iface.netmask; + Inter.v6.cidr = iface.cidr; + } } - } - if (!(interfaces[name][0].internal)) localInterfaces.push(Inter); + if (!(interfaces[name][0].internal)) localInterfaces.push(Inter); } return localInterfaces; } async function GetExternalPublicAddress() { const ExternlIPs = { - ipv4: null, - ipv6: null + ipv4: null, + ipv6: null } - ExternlIPs["ipv4"] = (await Request.TEXT("https://api.ipify.org")).replace("\n", "") + ExternlIPs["ipv4"] = (await Request.TEXT("https://api.ipify.org/")).replace("\n", "") ExternlIPs["ipv6"] = (await Request.TEXT("https://api64.ipify.org/")).replace("\n", "") if (ExternlIPs["ipv6"] === ExternlIPs["ipv4"]) ExternlIPs["ipv6"] = null; return ExternlIPs; } - -Request.TEXT("https://api.ipify.org").then(external_ipv4 => { - Request.TEXT("https://api64.ipify.org/").then(external_ipv6 => { - const externalIP = { - ipv4: external_ipv4.replace("\n", ""), - ipv6: external_ipv6.replace("\n", "") - } - - module.exports.externalIP = externalIP; - module.exports.ip = externalIP; - }); -}); +module.exports.externalIP = {ipv4: "", ipv6: ""}; +GetExternalPublicAddress().then(ExternlIPs => module.exports.externalIP = ExternlIPs); // Internal ip user const interfaces = os.networkInterfaces(); @@ -99,24 +89,24 @@ async function GetHost() { const ExternalAddress = (await GetExternalPublicAddress()).ipv4; const RequestUpstream = await fetch(`https://upstream.bdsmaneger.com/v1/public_domain?MacAddress=${JSON.stringify(MacAddr)}&ExternalAdress=${ExternalAddress}`, {mode: "cors"}); if (!RequestUpstream.ok) { - throw { - Backend: await RequestUpstream.json() - } + throw { + Backend: await RequestUpstream.json() + } } const HostInfo = await RequestUpstream.json(); const _toReturn = { - host: "", - UpstreamID: "", - delete_host: async () => { - const RequestDeleteHost = await fetch("https://upstream.bdsmaneger.com/v1/public_domain", { - method: "DELETE", - mode: "cors", - body: JSON.stringify({ - UUID: HostInfo.ID - }) - }); - return await RequestDeleteHost.json(); - } + host: "", + UpstreamID: "", + delete_host: async () => { + const RequestDeleteHost = await fetch("https://upstream.bdsmaneger.com/v1/public_domain", { + method: "DELETE", + mode: "cors", + body: JSON.stringify({ + UUID: HostInfo.ID + }) + }); + return await RequestDeleteHost.json(); + } } _toReturn["host"] = HostInfo.host.host _toReturn["UpstreamID"] = HostInfo.ID @@ -128,6 +118,5 @@ module.exports = { Interfaces, LocalInterfaces, GetExternalPublicAddress, - host: null, GetHost } diff --git a/src/api.js b/src/api.js index 4f784e4..5487521 100644 --- a/src/api.js +++ b/src/api.js @@ -160,7 +160,7 @@ app.get(["/bds/log", "/log"], CheckToken, (req, res) => { try { return { UUID: session, - data: fs.readFileSync(Sessions[session].LogPath, "utf8").replaceAll("\r\n", "\n").split("\n") + data: fs.readFileSync(Sessions[session].LogPath, "utf8").replace(/\r\n/gi, "\n").split("\n") }; } catch (err) { return { @@ -173,34 +173,39 @@ app.get(["/bds/log", "/log"], CheckToken, (req, res) => { // Server Info app.get("/bds/info/server", ({res}) => { - let ServerRunner = require("./BdsManegerServer").BdsRun; - if (!ServerRunner)ServerRunner = {}; - try { - const BdsConfig = BdsManegerCore.BdsSettings.GetJsonConfig(); - const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettings.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()]; - const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player))); - const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1))) - const Info = { - version: BdsConfig.server.versions[BdsSettings.GetPlatform()], - Platform: BdsSettings.GetPlatform(), - players: { - online: Online.length, - offline: Offline.length, - }, - Config: BdsManegerCore.BdsSettings.GetJsonConfig(), - Process: { - PID: ServerRunner.pid || 0, - Uptime: ServerRunner.uptime || 0, - StartTime: ServerRunner.StartTime || NaN, - } - } - res.json(Info); - } catch (error) { - res.status(500).json({ - error: "Backend Error", - message: `${error}` - }); + const ServerSessions = require("./BdsManegerServer").GetSessions(); + const ServerRunner = Object.keys(ServerSessions).map(session => ServerSessions[session]).map(a => ({ + UUID: a.uuid || "", + PID: a.PID || 0, + Uptime: a.Uptime || 0, + StartTime: a.StartTime || NaN + })); + const BdsConfig = BdsManegerCore.BdsSettings.GetJsonConfig(); + const Players = JSON.parse(fs.readFileSync(BdsManegerCore.BdsSettings.GetPaths("player"), "utf8"))[BdsSettings.GetPlatform()]; + const Offline = Players.filter(player => player.Action === "disconnect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player))); + const Online = Players.filter(player => player.Action === "connect").filter((thing, index, self) => index === self.findIndex((t) => (t.place === thing.place && t.Player === thing.Player && Offline.findIndex((t) => (t.place === thing.place && t.Player === thing.Player)) === -1))) + + // Delete Info + delete BdsConfig.telegram; + delete BdsConfig.cloud; + + const Info = { + version: BdsConfig.server.versions[BdsSettings.GetPlatform()], + Platform: BdsSettings.GetPlatform(), + players: { + online: Online.length, + offline: Offline.length, + }, + Config: BdsConfig, + Process: ServerRunner } + return res.json(Info); +}); + +// Create Backup +app.get("/bds/backup", CheckToken, ({res}) => { + const BackupBuffer = BdsManegerCore.BdsBackup.CreateBackup(); + return res.send(BackupBuffer.Buffer); }); // Download Server -- 2.49.0