Temp commit

This commit is contained in:
oitsjustjose 2025-06-13 20:05:07 -05:00
commit 57f71eb0b9
10 changed files with 111 additions and 14 deletions

1
.gitignore vendored
View file

@ -1 +1,2 @@
.venv
__pycache__

12
.vscode/launch.json vendored Normal file
View file

@ -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"]
}
]
}

11
Dockerfile Normal file
View file

@ -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"]

1
README.md Normal file
View file

@ -0,0 +1 @@
# A Python API for Docker MC Servers

16
requirements.txt Normal file
View file

@ -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

View file

View file

@ -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")

View file

@ -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),
)
)

View file

@ -2,7 +2,6 @@ import struct
import socket
import base64
import json
import sys
class Server:

25
src/server.py Normal file
View file

@ -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