65 lines
3.0 KiB
Python
65 lines
3.0 KiB
Python
import uuid
|
||
from datetime import datetime
|
||
from fastapi import HTTPException
|
||
from typing import Dict
|
||
|
||
# Глобальное хранилище команд (в реальном проекте используйте БД)
|
||
pending_commands: Dict[str, Dict] = {}
|
||
|
||
class CommandService:
|
||
async def add_command(self, command_data):
|
||
try:
|
||
command_id = str(uuid.uuid4())
|
||
pending_commands[command_id] = {
|
||
"command": command_data.command,
|
||
"server_ip": command_data.server_ip,
|
||
"require_online_player": command_data.require_online_player,
|
||
"target_message": command_data.target_message if hasattr(command_data, 'target_message') else None,
|
||
"global_message": command_data.global_message if hasattr(command_data, 'global_message') else None,
|
||
"created_at": datetime.now().isoformat()
|
||
}
|
||
print(f"[{datetime.now()}] Добавлена команда: {command_data.command} "
|
||
f"для сервера {command_data.server_ip}")
|
||
|
||
# Обновляем last_activity для сервера
|
||
await self._update_server_activity(command_data.server_ip)
|
||
|
||
return {"status": "success", "command_id": command_id}
|
||
except Exception as e:
|
||
raise HTTPException(status_code=400, detail=str(e))
|
||
|
||
async def get_commands(self, server_ip: str):
|
||
try:
|
||
# Получаем команды для указанного сервера
|
||
commands = [
|
||
{
|
||
"id": cmd_id,
|
||
"command": cmd["command"],
|
||
"require_online_player": cmd["require_online_player"],
|
||
"target_message": cmd.get("target_message"),
|
||
"global_message": cmd.get("global_message")
|
||
}
|
||
for cmd_id, cmd in pending_commands.items()
|
||
if cmd["server_ip"] == server_ip
|
||
]
|
||
|
||
# Удаляем полученные команды (чтобы не выполнять их повторно)
|
||
for cmd_id in list(pending_commands.keys()):
|
||
if pending_commands[cmd_id]["server_ip"] == server_ip:
|
||
del pending_commands[cmd_id]
|
||
|
||
return {"status": "success", "commands": commands}
|
||
except Exception as e:
|
||
raise HTTPException(status_code=400, detail=str(e))
|
||
|
||
async def _update_server_activity(self, server_ip):
|
||
"""Обновляет время последней активности для сервера"""
|
||
from app.db.database import db
|
||
game_servers_collection = db.game_servers
|
||
|
||
await game_servers_collection.update_one(
|
||
{"ip": server_ip},
|
||
{"$set": {"last_activity": datetime.utcnow()}},
|
||
upsert=False # Не создаем новый сервер, только обновляем существующий
|
||
)
|