minecraftd/util.py
2025-12-02 23:09:18 +01:00

47 lines
1.5 KiB
Python

from asyncio import sleep
from typing import Callable
from fastapi import HTTPException
from classes import ProcessStatus
from config import Config
from controllers import Controllers
async def stop_server(
action: str, countdown: int, reason: str, timeout: int, then: Callable | None = None
):
"""Warns the players, stops the Server, and kills its process if its taking too long.
Parameters:
action (str): Action to write in the warning ("SERVER IS {action}...").
countdown (int): Seconds to wait after the warning.
reason: (str): The reason for the Server shutdown.
timeout (int): Seconds to wait before killing the process.
then (Callable | None) (default: None): Function to be called after the Server is stopped.
"""
if countdown:
Controllers.server.command(f"say SERVER IS {action} IN {countdown} SECONDS!!!")
Controllers.server.command(f"say REASON: '{reason}'")
while countdown > 0 and Controllers.server.status().get("players", {}).get(
"online", 0
):
await sleep(1)
countdown -= 1
Controllers.server.command("stop")
while timeout > 0 and Controllers.process.status() == ProcessStatus.RUNNING:
await sleep(1)
timeout -= 1
if Controllers.process.status() == ProcessStatus.RUNNING:
Controllers.process.kill()
if then:
then()
def check_password(password: str):
if password != Config.MINECRAFTD_PASSWORD:
raise HTTPException(401, "Password is invalid")