feat: complete React + Flask rebuild of dashboard
Backend: - New Flask 3 app with service-layer architecture - Pydantic v2 models and unified API response format - psycopg3 connection pool with stored procedure support - 14 services: DB, SSH, K8s, BGD, RMQ (admin + game), realtime, player, economy, guild, world, progression, character, audit, chat - 30+ API endpoints covering players, guilds, economy, world, admin, server, files, director, chat - SSE real-time events for battlegroup, chat, metrics, connection status - SocketIO remote shell (xterm.js compatible) - Settings CRUD, moderation (ban/kick/unban), audit logging - Security: CSRF, rate limiting, CSP, HSTS, read-only SQL enforcement Frontend: - Vite + React 18 + TypeScript + Tailwind CSS - 14 Dune house themes via CSS custom properties - SWR for server state, Axios API client with interceptors - 14 pages: Overview, Player Explorer + Detail, Guild Manager, Vehicles, Buildings, Map Viewer, Accounts, Server Control, Admin Tools (7 tabs), Chat Monitor, Remote Shell, File Browser, Director, Settings - Player Detail with 6 tabs: overview, inventory, vehicles, buildings, progression, actions - Admin Tools: broadcast, economy, world, character, functions, raw query, audit log - Interactive canvas map viewer with zoom/pan/filter - Toast notifications, connection badges, theme switcher Other: - Updated .gitignore for frontend/backend structure - Updated README with new architecture, development guide, and project structure - Legacy app/ templates/ static/ remain untouched
This commit is contained in:
1 parent
fa620f4da9
commit
be845f76f1
76 files changed
+8410
-10
No files matched your search
@@ -0,0 +1 @@
|
||||
# Services package init.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Audit logging service — persistent PostgreSQL storage.
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AuditService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def log(self, action: str, user: str, details: dict | None = None,
|
||||
target_player_id: int | None = None, severity: str = "info",
|
||||
source_ip: str | None = None) -> bool:
|
||||
try:
|
||||
self.db.execute_mutation(
|
||||
"""INSERT INTO dashboard.audit_log
|
||||
(action_type, user_name, target_player_id, details, source_ip, severity, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, NOW())""",
|
||||
[action, user, target_player_id, details or {}, source_ip, severity],
|
||||
)
|
||||
logger.info("Audit: %s by %s", action, user)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("Audit log failed: %s", e)
|
||||
return False
|
||||
|
||||
def get_logs(self, action: str | None = None, user: str | None = None,
|
||||
target_player_id: int | None = None, limit: int = 100,
|
||||
offset: int = 0) -> list[dict]:
|
||||
sql = """SELECT id, action_type, user_name, target_player_id, details,
|
||||
source_ip, severity, created_at
|
||||
FROM dashboard.audit_log WHERE 1=1"""
|
||||
params = []
|
||||
if action:
|
||||
sql += " AND action_type = %s"
|
||||
params.append(action)
|
||||
if user:
|
||||
sql += " AND user_name = %s"
|
||||
params.append(user)
|
||||
if target_player_id:
|
||||
sql += " AND target_player_id = %s"
|
||||
params.append(target_player_id)
|
||||
sql += " ORDER BY created_at DESC LIMIT %s OFFSET %s"
|
||||
params.extend([limit, offset])
|
||||
return self.db.execute_readonly(sql, params)
|
||||
|
||||
def get_stats(self) -> dict:
|
||||
rows = self.db.execute_readonly(
|
||||
"""SELECT action_type, COUNT(*) as cnt FROM dashboard.audit_log
|
||||
GROUP BY action_type"""
|
||||
)
|
||||
return {r["action_type"]: r["cnt"] for r in rows}
|
||||
|
||||
def cleanup_old(self, days: int = 90) -> int:
|
||||
result = self.db.execute_mutation(
|
||||
"DELETE FROM dashboard.audit_log WHERE created_at < NOW() - INTERVAL '%s days'",
|
||||
[days],
|
||||
)
|
||||
logger.info("Audit cleanup: removed %d entries older than %d days", result, days)
|
||||
return result
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Battlegroup Director HTTP API client."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
|
||||
import httpx
|
||||
|
||||
from app.models import BattlegroupState, ErrorDetail
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BgDirectorService:
|
||||
def __init__(self, host: str, node_port: int):
|
||||
self.base_url = f"http://{host}:{node_port}"
|
||||
self.client = httpx.Client(base_url=self.base_url, timeout=15)
|
||||
logger.debug("BgDirectorService initialized: %s", self.base_url)
|
||||
|
||||
def _request(self, method: str, path: str, data: Any = None, timeout: int = 15) -> dict | str:
|
||||
try:
|
||||
if method == "GET":
|
||||
resp = self.client.get(path, timeout=timeout)
|
||||
else:
|
||||
if isinstance(data, str):
|
||||
resp = self.client.request(method, path, content=data, headers={"Content-Type": "application/json"}, timeout=timeout)
|
||||
else:
|
||||
resp = self.client.request(method, path, json=data, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
if resp.headers.get("content-type", "").startswith("application/json"):
|
||||
return resp.json()
|
||||
return resp.text
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error("BGD HTTP error %s %s: %s", method, path, e)
|
||||
raise DirectorUnavailableError(f"BGD returned {e.response.status_code}")
|
||||
except httpx.ConnectError as e:
|
||||
logger.error("BGD connection error %s %s: %s", method, path, e)
|
||||
raise DirectorUnavailableError("The Battlegroup Director is not responding. Check BGD pod logs.")
|
||||
except Exception as e:
|
||||
logger.error("BGD request error %s %s: %s", method, path, e)
|
||||
raise DirectorUnavailableError(str(e))
|
||||
|
||||
# ── Player Endpoints ──────────────────────────────────────────
|
||||
|
||||
def get_battlegroup(self) -> BattlegroupState:
|
||||
data = self._request("GET", "/v0/battlegroup", timeout=15)
|
||||
if isinstance(data, str):
|
||||
data = json.loads(data)
|
||||
return _parse_battlegroup(data)
|
||||
|
||||
def get_all_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def get_online_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players/online")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def get_intransit_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players/intransit")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def get_graceperiod_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players/graceperiod")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def get_completion_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players/completion")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def get_queued_players(self) -> list[str]:
|
||||
data = self._request("GET", "/v0/players/queued")
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
# ── FLS Settings ───────────────────────────────────────────────
|
||||
|
||||
def get_fls_settings(self) -> dict:
|
||||
return self._request("GET", "/v0/BattlegroupFetchFlsReportSettings")
|
||||
|
||||
def update_fls_settings(self, settings: dict) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupUpdateFlsReportSettings", data=settings, timeout=30)
|
||||
|
||||
def clear_fls_overrides(self) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupClearFlsReportOverrides", timeout=30)
|
||||
|
||||
# ── Server Config ──────────────────────────────────────────────
|
||||
|
||||
def update_server_config(self, config: dict) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupUpdateServerGroupConfig", data=config, timeout=30)
|
||||
|
||||
def clear_map_config(self, map_name: str) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupClearMapConfigOverrides", data=map_name, timeout=30)
|
||||
|
||||
# ── Character Transfer ──────────────────────────────────────────
|
||||
|
||||
def get_transfer_rules(self) -> dict:
|
||||
return self._request("GET", "/v0/BattlegroupFetchCharacterTransferRules")
|
||||
|
||||
def update_transfer_settings(self, config: dict) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupUpdateCharacterTransferSettings", data=config, timeout=30)
|
||||
|
||||
def clear_transfer_overrides(self) -> str:
|
||||
return self._request("POST", "/v0/BattlegroupClearCharacterTransferOverrides", timeout=30)
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
|
||||
class DirectorUnavailableError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _parse_battlegroup(data: dict) -> BattlegroupState:
|
||||
"""Parse raw BGD JSON into BattlegroupState model."""
|
||||
state = BattlegroupState()
|
||||
|
||||
for key in ["dimensionMaps", "singleServerMaps", "instancedMaps"]:
|
||||
if key in data:
|
||||
target = "dimension_maps" if key == "dimensionMaps" else "single_server_maps" if key == "singleServerMaps" else "instanced_maps"
|
||||
for mg in data[key]:
|
||||
group = {"name": mg.get("name", ""), "servers": []}
|
||||
for sv in mg.get("servers", []):
|
||||
sst = sv.get("lastServerState", {})
|
||||
sgs = sst.get("serverGameplaySettings", {})
|
||||
server = {
|
||||
"partition": sv.get("partition", ""),
|
||||
"ip": sv.get("ip", ""),
|
||||
"game_port": sv.get("gamePort", 7777),
|
||||
"num_players": sv.get("numPlayers", 0),
|
||||
"status": sv.get("status", "unknown"),
|
||||
"hydration": sgs.get("hydration", 1.0),
|
||||
"sandstorm": sgs.get("sandstorm", False),
|
||||
"sandworm": sgs.get("sandworm", True),
|
||||
"pvp_enabled": sgs.get("pvpEnabled", False),
|
||||
"mining_multiplier": sgs.get("miningMultiplier", 1.0),
|
||||
"durability": sgs.get("durability", 1.0),
|
||||
}
|
||||
group["servers"].append(server)
|
||||
getattr(state, target).append(group)
|
||||
|
||||
return state
|
||||
@@ -0,0 +1,50 @@
|
||||
# Character service — rename, delete, demo, cheater flags using DB functions.
|
||||
|
||||
import logging
|
||||
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CharacterService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def rename(self, account_id: int, name: str) -> bool:
|
||||
self.db.call_procedure("set_character_name", [account_id, name])
|
||||
return True
|
||||
|
||||
def delete_character(self, actor_id: int) -> bool:
|
||||
self.db.call_procedure("delete_character", [actor_id])
|
||||
return True
|
||||
|
||||
def delete_account(self, user_id: str, reason: str = "admin") -> bool:
|
||||
self.db.call_procedure("delete_account", [user_id, reason])
|
||||
return True
|
||||
|
||||
def set_demo(self, user_id: str, state: str) -> bool:
|
||||
self.db.call_procedure("set_demo_state", [user_id, state])
|
||||
return True
|
||||
|
||||
def flag_cheater(self, account_id: int, cheat_type: str) -> bool:
|
||||
self.db.call_procedure("flag_player_as_cheater", [account_id, cheat_type])
|
||||
return True
|
||||
|
||||
def get_tags(self, account_id: int) -> list[str]:
|
||||
rows = self.db.call_function("admin_read_player_tags", [account_id])
|
||||
return [r.get("tag", "") for r in rows if r.get("tag")]
|
||||
|
||||
def update_tags(self, account_id: int, add: list[str], remove: list[str]) -> bool:
|
||||
# DB-ONLY direct SQL — no function exists for tag management
|
||||
for tag in add:
|
||||
self.db.execute_mutation(
|
||||
"INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
||||
[account_id, tag],
|
||||
)
|
||||
if remove:
|
||||
self.db.execute_mutation(
|
||||
"DELETE FROM dune.player_tags WHERE account_id = %s AND tag = ANY(%s)",
|
||||
[account_id, remove],
|
||||
)
|
||||
return True
|
||||
@@ -0,0 +1,148 @@
|
||||
# Chat service — chat history and log parsing.
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, db: DatabaseService, k8s_service, ssh_service):
|
||||
self.db = db
|
||||
self.k8s = k8s_service
|
||||
self.ssh = ssh_service
|
||||
self.ensured_table = False
|
||||
|
||||
def ensure_history_table(self):
|
||||
if self.ensured_table:
|
||||
return True
|
||||
try:
|
||||
self.db.execute_mutation("""
|
||||
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
|
||||
id SERIAL PRIMARY KEY,
|
||||
timestamp TIMESTAMP DEFAULT NOW(),
|
||||
channel VARCHAR(50),
|
||||
sender VARCHAR(255),
|
||||
message TEXT,
|
||||
target VARCHAR(255),
|
||||
location_x FLOAT,
|
||||
location_y FLOAT,
|
||||
location_z FLOAT,
|
||||
is_admin BOOLEAN DEFAULT FALSE
|
||||
)
|
||||
""")
|
||||
self.db.execute_mutation(
|
||||
"CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)"
|
||||
)
|
||||
self.ensured_table = True
|
||||
logger.info("Chat history table ready")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("Failed to create chat history table: %s", e)
|
||||
return False
|
||||
|
||||
def save_message(self, channel, sender, message, target="", location=None, is_admin=False):
|
||||
loc_x = location.get("X", 0) if location else 0
|
||||
loc_y = location.get("Y", 0) if location else 0
|
||||
loc_z = location.get("Z", 0) if location else 0
|
||||
return self.db.execute_mutation(
|
||||
"""INSERT INTO dashboard.chat_history
|
||||
(channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
|
||||
[channel, sender, message, target, loc_x, loc_y, loc_z, is_admin],
|
||||
)
|
||||
|
||||
def get_history(self, limit: int = 200) -> list[dict]:
|
||||
return self.db.execute_readonly(
|
||||
"""SELECT id, timestamp, channel, sender, message, target,
|
||||
location_x, location_y, location_z, is_admin
|
||||
FROM dashboard.chat_history ORDER BY timestamp DESC LIMIT %s""",
|
||||
[limit],
|
||||
)
|
||||
|
||||
def catch_up(self, namespace: str) -> int:
|
||||
db_messages = self.get_history(1)
|
||||
has_history = db_messages and len(db_messages) >= 10
|
||||
if has_history:
|
||||
return 0
|
||||
|
||||
if not namespace:
|
||||
logger.warning("Cannot catch up — kubernetes namespace not set")
|
||||
return 0
|
||||
|
||||
pod_name = self.k8s.get_text_router_pod()
|
||||
if not pod_name:
|
||||
logger.warning("Cannot catch up — no text-router pod found")
|
||||
return 0
|
||||
|
||||
log_cmd = f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null"
|
||||
out, err, rc = self.ssh.run(log_cmd, timeout=30)
|
||||
if rc != 0 or not out:
|
||||
logger.debug("Cannot catch up — failed to get pod logs (rc=%d)", rc)
|
||||
return 0
|
||||
|
||||
lines = [line for line in out.split("\n") if "CLOG" in line and "TextChat" in line]
|
||||
lines = [line for line in lines if "Starting filtering" not in line]
|
||||
lines = [line for line in lines if "Skipping filtering" not in line]
|
||||
lines = [line for line in lines if "Redirected message" not in line]
|
||||
|
||||
messages = []
|
||||
seen = set()
|
||||
for line in lines:
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
idx = line.index("received message from ")
|
||||
rest = line[idx + len("received message from "):]
|
||||
parts = rest.split(" to ", 1)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
sender_id = parts[0].strip()
|
||||
target_and_json = parts[1]
|
||||
target_idx = target_and_json.index(": ")
|
||||
target = target_and_json[:target_idx].strip()
|
||||
msg_str = target_and_json[target_idx + 2:].strip()
|
||||
|
||||
msg_data = json.loads(msg_str)
|
||||
content = json.loads(msg_data.get("content", "{}"))
|
||||
|
||||
dedup_key = (
|
||||
content.get("m_ChannelType", ""),
|
||||
content.get("m_FuncomIdFrom", ""),
|
||||
content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
||||
)
|
||||
if dedup_key in seen:
|
||||
continue
|
||||
seen.add(dedup_key)
|
||||
|
||||
messages.append({
|
||||
"channel": content.get("m_ChannelType", "Unknown"),
|
||||
"sender": content.get("m_FuncomIdFrom", sender_id),
|
||||
"message": content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
||||
"target": target,
|
||||
"location": content.get("m_OriginLocation", {}),
|
||||
"is_admin": False,
|
||||
})
|
||||
except (ValueError, KeyError, json.JSONDecodeError, IndexError):
|
||||
continue
|
||||
|
||||
if messages:
|
||||
saved = self._save_batch(messages)
|
||||
logger.info("Caught up %d chat messages from pod logs", saved)
|
||||
return saved
|
||||
return 0
|
||||
|
||||
def _save_batch(self, messages: list[dict]) -> int:
|
||||
if not messages:
|
||||
return 0
|
||||
count = 0
|
||||
for msg in messages:
|
||||
if self.save_message(
|
||||
msg["channel"], msg["sender"], msg["message"],
|
||||
msg.get("target", ""), msg.get("location"), msg.get("is_admin", False),
|
||||
):
|
||||
count += 1
|
||||
return count
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Database service — psycopg3 connection pool and stored procedure executor."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, List
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseService:
|
||||
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema="dashboard"):
|
||||
self.db_config = db_config
|
||||
self.min_conn = min_conn
|
||||
self.max_conn = max_conn
|
||||
self.dashboard_schema = dashboard_schema
|
||||
self.pool = None
|
||||
|
||||
def init_pool(self):
|
||||
if self.pool is not None:
|
||||
return self.pool
|
||||
|
||||
conninfo = (
|
||||
f"host={self.db_config['host']} "
|
||||
f"port={self.db_config['port']} "
|
||||
f"dbname={self.db_config['database']} "
|
||||
f"user={self.db_config['user']} "
|
||||
f"password={self.db_config['password']}"
|
||||
)
|
||||
|
||||
for attempt in range(10):
|
||||
try:
|
||||
self.pool = ConnectionPool(
|
||||
conninfo=conninfo,
|
||||
min_size=self.min_conn,
|
||||
max_size=self.max_conn,
|
||||
open=False,
|
||||
)
|
||||
self.pool.open(wait=True, timeout=20)
|
||||
logger.info("Database connection pool initialized (psycopg3)")
|
||||
return self.pool
|
||||
except Exception as e:
|
||||
if attempt < 9:
|
||||
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||
time.sleep(2)
|
||||
else:
|
||||
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
||||
self.pool = None
|
||||
return self.pool
|
||||
|
||||
def call_function(self, name: str, args: List[Any]) -> List[dict]:
|
||||
"""Call a dune schema function and return rows as dicts."""
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
raise ConnectionError("Database pool not available")
|
||||
|
||||
placeholders = ",".join(["%s"] * len(args))
|
||||
sql = f"SELECT * FROM dune.{name}({placeholders})"
|
||||
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(sql, args)
|
||||
rows = cur.fetchall()
|
||||
return rows if rows else []
|
||||
|
||||
def call_procedure(self, name: str, args: List[Any]) -> None:
|
||||
"""Call a dune schema procedure (void return)."""
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
raise ConnectionError("Database pool not available")
|
||||
|
||||
placeholders = ",".join(["%s"] * len(args))
|
||||
sql = f"CALL dune.{name}({placeholders})"
|
||||
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, args)
|
||||
conn.commit()
|
||||
|
||||
def execute_readonly(self, sql: str, params: List[Any] | None = None) -> List[dict]:
|
||||
"""Execute a read-only SELECT query."""
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
raise ConnectionError("Database pool not available")
|
||||
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(sql, params or [])
|
||||
rows = cur.fetchall()
|
||||
return rows if rows else []
|
||||
|
||||
def execute_mutation(self, sql: str, params: List[Any] | None = None) -> int:
|
||||
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
raise ConnectionError("Database pool not available")
|
||||
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, params or [])
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
def health_check(self) -> bool:
|
||||
try:
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
return False
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Database health check FAILED: {e}")
|
||||
return False
|
||||
|
||||
def ensure_tables(self):
|
||||
"""Ensure dashboard schema tables exist."""
|
||||
pool = self.init_pool()
|
||||
if not pool:
|
||||
return
|
||||
|
||||
schema = self.dashboard_schema
|
||||
ddl = f"""
|
||||
CREATE SCHEMA IF NOT EXISTS {schema};
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.audit_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
action_type VARCHAR(50) NOT NULL,
|
||||
user_name VARCHAR(100) NOT NULL,
|
||||
target_player_id BIGINT,
|
||||
details JSONB DEFAULT '{{}}',
|
||||
source_ip INET,
|
||||
severity VARCHAR(20) DEFAULT 'info',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON {schema}.audit_log (created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_action ON {schema}.audit_log (action_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_user ON {schema}.audit_log (user_name);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
|
||||
player_id BIGINT PRIMARY KEY,
|
||||
ip_address INET NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.bans (
|
||||
id SERIAL PRIMARY KEY,
|
||||
player_id BIGINT UNIQUE,
|
||||
account_id BIGINT,
|
||||
reason TEXT DEFAULT '',
|
||||
note TEXT DEFAULT '',
|
||||
duration INT DEFAULT 0,
|
||||
banned_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMP,
|
||||
active BOOLEAN DEFAULT TRUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
player_id BIGINT NOT NULL,
|
||||
action_type VARCHAR(50) NOT NULL,
|
||||
reason TEXT DEFAULT '',
|
||||
note TEXT DEFAULT '',
|
||||
duration_minutes INT DEFAULT 0,
|
||||
ip_address INET,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.chat_history (
|
||||
id SERIAL PRIMARY KEY,
|
||||
timestamp TIMESTAMP DEFAULT NOW(),
|
||||
channel VARCHAR(50),
|
||||
sender VARCHAR(255),
|
||||
message TEXT,
|
||||
target VARCHAR(255),
|
||||
location_x FLOAT,
|
||||
location_y FLOAT,
|
||||
location_z FLOAT,
|
||||
is_admin BOOLEAN DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON {schema}.chat_history (timestamp DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS {schema}.settings (
|
||||
key VARCHAR(255) PRIMARY KEY,
|
||||
value TEXT DEFAULT '',
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
"""
|
||||
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(ddl)
|
||||
conn.commit()
|
||||
logger.info(f"Dashboard tables ensured in schema '{schema}'")
|
||||
|
||||
def close(self):
|
||||
if self.pool:
|
||||
try:
|
||||
self.pool.close()
|
||||
logger.info("Database pool closed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing pool: {e}")
|
||||
self.pool = None
|
||||
@@ -0,0 +1,182 @@
|
||||
# Economy service — items, currency, vitals, vendors.
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.models import Inventory, Item, CurrencyBalance, Vitals
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ALLOWED_ITEM_FIELDS = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
|
||||
|
||||
|
||||
class EconomyService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
# ── Inventory ─────────────────────────────────────────────────
|
||||
|
||||
def get_inventory(self, account_id: int) -> list[Inventory]:
|
||||
return PlayerService(self.db)._get_inventory(account_id)
|
||||
|
||||
def add_item(self, inventory_id: int, template_id: str, stack_size: int = 1, quality_level: int = 0) -> int:
|
||||
rows = self.db.call_function("add_item", [inventory_id, template_id, stack_size, quality_level])
|
||||
if rows and rows[0].get("id"):
|
||||
return rows[0]["id"]
|
||||
raise ValueError("Item add failed: no ID returned")
|
||||
|
||||
def delete_item(self, item_id: int) -> bool:
|
||||
self.db.call_procedure("delete_item", [item_id])
|
||||
return True
|
||||
|
||||
def delete_inventory_item(self, item_id: int, count: int) -> bool:
|
||||
self.db.call_procedure("delete_inventory_item", [item_id, count])
|
||||
return True
|
||||
|
||||
# ── Item Editing (DB-ONLY direct UPDATE — validated) ──────────
|
||||
|
||||
def edit_item_field(self, item_id: int, field: str, value: Any) -> bool:
|
||||
if field not in ALLOWED_ITEM_FIELDS:
|
||||
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(ALLOWED_ITEM_FIELDS))}")
|
||||
|
||||
if field == "is_new":
|
||||
self.db.execute_mutation(
|
||||
"UPDATE dune.items SET is_new = %s WHERE id = %s",
|
||||
[bool(value), item_id],
|
||||
)
|
||||
elif field in ("durability", "max_durability", "ammo"):
|
||||
stats_path = {
|
||||
"durability": "{FItemStackAndDurabilityStats,CurrentDurability}",
|
||||
"max_durability": "{FItemStackAndDurabilityStats,DecayedMaxDurability}",
|
||||
"ammo": "{FWeaponItemStats,CurrentAmmo}",
|
||||
}[field]
|
||||
self.db.execute_mutation(
|
||||
"UPDATE dune.items SET stats = jsonb_set(stats, %s, to_jsonb(%s::text), true) WHERE id = %s",
|
||||
[stats_path.split(","), str(value), item_id],
|
||||
)
|
||||
else:
|
||||
self.db.execute_mutation(
|
||||
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
|
||||
[int(value), item_id],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Currency ──────────────────────────────────────────────────
|
||||
|
||||
def get_currency(self, controller_id: int) -> list[CurrencyBalance]:
|
||||
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
|
||||
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
|
||||
return [CurrencyBalance(
|
||||
currency_id=r["currency_id"],
|
||||
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
|
||||
balance=r.get("balance", 0),
|
||||
) for r in rows]
|
||||
|
||||
def adjust_currency(self, controller_id: int, currency_id: int, delta: int) -> int:
|
||||
rows = self.db.call_function("adjust_player_virtual_currency_balance", [controller_id, currency_id, delta])
|
||||
if rows and len(rows) > 0:
|
||||
return rows[0].get("balance", 0)
|
||||
raise ValueError("Currency adjustment failed")
|
||||
|
||||
def set_currency(self, controller_id: int, currency_id: int, balance: int) -> bool:
|
||||
# DB-ONLY direct UPSERT — validated
|
||||
if balance < 0:
|
||||
raise ValueError("Balance cannot be negative")
|
||||
self.db.execute_mutation(
|
||||
"""INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET balance = EXCLUDED.balance""",
|
||||
[controller_id, currency_id, balance],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Vitals (DB-ONLY direct UPDATE — validated + offline check) ─
|
||||
|
||||
def get_vitals(self, pawn_id: int) -> Vitals:
|
||||
rows = self.db.call_function("admin_get_character_details", [pawn_id])
|
||||
if not rows:
|
||||
return Vitals()
|
||||
# Character details returns by account_id, but we need pawn data
|
||||
# Fallback to actors query for vitals
|
||||
actor_rows = self.db.execute_readonly(
|
||||
"""SELECT properties, gas_attributes FROM dune.actors WHERE id = %s""",
|
||||
[pawn_id],
|
||||
)
|
||||
if not actor_rows:
|
||||
return Vitals()
|
||||
row = actor_rows[0]
|
||||
props = row.get("properties") or {}
|
||||
gas = row.get("gas_attributes") or {}
|
||||
dmg = props.get("DamageableActorComponent") or {}
|
||||
hyd = gas.get("DuneHydrationAttributeSet") or {}
|
||||
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
|
||||
return Vitals(
|
||||
current_health=dmg.get("m_CurrentMaxHealth"),
|
||||
max_health=dmg.get("m_TotalMaxHealth"),
|
||||
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
|
||||
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
|
||||
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
|
||||
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
|
||||
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
|
||||
)
|
||||
|
||||
def set_vitals(self, pawn_id: int, health: float | None, max_health: float | None,
|
||||
hydration: float, spice: float) -> bool:
|
||||
# DB-ONLY: Validate player is offline
|
||||
offline_check = self.db.execute_readonly(
|
||||
"""SELECT 1 FROM dune.player_state
|
||||
WHERE player_pawn_id = %s AND online_status::text = 'Online'""",
|
||||
[pawn_id],
|
||||
)
|
||||
if offline_check:
|
||||
raise ValueError("Player must be offline to edit vitals")
|
||||
|
||||
if health is not None and health < 0:
|
||||
raise ValueError("Health cannot be negative")
|
||||
if max_health is not None and max_health < 0:
|
||||
raise ValueError("Max health cannot be negative")
|
||||
if hydration < 0:
|
||||
raise ValueError("Hydration cannot be negative")
|
||||
if spice < 0:
|
||||
raise ValueError("Spice cannot be negative")
|
||||
|
||||
if health is not None:
|
||||
self.db.execute_mutation(
|
||||
"""UPDATE dune.actors SET properties = jsonb_set(
|
||||
properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)
|
||||
) WHERE id = %s""",
|
||||
[health, pawn_id],
|
||||
)
|
||||
if max_health is not None:
|
||||
self.db.execute_mutation(
|
||||
"""UPDATE dune.actors SET properties = jsonb_set(
|
||||
properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)
|
||||
) WHERE id = %s""",
|
||||
[max_health, pawn_id],
|
||||
)
|
||||
|
||||
self.db.execute_mutation(
|
||||
"""UPDATE dune.actors SET gas_attributes = jsonb_set(
|
||||
jsonb_set(jsonb_set(jsonb_set(gas_attributes,
|
||||
'{DuneHydrationAttributeSet,CurrentHydration,CurrentValue}', to_jsonb(%s::float)),
|
||||
'{DuneHydrationAttributeSet,CurrentHydration,BaseValue}', to_jsonb(%s::float)),
|
||||
'{DuneSpiceAddictionAttributeSet,CurrentSpice,CurrentValue}', to_jsonb(%s::float)),
|
||||
'{DuneSpiceAddictionAttributeSet,CurrentSpice,BaseValue}', to_jsonb(%s::float)
|
||||
) WHERE id = %s""",
|
||||
[hydration, hydration, spice, spice, pawn_id],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Vendors ───────────────────────────────────────────────────
|
||||
|
||||
def clean_vendor_stock(self, player_id: int) -> bool:
|
||||
self.db.call_procedure("clean_stock_for_player", [player_id])
|
||||
return True
|
||||
|
||||
def get_tax_invoices(self, player_id: int) -> list[dict]:
|
||||
return self.db.call_function("taxation_get_all_invoices_for_player", [player_id])
|
||||
|
||||
|
||||
# Import here to avoid circular dependency at module load time
|
||||
from app.services.player import PlayerService
|
||||
@@ -0,0 +1,64 @@
|
||||
# Guild service — guild operations using DB functions only.
|
||||
|
||||
import logging
|
||||
|
||||
from app.models import GuildDetail, GuildMember, GuildSummary
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"}
|
||||
|
||||
|
||||
class GuildService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def list_all(self) -> list[GuildSummary]:
|
||||
rows = self.db.call_function("get_all_guilds", [])
|
||||
return [GuildSummary(
|
||||
guild_id=r.get("guild_id", 0),
|
||||
guild_name=r.get("guild_name", ""),
|
||||
guild_description=r.get("guild_description"),
|
||||
faction_name=r.get("faction_name"),
|
||||
member_count=r.get("member_count", 0),
|
||||
online_count=0, # requires additional query if needed
|
||||
) for r in rows]
|
||||
|
||||
def get_detail(self, guild_id: int) -> GuildDetail | None:
|
||||
guild_rows = self.db.call_function("get_guild_data", [guild_id])
|
||||
if not guild_rows:
|
||||
return None
|
||||
g = guild_rows[0]
|
||||
member_rows = self.db.call_function("get_guild_members", [guild_id])
|
||||
members = [GuildMember(
|
||||
player_id=r.get("player_id", 0),
|
||||
role_id=r.get("role_id", 50),
|
||||
role_name=GUILD_ROLES.get(r.get("role_id", 50), f"Role {r.get('role_id', 50)}"),
|
||||
player_name=r.get("name", "Unknown"),
|
||||
online_status=r.get("online_status", "Unknown"),
|
||||
) for r in member_rows]
|
||||
return GuildDetail(
|
||||
guild_id=g.get("guild_id", guild_id),
|
||||
guild_name=g.get("guild_name", ""),
|
||||
guild_description=g.get("guild_description"),
|
||||
faction_name=g.get("faction_name"),
|
||||
faction_id=g.get("guild_faction"),
|
||||
members=members,
|
||||
)
|
||||
|
||||
def disband(self, guild_id: int) -> bool:
|
||||
self.db.call_procedure("disband_guild", [guild_id])
|
||||
return True
|
||||
|
||||
def remove_member(self, guild_id: int, player_id: int, reason: int = 0) -> bool:
|
||||
self.db.call_procedure("remove_guild_members", [[player_id], guild_id, reason])
|
||||
return True
|
||||
|
||||
def promote(self, guild_id: int, player_id: int, role_id: int) -> bool:
|
||||
self.db.call_procedure("promote_guild_member", [guild_id, player_id, role_id])
|
||||
return True
|
||||
|
||||
def demote(self, guild_id: int, player_id: int, role_id: int) -> bool:
|
||||
self.db.call_procedure("demote_guild_member", [guild_id, player_id, role_id])
|
||||
return True
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Kubernetes service — kubectl operations via SSH."""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class K8sService:
|
||||
def __init__(self, ssh_service, namespace):
|
||||
self.ssh = ssh_service
|
||||
self.namespace = namespace
|
||||
|
||||
def run(self, kubectl_command, timeout=30):
|
||||
full_cmd = f"sudo kubectl {kubectl_command} -n {self.namespace}"
|
||||
logger.debug("K8s executing: %s", full_cmd)
|
||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
||||
out, err, rc = result
|
||||
if rc != 0:
|
||||
logger.debug("K8s command failed (rc=%d): %s", rc, err[:100] if err else "no error")
|
||||
else:
|
||||
logger.debug("K8s command OK, output lines: %d", len(out.split("\n")) if out else 0)
|
||||
return result
|
||||
|
||||
def get_pods(self):
|
||||
out, err, rc = self.run("get pods -o json")
|
||||
if rc != 0:
|
||||
logger.error("Failed to get pods: %s", err)
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(out or "{}")
|
||||
items = data.get("items", [])
|
||||
pods = []
|
||||
for item in items:
|
||||
metadata = item.get("metadata", {})
|
||||
status = item.get("status", {})
|
||||
container_statuses = status.get("containerStatuses", [])
|
||||
restarts = sum(c.get("restartCount", 0) for c in container_statuses)
|
||||
pods.append({
|
||||
"name": metadata.get("name", ""),
|
||||
"namespace": metadata.get("namespace", self.namespace),
|
||||
"status": status.get("phase", "Unknown"),
|
||||
"restarts": restarts,
|
||||
"age": self._age_from_creation(metadata.get("creationTimestamp")),
|
||||
})
|
||||
logger.debug("Found %d pods in namespace %s", len(pods), self.namespace)
|
||||
return pods
|
||||
except Exception as e:
|
||||
logger.error("Failed to parse pods: %s", e)
|
||||
return []
|
||||
|
||||
def find_pod_by_pattern(self, pattern):
|
||||
pods = self.get_pods()
|
||||
for pod in pods:
|
||||
if pattern.lower() in pod.lower():
|
||||
return pod
|
||||
return None
|
||||
|
||||
def get_text_router_pod(self):
|
||||
pod = self.find_pod_by_pattern("tr-deploy")
|
||||
if pod:
|
||||
return pod
|
||||
pod = self.find_pod_by_pattern("text")
|
||||
if pod:
|
||||
return pod
|
||||
return self.find_pod_by_pattern("router")
|
||||
|
||||
def get_rabbitmq_pod(self, admin=True):
|
||||
if admin:
|
||||
return self.find_pod_by_pattern("mq-admin")
|
||||
return self.find_pod_by_pattern("mq-game")
|
||||
|
||||
def get_filebrowser_pod(self):
|
||||
return self.find_pod_by_pattern("fb-deploy")
|
||||
|
||||
def get_deployments(self):
|
||||
out, err, rc = self.run("get deployments -o json")
|
||||
if rc != 0:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(out or "{}")
|
||||
items = data.get("items", [])
|
||||
deployments = []
|
||||
for item in items:
|
||||
metadata = item.get("metadata", {})
|
||||
spec = item.get("spec", {})
|
||||
status = item.get("status", {})
|
||||
deployments.append({
|
||||
"name": metadata.get("name", ""),
|
||||
"namespace": metadata.get("namespace", self.namespace),
|
||||
"replicas": spec.get("replicas", 0),
|
||||
"available": status.get("availableReplicas", 0),
|
||||
})
|
||||
return deployments
|
||||
except Exception as e:
|
||||
logger.error("Failed to parse deployments: %s", e)
|
||||
return []
|
||||
|
||||
def get_node_metrics(self):
|
||||
out, err, rc = self.run("top nodes")
|
||||
if rc == 0 and out.strip():
|
||||
lines = out.strip().split("\n")
|
||||
if len(lines) >= 2:
|
||||
parts = lines[1].split()
|
||||
if len(parts) >= 4:
|
||||
return {
|
||||
"cpu": parts[2],
|
||||
"memory": parts[3],
|
||||
"cpu_pct": parts[1],
|
||||
}
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def _age_from_creation(timestamp: str | None) -> str:
|
||||
if not timestamp:
|
||||
return "Unknown"
|
||||
from datetime import datetime, timezone
|
||||
try:
|
||||
created = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
||||
delta = datetime.now(timezone.utc) - created
|
||||
days = delta.days
|
||||
hours = delta.seconds // 3600
|
||||
minutes = (delta.seconds % 3600) // 60
|
||||
if days > 0:
|
||||
return f"{days}d"
|
||||
if hours > 0:
|
||||
return f"{hours}h"
|
||||
return f"{minutes}m"
|
||||
except Exception:
|
||||
return "Unknown"
|
||||
|
||||
def auto_detect_namespace(self):
|
||||
out, err, rc = self.ssh.run("sudo kubectl get namespaces -o name", timeout=10)
|
||||
if rc == 0:
|
||||
for line in (out or "").strip().split("\n"):
|
||||
ns = line.replace("namespace/", "").strip()
|
||||
if ns.startswith("funcom-seabass-"):
|
||||
logger.info("Auto-detected K8s namespace: %s", ns)
|
||||
self.namespace = ns
|
||||
return ns
|
||||
return None
|
||||
@@ -0,0 +1,269 @@
|
||||
# Player service — player queries using DB functions only.
|
||||
|
||||
import logging
|
||||
from typing import List
|
||||
|
||||
from app.models import PlayerDetail, PlayerSummary, Vitals, Inventory, Item
|
||||
from app.models import CurrencyBalance, SpecializationTrack, Keystone
|
||||
from app.models import FactionReputation, LandsraadInfo
|
||||
from app.models import VehicleSummary, BuildingSummary, Landclaim
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PlayerService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
# ── Search & List ─────────────────────────────────────────────
|
||||
|
||||
def search(self, term: str, limit: int = 50) -> list[PlayerSummary]:
|
||||
rows = self.db.call_function("admin_get_character_ids", [f"%{term}%"])
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
account_ids = [r.get("id") for r in rows if r.get("id")]
|
||||
if not account_ids:
|
||||
return []
|
||||
|
||||
return self._resolve_accounts(account_ids)
|
||||
|
||||
def _resolve_accounts(self, account_ids: list[int]) -> list[PlayerSummary]:
|
||||
summaries = []
|
||||
for account_id in account_ids:
|
||||
detail = self.db.call_function("admin_get_character_details", [account_id])
|
||||
if detail:
|
||||
row = detail[0]
|
||||
summaries.append(PlayerSummary(
|
||||
player_controller_id=row.get("player_controller_id"),
|
||||
character_name=row.get("character_name") or "Unknown",
|
||||
account_email=row.get("account_email"),
|
||||
funcom_id=row.get("funcom_id"),
|
||||
faction_name=row.get("faction_name"),
|
||||
faction_id=row.get("faction_id"),
|
||||
map=row.get("map"),
|
||||
online_status=row.get("online_status") or "Unknown",
|
||||
life_state=row.get("life_state"),
|
||||
last_login_time=row.get("last_login_time"),
|
||||
last_avatar_activity=row.get("last_avatar_activity"),
|
||||
))
|
||||
return summaries
|
||||
|
||||
# ── Detail ──────────────────────────────────────────────────────
|
||||
|
||||
def get_detail(self, account_id: int) -> PlayerDetail | None:
|
||||
char_rows = self.db.call_function("admin_get_character_details", [account_id])
|
||||
if not char_rows:
|
||||
return None
|
||||
row = char_rows[0]
|
||||
|
||||
controller_id = row.get("player_controller_id")
|
||||
pawn_id = row.get("player_pawn_id")
|
||||
|
||||
vitals = self._extract_vitals(row)
|
||||
currency = self._get_currency(controller_id)
|
||||
inventories = self._get_inventory(account_id)
|
||||
vehicles = self._get_vehicles(controller_id, account_id)
|
||||
buildings = self._get_buildings(pawn_id)
|
||||
landclaims = self._get_landclaims(account_id)
|
||||
spec = self._get_specialization(controller_id)
|
||||
keystones = self._get_keystones(controller_id)
|
||||
faction_rep = self._get_faction_reputation(controller_id)
|
||||
landsraad = self._get_landsraad(controller_id)
|
||||
tags = self._get_tags(account_id)
|
||||
is_online = self._check_online(controller_id)
|
||||
|
||||
return PlayerDetail(
|
||||
id=row.get("id"),
|
||||
account_id=account_id,
|
||||
player_controller_id=controller_id,
|
||||
player_pawn_id=pawn_id,
|
||||
character_name=row.get("character_name") or "Unknown",
|
||||
account_email=row.get("account_email"),
|
||||
funcom_id=row.get("funcom_id"),
|
||||
faction_name=row.get("faction_name"),
|
||||
faction_id=row.get("faction_id"),
|
||||
map=row.get("map"),
|
||||
online_status=row.get("online_status") or "Unknown",
|
||||
life_state=row.get("life_state"),
|
||||
last_login_time=row.get("last_login_time"),
|
||||
last_avatar_activity=row.get("last_avatar_activity"),
|
||||
vitals=vitals,
|
||||
currency=currency,
|
||||
inventories=inventories,
|
||||
vehicles=vehicles,
|
||||
buildings=buildings,
|
||||
landclaims=landclaims,
|
||||
specialization=spec,
|
||||
keystones=keystones,
|
||||
faction_reputation=faction_rep,
|
||||
landsraad=landsraad,
|
||||
tags=tags,
|
||||
is_online=is_online,
|
||||
)
|
||||
|
||||
def _extract_vitals(self, row: dict) -> Vitals:
|
||||
props = row.get("properties") or {}
|
||||
gas = row.get("gas_attributes") or {}
|
||||
dmg = props.get("DamageableActorComponent") or {}
|
||||
hyd = gas.get("DuneHydrationAttributeSet") or {}
|
||||
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
|
||||
return Vitals(
|
||||
current_health=dmg.get("m_CurrentMaxHealth"),
|
||||
max_health=dmg.get("m_TotalMaxHealth"),
|
||||
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
|
||||
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
|
||||
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
|
||||
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
|
||||
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
|
||||
)
|
||||
|
||||
def _get_currency(self, controller_id: int | None) -> list[CurrencyBalance]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
|
||||
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
|
||||
return [CurrencyBalance(
|
||||
currency_id=r["currency_id"],
|
||||
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
|
||||
balance=r.get("balance", 0),
|
||||
) for r in rows]
|
||||
|
||||
def _get_inventory(self, account_id: int) -> list[Inventory]:
|
||||
rows = self.db.call_function("admin_get_inventory_details", [account_id])
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
from app.utils.constants import INVENTORY_TYPE_LABELS
|
||||
inventories = {}
|
||||
for r in rows:
|
||||
inv_id = r.get("inventory_id")
|
||||
if inv_id not in inventories:
|
||||
inv_type = r.get("inventory_type", 0)
|
||||
inventories[inv_id] = Inventory(
|
||||
inventory_id=inv_id,
|
||||
actor_id=r.get("actor_id"),
|
||||
inventory_type=inv_type,
|
||||
inventory_type_label=INVENTORY_TYPE_LABELS.get(inv_type, f"Type {inv_type}"),
|
||||
max_item_count=r.get("max_item_count"),
|
||||
max_item_volume=r.get("max_item_volume"),
|
||||
items=[],
|
||||
)
|
||||
stats = r.get("stats") or {}
|
||||
dur = stats.get("FItemStackAndDurabilityStats") or {}
|
||||
wpn = stats.get("FWeaponItemStats") or {}
|
||||
inventories[inv_id].items.append(Item(
|
||||
id=r.get("item_id"),
|
||||
template_id=r.get("template_id", ""),
|
||||
stack_size=r.get("count", 1),
|
||||
quality_level=r.get("quality_level", 0),
|
||||
is_new=r.get("is_new", False),
|
||||
position_index=r.get("position_index", 0),
|
||||
stats=stats,
|
||||
durability=dur.get("CurrentDurability") if isinstance(dur, dict) else None,
|
||||
max_durability=dur.get("DecayedMaxDurability") if isinstance(dur, dict) else None,
|
||||
ammo=wpn.get("CurrentAmmo") if isinstance(wpn, dict) else None,
|
||||
))
|
||||
return list(inventories.values())
|
||||
|
||||
def _get_vehicles(self, controller_id: int | None, account_id: int) -> list[VehicleSummary]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_owned_vehicles_data", [controller_id, account_id])
|
||||
return [VehicleSummary(
|
||||
id=r.get("vehicle_id"),
|
||||
class_name=r.get("class", ""),
|
||||
display_name=self._vehicle_display_name(r.get("class", "")),
|
||||
map=r.get("map"),
|
||||
) for r in rows]
|
||||
|
||||
def _get_buildings(self, player_id: int | None) -> list[BuildingSummary]:
|
||||
if not player_id:
|
||||
return []
|
||||
# DB-READ: no function for buildings-by-owner
|
||||
rows = self.db.execute_readonly(
|
||||
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
|
||||
a.properties->>'m_PowerLevel' as power_level
|
||||
FROM dune.buildings b JOIN dune.actors a ON b.id = a.id
|
||||
WHERE b.owner_id = %s ORDER BY a.map""",
|
||||
[player_id],
|
||||
)
|
||||
return [BuildingSummary(
|
||||
id=r["id"],
|
||||
class_name=r["class"],
|
||||
map=r["map"],
|
||||
owner_name="", # known from context
|
||||
instance_count=0,
|
||||
is_powered=r.get("is_powered") == "True",
|
||||
power_level=r.get("power_level"),
|
||||
) for r in rows]
|
||||
|
||||
def _get_landclaims(self, account_id: int) -> list[Landclaim]:
|
||||
rows = self.db.execute_readonly(
|
||||
"""SELECT DISTINCT a.id, a.class, a.map
|
||||
FROM dune.landclaim_segments lcs
|
||||
JOIN dune.actors a ON lcs.totem_id = a.id
|
||||
WHERE a.owner_account_id = %s""",
|
||||
[account_id],
|
||||
)
|
||||
return [Landclaim(id=r["id"], class_name=r["class"], map=r["map"]) for r in rows]
|
||||
|
||||
def _get_specialization(self, controller_id: int | None) -> list[SpecializationTrack]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_specialization", [controller_id])
|
||||
return [SpecializationTrack(
|
||||
track_type=r.get("track_type", ""),
|
||||
xp_amount=r.get("xp_amount", 0),
|
||||
level=r.get("level", 0),
|
||||
) for r in rows]
|
||||
|
||||
def _get_keystones(self, controller_id: int | None) -> list[Keystone]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_keystones", [controller_id])
|
||||
return [Keystone(id=r.get("id", 0), name=r.get("name", "")) for r in rows]
|
||||
|
||||
def _get_faction_reputation(self, controller_id: int | None) -> list[FactionReputation]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_current_faction_reputation", [controller_id])
|
||||
return [FactionReputation(
|
||||
faction_id=r.get("out_faction_id"),
|
||||
faction_name="", # resolved later if needed
|
||||
reputation_amount=r.get("out_reputation_amount", 0),
|
||||
) for r in rows]
|
||||
|
||||
def _get_landsraad(self, controller_id: int | None) -> LandsraadInfo:
|
||||
if not controller_id:
|
||||
return LandsraadInfo()
|
||||
rows = self.db.call_function("get_player_landsraad", [controller_id])
|
||||
if rows:
|
||||
r = rows[0]
|
||||
return LandsraadInfo(
|
||||
daily_reward_charges=r.get("daily_reward_charges"),
|
||||
last_viewed_term_id=r.get("last_viewed_term_id"),
|
||||
daily_reward_last_processed=r.get("daily_reward_last_processed"),
|
||||
)
|
||||
return LandsraadInfo()
|
||||
|
||||
def _get_tags(self, account_id: int) -> list[str]:
|
||||
rows = self.db.call_function("admin_read_player_tags", [account_id])
|
||||
return [r.get("tag", "") for r in rows if r.get("tag")]
|
||||
|
||||
def _check_online(self, controller_id: int | None) -> bool:
|
||||
if not controller_id:
|
||||
return False
|
||||
rows = self.db.call_function("get_player_ids_online_state", [[controller_id]])
|
||||
return bool(rows)
|
||||
|
||||
# ── Utilities ─────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _vehicle_display_name(cls: str) -> str:
|
||||
if "/" in cls:
|
||||
short = cls.split("/")[-1].replace("_C", "")
|
||||
else:
|
||||
short = cls.replace("_C", "")
|
||||
return short.replace("BP_", "").replace("_CHOAM", "").replace("_", " ")
|
||||
@@ -0,0 +1,32 @@
|
||||
# Progression service — journey and specialization using DB functions.
|
||||
|
||||
import logging
|
||||
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProgressionService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def complete_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
||||
self.db.call_procedure("complete_journey_story_nodes_for_player", [player_id, node_ids])
|
||||
return True
|
||||
|
||||
def reveal_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
||||
self.db.call_procedure("reveal_journey_story_nodes_for_player", [player_id, node_ids])
|
||||
return True
|
||||
|
||||
def reset_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
||||
self.db.call_procedure("delete_journey_story_nodes_for_player", [player_id, node_ids])
|
||||
return True
|
||||
|
||||
def set_specialization(self, player_id: int, track_type: str, xp: int, level: float) -> bool:
|
||||
self.db.call_procedure("set_specialization_xp_and_level", [player_id, track_type, xp, level])
|
||||
return True
|
||||
|
||||
def reset_specializations(self, player_id: int) -> bool:
|
||||
self.db.call_procedure("reset_specialization_tracks", [player_id])
|
||||
return True
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Realtime service — SSE broadcaster + BGD/RMQ poller."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Callable, Dict, Set
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SseClient:
|
||||
"""Simple wrapper for an SSE client connection."""
|
||||
def __init__(self, queue: asyncio.Queue):
|
||||
self.queue = queue
|
||||
self.connected_at = time.time()
|
||||
|
||||
|
||||
class RealtimeService:
|
||||
def __init__(self, bg_director, rmq_admin, chat_service):
|
||||
self.bg_director = bg_director
|
||||
self.rmq_admin = rmq_admin
|
||||
self.chat_service = chat_service
|
||||
self._clients: Set[asyncio.Queue] = set()
|
||||
self._lock = threading.Lock()
|
||||
self._previous_bg: dict | None = None
|
||||
self._running = False
|
||||
self._bgd_task = None
|
||||
self._rmq_task = None
|
||||
|
||||
# ── Client Management ─────────────────────────────────────────
|
||||
|
||||
def add_client(self, queue: asyncio.Queue):
|
||||
with self._lock:
|
||||
self._clients.add(queue)
|
||||
logger.debug("SSE client added. Total: %d", len(self._clients))
|
||||
|
||||
def remove_client(self, queue: asyncio.Queue):
|
||||
with self._lock:
|
||||
self._clients.discard(queue)
|
||||
logger.debug("SSE client removed. Total: %d", len(self._clients))
|
||||
|
||||
async def _broadcast(self, event: str, data: dict):
|
||||
"""Broadcast an event to all connected SSE clients."""
|
||||
payload = f"event: {event}\ndata: {json.dumps(data)}\n\n"
|
||||
with self._lock:
|
||||
dead = set()
|
||||
for queue in self._clients:
|
||||
try:
|
||||
queue.put_nowait(payload)
|
||||
except asyncio.QueueFull:
|
||||
dead.add(queue)
|
||||
except Exception:
|
||||
dead.add(queue)
|
||||
self._clients -= dead
|
||||
|
||||
# ── Background Polling ──────────────────────────────────────
|
||||
|
||||
def start(self):
|
||||
if self._running:
|
||||
return
|
||||
self._running = True
|
||||
self._bgd_task = threading.Thread(target=self._bgd_poll_loop, daemon=True)
|
||||
self._bgd_task.start()
|
||||
self._rmq_task = threading.Thread(target=self._rmq_poll_loop, daemon=True)
|
||||
self._rmq_task.start()
|
||||
logger.info("RealtimeService started")
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
logger.info("RealtimeService stopped")
|
||||
|
||||
def _bgd_poll_loop(self):
|
||||
"""Poll BGD every 10 seconds and broadcast deltas."""
|
||||
while self._running:
|
||||
try:
|
||||
bg = self.bg_director.get_battlegroup()
|
||||
current = bg.model_dump() if hasattr(bg, "model_dump") else bg.__dict__
|
||||
delta = self._compute_bg_delta(self._previous_bg, current)
|
||||
if delta:
|
||||
asyncio.run(self._broadcast("battlegroup_update", delta))
|
||||
self._previous_bg = current
|
||||
except Exception as e:
|
||||
logger.warning("BGD poll failed: %s", e)
|
||||
asyncio.run(self._broadcast("connection_status", {"bgd": False}))
|
||||
time.sleep(10)
|
||||
|
||||
def _rmq_poll_loop(self):
|
||||
"""Poll RMQ every 30 seconds and broadcast health."""
|
||||
while self._running:
|
||||
try:
|
||||
overview = self.rmq_admin.get_overview()
|
||||
data = {
|
||||
"cluster_name": overview.cluster_name,
|
||||
"queue_totals": overview.queue_totals,
|
||||
"message_stats": overview.message_stats,
|
||||
}
|
||||
asyncio.run(self._broadcast("rmq_health", data))
|
||||
except Exception as e:
|
||||
logger.warning("RMQ poll failed: %s", e)
|
||||
asyncio.run(self._broadcast("connection_status", {"rmq": False}))
|
||||
time.sleep(30)
|
||||
|
||||
def _compute_bg_delta(self, previous: dict | None, current: dict) -> dict | None:
|
||||
"""Compute meaningful deltas between battlegroup states."""
|
||||
if not previous:
|
||||
return {
|
||||
"online_count": self._count_online(current),
|
||||
"intransit_count": len(current.get("intransit_players", [])),
|
||||
"server_statuses": self._extract_server_statuses(current),
|
||||
"map_counts": self._extract_map_counts(current),
|
||||
}
|
||||
|
||||
prev_online = self._count_online(previous)
|
||||
curr_online = self._count_online(current)
|
||||
prev_statuses = self._extract_server_statuses(previous)
|
||||
curr_statuses = self._extract_server_statuses(current)
|
||||
|
||||
delta = {}
|
||||
if curr_online != prev_online:
|
||||
delta["online_count"] = curr_online
|
||||
if len(current.get("intransit_players", [])) != len(previous.get("intransit_players", [])):
|
||||
delta["intransit_count"] = len(current.get("intransit_players", []))
|
||||
if curr_statuses != prev_statuses:
|
||||
delta["server_statuses"] = curr_statuses
|
||||
|
||||
return delta if delta else None
|
||||
|
||||
def _count_online(self, state: dict) -> int:
|
||||
return len(state.get("online_players", []))
|
||||
|
||||
def _extract_server_statuses(self, state: dict) -> dict:
|
||||
statuses = {}
|
||||
for key in ["dimension_maps", "single_server_maps", "instanced_maps"]:
|
||||
for mg in state.get(key, []):
|
||||
for sv in mg.get("servers", []):
|
||||
partition = sv.get("partition", "")
|
||||
if partition:
|
||||
statuses[partition] = sv.get("status", "unknown")
|
||||
return statuses
|
||||
|
||||
def _extract_map_counts(self, state: dict) -> dict:
|
||||
counts = {}
|
||||
for key in ["dimension_maps", "single_server_maps", "instanced_maps"]:
|
||||
for mg in state.get(key, []):
|
||||
name = mg.get("name", "")
|
||||
if name:
|
||||
counts[name] = sum(sv.get("num_players", 0) for sv in mg.get("servers", []))
|
||||
return counts
|
||||
|
||||
# ── Event Helpers ───────────────────────────────────────────
|
||||
|
||||
async def notify_chat_message(self, msg: dict):
|
||||
await self._broadcast("chat_message", msg)
|
||||
|
||||
async def notify_server_event(self, event: dict):
|
||||
await self._broadcast("server_event", event)
|
||||
|
||||
async def notify_player_event(self, event: dict):
|
||||
await self._broadcast("player_event", event)
|
||||
|
||||
async def notify_connection_status(self, status: dict):
|
||||
await self._broadcast("connection_status", status)
|
||||
@@ -0,0 +1,146 @@
|
||||
"""RabbitMQ Admin Management HTTP API client."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import httpx
|
||||
|
||||
from app.models import RmqOverview, RmqQueueInfo
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RmqAdminService:
|
||||
def __init__(self, host: str, port: int, username: str, password: str):
|
||||
self.base_url = f"http://{host}:{port}"
|
||||
self.auth = (username, password)
|
||||
self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15)
|
||||
logger.debug("RmqAdminService initialized: %s", self.base_url)
|
||||
|
||||
def _get(self, path: str) -> dict | list:
|
||||
try:
|
||||
resp = self.client.get(path)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error("RMQ Admin GET %s failed: %s", path, e)
|
||||
raise RmqError(f"RMQ Admin HTTP {e.response.status_code}")
|
||||
except httpx.ConnectError as e:
|
||||
logger.error("RMQ Admin connection failed: %s", e)
|
||||
raise RmqError("Cannot connect to RMQ Admin API")
|
||||
|
||||
def _post(self, path: str, data: dict) -> dict:
|
||||
try:
|
||||
resp = self.client.post(path, json=data)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error("RMQ Admin POST %s failed: %s", path, e)
|
||||
raise RmqError(f"RMQ Admin HTTP {e.response.status_code}")
|
||||
except httpx.ConnectError as e:
|
||||
logger.error("RMQ Admin connection failed: %s", e)
|
||||
raise RmqError("Cannot connect to RMQ Admin API")
|
||||
|
||||
# ── Overview & Health ───────────────────────────────────────────
|
||||
|
||||
def get_overview(self) -> RmqOverview:
|
||||
data = self._get("/api/overview")
|
||||
return RmqOverview(
|
||||
cluster_name=data.get("cluster_name", ""),
|
||||
node=data.get("node", ""),
|
||||
message_stats=data.get("message_stats", {}),
|
||||
queue_totals=data.get("queue_totals", {}),
|
||||
object_totals=data.get("object_totals", {}),
|
||||
)
|
||||
|
||||
def get_nodes(self) -> list[dict]:
|
||||
return self._get("/api/nodes")
|
||||
|
||||
def health_check(self) -> dict:
|
||||
return self._get("/api/health/checks/alarms")
|
||||
|
||||
# ── Exchanges & Queues ────────────────────────────────────────
|
||||
|
||||
def get_exchanges(self) -> list[dict]:
|
||||
return self._get("/api/exchanges")
|
||||
|
||||
def get_queues(self) -> list[dict]:
|
||||
return self._get("/api/queues")
|
||||
|
||||
def get_queue_info(self, name: str) -> dict:
|
||||
return self._get(f"/api/queues/%2f/{name}")
|
||||
|
||||
def get_bindings(self) -> list[dict]:
|
||||
return self._get("/api/bindings")
|
||||
|
||||
def get_consumers(self) -> list[dict]:
|
||||
return self._get("/api/consumers")
|
||||
|
||||
def get_connections(self) -> list[dict]:
|
||||
return self._get("/api/connections")
|
||||
|
||||
def get_channels(self) -> list[dict]:
|
||||
return self._get("/api/channels")
|
||||
|
||||
# ── Publish / Consume ─────────────────────────────────────────
|
||||
|
||||
def publish(
|
||||
self,
|
||||
exchange: str,
|
||||
routing_key: str,
|
||||
payload: str | dict,
|
||||
payload_encoding: str = "string",
|
||||
properties: dict | None = None,
|
||||
) -> bool:
|
||||
body_payload = payload if isinstance(payload, str) else json.dumps(payload)
|
||||
body = {
|
||||
"routing_key": routing_key,
|
||||
"payload": body_payload,
|
||||
"payload_encoding": payload_encoding,
|
||||
}
|
||||
if properties:
|
||||
body["properties"] = properties
|
||||
result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body)
|
||||
return result.get("routed", False)
|
||||
|
||||
def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]:
|
||||
body = {"count": count, "ackmode": ackmode, "encoding": "auto"}
|
||||
return self._post(f"/api/queues/%2f/{queue}/get", body)
|
||||
|
||||
def get_exchange_bindings(self, exchange: str) -> list[dict]:
|
||||
return self._get(f"/api/exchanges/%2f/{exchange}/bindings/source")
|
||||
|
||||
def get_queue_bindings(self, queue: str) -> list[dict]:
|
||||
return self._get(f"/api/queues/%2f/{queue}/bindings")
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────
|
||||
|
||||
def get_queue_depths(self) -> list[RmqQueueInfo]:
|
||||
queues = self.get_queues()
|
||||
return [
|
||||
RmqQueueInfo(
|
||||
name=q.get("name", ""),
|
||||
messages_ready=q.get("messages_ready", 0),
|
||||
messages_unacknowledged=q.get("messages_unacknowledged", 0),
|
||||
consumer_count=q.get("consumers", 0),
|
||||
state=q.get("state", ""),
|
||||
)
|
||||
for q in queues
|
||||
]
|
||||
|
||||
def publish_settings_update(self, payload: dict) -> bool:
|
||||
"""Publish to the settingsUpdate fanout exchange."""
|
||||
return self.publish(
|
||||
exchange="settingsUpdate",
|
||||
routing_key="",
|
||||
payload=json.dumps(payload),
|
||||
properties={"content_type": "application/json"},
|
||||
)
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
|
||||
class RmqError(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,126 @@
|
||||
"""RabbitMQ Game Management HTTP API client."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RmqGameService:
|
||||
def __init__(self, host: str, port: int, username: str, password: str):
|
||||
self.base_url = f"http://{host}:{port}"
|
||||
self.auth = (username, password)
|
||||
self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15)
|
||||
logger.debug("RmqGameService initialized: %s", self.base_url)
|
||||
|
||||
def _get(self, path: str) -> dict | list:
|
||||
try:
|
||||
resp = self.client.get(path)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error("RMQ Game GET %s failed: %s", path, e)
|
||||
raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}")
|
||||
except httpx.ConnectError as e:
|
||||
logger.error("RMQ Game connection failed: %s", e)
|
||||
raise RmqGameError("Cannot connect to RMQ Game API")
|
||||
|
||||
def _post(self, path: str, data: dict) -> dict:
|
||||
try:
|
||||
resp = self.client.post(path, json=data)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error("RMQ Game POST %s failed: %s", path, e)
|
||||
raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}")
|
||||
except httpx.ConnectError as e:
|
||||
logger.error("RMQ Game connection failed: %s", e)
|
||||
raise RmqGameError("Cannot connect to RMQ Game API")
|
||||
|
||||
# ── Overview ──────────────────────────────────────────────────
|
||||
|
||||
def get_overview(self) -> dict:
|
||||
return self._get("/api/overview")
|
||||
|
||||
def get_exchanges(self) -> list[dict]:
|
||||
return self._get("/api/exchanges")
|
||||
|
||||
def get_queues(self) -> list[dict]:
|
||||
return self._get("/api/queues")
|
||||
|
||||
# ── Publish ───────────────────────────────────────────────────
|
||||
|
||||
def publish(
|
||||
self,
|
||||
exchange: str,
|
||||
routing_key: str,
|
||||
payload: str | dict,
|
||||
payload_encoding: str = "string",
|
||||
properties: dict | None = None,
|
||||
) -> bool:
|
||||
body_payload = payload if isinstance(payload, str) else json.dumps(payload)
|
||||
body = {
|
||||
"routing_key": routing_key,
|
||||
"payload": body_payload,
|
||||
"payload_encoding": payload_encoding,
|
||||
}
|
||||
if properties:
|
||||
body["properties"] = properties
|
||||
result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body)
|
||||
return result.get("routed", False)
|
||||
|
||||
def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]:
|
||||
body = {"count": count, "ackmode": ackmode, "encoding": "auto"}
|
||||
return self._post(f"/api/queues/%2f/{queue}/get", body)
|
||||
|
||||
# ── Broadcast ─────────────────────────────────────────────────
|
||||
|
||||
def send_broadcast(self, message: str, title: str = "", duration: int = 30, server: str | None = None, partition: str | None = None) -> bool:
|
||||
"""Send an in-game broadcast via the heartbeats exchange."""
|
||||
display_title = title or "Admin Broadcast"
|
||||
inner = {
|
||||
"ServerCommand": "ServiceBroadcast",
|
||||
"BroadcastType": "Generic",
|
||||
"BroadcastPayload": {
|
||||
"BroadcastDuration": duration,
|
||||
"LocalizedText": [
|
||||
{"Key": "en", "Title": display_title, "Body": message},
|
||||
{"Key": "en-US", "Title": display_title, "Body": message},
|
||||
],
|
||||
},
|
||||
}
|
||||
body = {
|
||||
"Version": 2,
|
||||
"AuthToken": "Nu6VmPWUMvdPMeB7qErr",
|
||||
"MessageContent": inner,
|
||||
}
|
||||
return self.publish(
|
||||
exchange="heartbeats",
|
||||
routing_key="notifications",
|
||||
payload=json.dumps(body),
|
||||
payload_encoding="string",
|
||||
properties={
|
||||
"content_type": "application/json",
|
||||
"message_id": f"manual-service-broadcast-{int(time.time() * 1000)}",
|
||||
"app_id": "fls",
|
||||
"user_id": "fls_backend",
|
||||
},
|
||||
)
|
||||
|
||||
# ── Chat Intercept ────────────────────────────────────────────
|
||||
|
||||
def peek_chat_intercept(self, count: int = 10) -> list[dict]:
|
||||
"""Peek messages from the chat.intercept queue."""
|
||||
return self.peek_messages("queue.intercept", count=count)
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
|
||||
class RmqGameError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
import time
|
||||
@@ -0,0 +1,103 @@
|
||||
"""SSH service — remote command execution via paramiko."""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import paramiko
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SSHService:
|
||||
def __init__(self, host, user, ssh_key=None):
|
||||
self.host = host
|
||||
self.user = user
|
||||
self.ssh_key = ssh_key
|
||||
self._client = None
|
||||
self._lock = threading.Lock()
|
||||
key_status = self.ssh_key if self.ssh_key else "default ssh identity/agent"
|
||||
logger.info("SSHService initialized: %s@%s using %s", user, host, key_status)
|
||||
|
||||
def _get_client(self):
|
||||
with self._lock:
|
||||
if self._client is not None:
|
||||
transport = self._client.get_transport()
|
||||
if transport and transport.is_active():
|
||||
return self._client
|
||||
self._client = None
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
|
||||
connect_kwargs = {
|
||||
"hostname": self.host,
|
||||
"username": self.user,
|
||||
"timeout": 15,
|
||||
"allow_agent": True,
|
||||
"look_for_keys": True,
|
||||
}
|
||||
if self.ssh_key:
|
||||
connect_kwargs["key_filename"] = self.ssh_key
|
||||
|
||||
try:
|
||||
client.connect(**connect_kwargs)
|
||||
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
||||
except paramiko.AuthenticationException:
|
||||
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
||||
raise
|
||||
except paramiko.SSHException as e:
|
||||
logger.error("SSH connection error: %s", e)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("Unexpected SSH error: %s", e)
|
||||
raise
|
||||
|
||||
self._client = client
|
||||
return self._client
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
cmd_display = command[:150] + "..." if len(command) > 150 else command
|
||||
logger.debug("SSH executing: %s", cmd_display)
|
||||
|
||||
try:
|
||||
client = self._get_client()
|
||||
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
||||
out = stdout.read().decode("utf-8", errors="replace")
|
||||
err = stderr.read().decode("utf-8", errors="replace")
|
||||
rc = stdout.channel.recv_exit_status()
|
||||
|
||||
logger.debug("SSH result: rc=%d, stdout_len=%d, stderr_len=%d", rc, len(out), len(err))
|
||||
if err and rc != 0:
|
||||
logger.warning("SSH stderr (rc=%d): %s", rc, err[:200])
|
||||
if rc != 0:
|
||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_display, err[:100] if err else "none")
|
||||
return out, err, rc
|
||||
except paramiko.SSHException as e:
|
||||
logger.error("SSH command error (%s): %s", self.host, e)
|
||||
self._client = None
|
||||
return "", str(e), -1
|
||||
except Exception as ex:
|
||||
logger.error("Unexpected SSH command error (%s): %s", self.host, ex)
|
||||
self._client = None
|
||||
return "", str(ex), -1
|
||||
|
||||
def check_connection(self):
|
||||
try:
|
||||
out, err, rc = self.run("echo ok", timeout=10)
|
||||
if rc == 0 and "ok" in out:
|
||||
logger.debug("SSH connection check passed")
|
||||
return True
|
||||
logger.warning("SSH connection check failed: rc=%d, out=%s", rc, out[:50])
|
||||
return False
|
||||
except Exception:
|
||||
logger.warning("SSH connection check failed with exception")
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
with self._lock:
|
||||
if self._client:
|
||||
try:
|
||||
self._client.close()
|
||||
logger.debug("SSH connection closed")
|
||||
except Exception as e:
|
||||
logger.debug("Error closing SSH connection: %s", e)
|
||||
self._client = None
|
||||
@@ -0,0 +1,35 @@
|
||||
# World service — partitions, spice, teleport.
|
||||
|
||||
import logging
|
||||
|
||||
from app.models import PartitionInfo
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WorldService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def get_partitions(self, map_name: str = "") -> list[PartitionInfo]:
|
||||
rows = self.db.call_function("get_partitions", [map_name])
|
||||
return [PartitionInfo(
|
||||
id=r.get("partition_id", 0),
|
||||
map=r.get("map", ""),
|
||||
dimension_index=r.get("dimension_index", 0),
|
||||
label=r.get("label", ""),
|
||||
definition=str(r.get("partition_definition", "")),
|
||||
) for r in rows]
|
||||
|
||||
def teleport(self, fls_id: str, partition_id: int, x: float, y: float, z: float) -> bool:
|
||||
self.db.call_procedure("admin_move_offline_player_to_partition", [fls_id, partition_id, (x, y, z)])
|
||||
return True
|
||||
|
||||
def reset_spice(self, map_name: str, dimension_index: int) -> bool:
|
||||
self.db.call_procedure("reset_global_spice_field_state", [map_name, dimension_index])
|
||||
return True
|
||||
|
||||
def force_spice_spawn(self, server_id: str, spicefield_type_id: int) -> bool:
|
||||
self.db.call_procedure("try_spawn_spicefield", [server_id, spicefield_type_id])
|
||||
return True
|
||||
Reference in new issue
Block a user