diff --git a/.gitignore b/.gitignore index ed8ebf5..0e5ac79 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +.venv __pycache__ \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..7b37cb3 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,12 @@ +{ + "version": "0.1.0", + "configurations": [ + { + "name": "Python:Flask", + "type": "debugpy", + "request": "launch", + "module": "streamlit", + "args": ["run", "src/main.py", "--server.headless", "true"] + } + ] +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c2b74b6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.10-buster + +RUN apt-get update && apt-get upgrade -y + +COPY . . + +RUN pip install -r requirements.txt + +WORKDIR /src + +CMD ["python", "src/__main__.py"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..30045d2 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# A Python API for Docker MC Servers diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..387f4c3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +asyncio==3.4.3 +blinker==1.9.0 +certifi==2025.4.26 +charset-normalizer==3.4.2 +click==8.2.1 +docker==7.1.0 +Flask==3.1.1 +flask-cors==6.0.1 +idna==3.10 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.2 +requests==2.32.4 +urllib3==2.4.0 +websockets==15.0.1 +Werkzeug==3.1.3 diff --git a/ws.py b/src/__.py similarity index 100% rename from ws.py rename to src/__.py diff --git a/api.py b/src/__main__.py similarity index 70% rename from api.py rename to src/__main__.py index edfb609..1f4ca3d 100644 --- a/api.py +++ b/src/__main__.py @@ -10,21 +10,23 @@ from common import get_server_info app = Flask(__name__) CORS(app) + @app.route("/") def index(): try: - data = get_server_info(all=request.args.get('all')) + data = get_server_info(all=request.args.get("all")) - if request.args.get('sortedOnKey'): - data = sorted(data, key=lambda x: x[request.args.get('sortedOnKey')]) + if request.args.get("sort"): + data = sorted(data, key=lambda x: x[request.args.get("sort")]) resp = jsonify(data) resp.status_code = 200 return resp except KeyError as e: - resp = jsonify({ "error": f"Failed to find key {str(e)}" }) + resp = jsonify({"error": f"Failed to find key {str(e)}"}) resp.status_code = 422 return resp + if __name__ == "__main__": - app.run(host='0.0.0.0') + app.run(host="0.0.0.0") diff --git a/common.py b/src/common.py similarity index 83% rename from common.py rename to src/common.py index 51e3ed1..efad8d3 100644 --- a/common.py +++ b/src/common.py @@ -3,14 +3,16 @@ Author: Jose Stovall Description: Common utilities used to fetch current server statuses """ -import docker import base64 -import json + +import docker import requests + from ping import ping as ping_server client = docker.from_env() + def __parse_log(log: str) -> dict: """ Gets the Game Version, MOTD, Online and Max Count from the server's log string @@ -24,7 +26,30 @@ def __parse_log(log: str) -> dict: "motd": str """ - FORMAT_CODES = ["§0", "§1", "§2", "§3", "§4", "§5", "§6", "§7", "§8", "§9", "§a", "§b", "§c", "§d", "§e", "§f", "§o", "§l", "§m", "§n", "§o", "§r"] + FORMAT_CODES = [ + "§0", + "§1", + "§2", + "§3", + "§4", + "§5", + "§6", + "§7", + "§8", + "§9", + "§a", + "§b", + "§c", + "§d", + "§e", + "§f", + "§o", + "§l", + "§m", + "§n", + "§o", + "§r", + ] KEYS = ["version", "online", "max", "motd"] log = log.replace("localhost:25565 : ", "") for cd in FORMAT_CODES: @@ -35,7 +60,7 @@ def __parse_log(log: str) -> dict: start = log.find(key) + len(key) end = 0 try: - end = log.index(KEYS[idx+1]) + end = log.index(KEYS[idx + 1]) except IndexError: end = len(log) except ValueError: @@ -45,6 +70,7 @@ def __parse_log(log: str) -> dict: ret[key] = value return ret + def __get_type(env: list) -> str: """ Gets the type of MC Server currently hosted based on the Environment variables @@ -90,7 +116,9 @@ def __extract_info(attrs: dict) -> dict: for binding in attrs["HostConfig"]["PortBindings"][key]: try: data = ping_server("localhost", port=int(binding["HostPort"])) - if not data: # Hmm, it's a minecraft container but not a minecraft server port? might be dynmap: + if ( + not data + ): # Hmm, it's a minecraft container but not a minecraft server port? might be dynmap: # dynmap = find_dynmap(int(binding["HostPort"])) host_port = int(binding["HostPort"]) request = requests.get(f"http://172.16.1.4:7070/{host_port}") @@ -110,12 +138,13 @@ def __extract_info(attrs: dict) -> dict: "health": attrs["State"]["Health"]["Status"], "players": players, "icon": str(base64.b64encode(icon).decode()) if icon else None, - "dynmap": dynmap + "dynmap": dynmap, } info.update(__parse_log(attrs["State"]["Health"]["Log"][-1]["Output"])) return info + def get_server_info(all: bool = False): """ Distills the container data for all servers on the current host into a usable format @@ -126,8 +155,9 @@ def get_server_info(all: bool = False): """ containers = list( filter( - lambda x: "itzg/minecraft-server" in x.attrs['Config']['Image'] and "net.forgeserv.hide" not in x.labels, - client.containers.list(all=all) + lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] + and "net.forgeserv.hide" not in x.labels, + client.containers.list(all=all), ) ) diff --git a/ping.py b/src/ping.py similarity index 99% rename from ping.py rename to src/ping.py index 43606f8..f98d5ce 100644 --- a/ping.py +++ b/src/ping.py @@ -2,7 +2,6 @@ import struct import socket import base64 import json -import sys class Server: diff --git a/src/server.py b/src/server.py new file mode 100644 index 0000000..ba0c19e --- /dev/null +++ b/src/server.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass +from typing import Union, List + + +@dataclass +class Player: + pass + + +@dataclass +class Server: + dynmap: Union[str, None] + health: str + icon: str + + motd: str + name: str + + online: int + max: int + players: List[Player] + + status: str + type: str + version: str