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:
Reditus committed 2026-05-23 07:08:30 +01:00
1 parent fa620f4da9
commit be845f76f1
76 files changed
+8410 -10

No files matched your search

+12 -1
View File
@@ -4,10 +4,15 @@ __pycache__/
*$py.class
*.egg-info/
*.egg
dist/
dist/*.egg
build/
*.whl
# Frontend
frontend/node_modules/
frontend/.pnpm-store/
frontend/.vite/
# Virtual environments
venv/
env/
@@ -103,3 +108,9 @@ app/logs/
# Local settings with real credentials
app/settings.yaml
# Node artifacts
node_modules/
package-lock.json
yarn.lock
pnpm-lock.yaml
+96 -9
View File
@@ -32,12 +32,12 @@ If you're testing this project, grab builds from nightly for the latest features
## Features
- **Map Features**: Interactive maps with real-world coordinate calibration for Hagga Basin and The Deep Desert. Default view centers on Hagga Basin at 15% zoom. Zoom range: 15%–100%.
- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations.
- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. Rich detail view with vitals, currency, inventory, vehicles, buildings, landclaims, specialization, keystones, and faction reputation.
- **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh.
- **Director Controls**: Live battlegroup stats, world state management, and server transfer controls.
- **File Browser**: Secure SSH-based file browser for server configuration and logs.
- **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser.
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, and player history.
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface.
- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page.
- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures.
- **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard.
@@ -59,6 +59,7 @@ This project is **Source Available** under the [Dune Dashboard Source License (D
## Requirements
- Python 3.8+
- Node.js 18+ (for frontend development/build)
- OpenSSH client
- `kubectl` access to the Dune: Awakening Kubernetes cluster
- SSH access to the game server VM
@@ -207,13 +208,36 @@ SSL certificates are automatically regenerated when they approach expiry:
```
DuneDashboard/
├── app/ # Core application package
│ ├── routes/ # HTTP route handlers
│ ├── services/ # Business logic (DB, SSH, K8s, etc.)
│ ├── utils/ # Helpers and constants
│ └── websocket/ # Socket.IO handlers
├── templates/ # Jinja2 HTML templates
├── static/ # CSS and frontend assets
├── backend/ # New Flask backend (API + services)
│ ├── app/
│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat)
│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.)
│ │ ├── models/ # Pydantic v2 models
│ │ ├── websocket/ # Socket.IO shell handler
│ │ ├── config.py # Settings loader
│ │ └── factory.py # App factory (services, blueprints, security)
│ ├── run.py # Entry point
│ └── requirements.txt # Python dependencies
│
├── frontend/ # New React SPA (Vite + TypeScript + Tailwind)
│ ├── src/
│ │ ├── components/ # Pages (overview, players, guilds, vehicles, buildings, map, accounts, server, admin, chat, shell, files, director, settings)
│ │ ├── api/ # Axios client
│ │ ├── stores/ # React Context (app state, auth, theme)
│ │ ├── hooks/ # Custom hooks (realtime, debounce)
│ │ └── styles/ # Tailwind + 14 Dune themes
│ ├── index.html
│ ├── package.json
│ ├── vite.config.ts
│ └── tsconfig.json
│
├── app/ # Legacy Flask/Jinja2 dashboard (untouched, still functional)
│ ├── routes/
│ ├── services/
│ ├── utils/
│ └── websocket/
├── templates/ # Legacy Jinja2 HTML templates
├── static/ # Legacy CSS and frontend assets
├── scripts/ # Pre-flight utilities (db_check.py)
├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools)
├── start.sh # Linux/macOS entry point
@@ -221,12 +245,49 @@ DuneDashboard/
└── settings.yaml.example # Reference configuration
```
> **Note**: The legacy `app/`, `templates/`, and `static/` directories remain untouched and functional. The new system lives in `backend/` and `frontend/`. Both can coexist during migration.
## Architecture
### Frontend
- **React 18** with TypeScript
- **Vite** for fast builds and HMR
- **Tailwind CSS** for styling with 14 Dune house themes
- **SWR** for server state caching and revalidation
- **Axios** for HTTP requests with 401 redirect handling
- **Socket.IO Client** for the remote terminal
- **xterm.js** for the in-browser shell
### Backend
- **Flask 3** with Blueprint-based routing
- **Pydantic v2** for request/response validation
- **psycopg3** with connection pooling for PostgreSQL
- **Flask-SocketIO** for the interactive shell
- **Flask-Login** for session-based authentication (Argon2 password hashing)
- **Flask-Limiter** for rate limiting
- **SSE (Server-Sent Events)** for real-time updates (battlegroup, chat, metrics)
### Services
- `DatabaseService` — psycopg3 pool, stored procedure executor, audit table DDL
- `SSHService` — paramiko SSH client for tunneling and remote commands
- `K8sService` — kubectl-over-SSH for pod/deployment management
- `BgDirectorService` — HTTP client for the Battlegroup Director API
- `RmqAdminService` — RabbitMQ Management HTTP API client
- `RmqGameService` — RabbitMQ Game HTTP API client (broadcasts, chat intercept)
- `RealtimeService` — SSE broadcaster with background polling loops
- `PlayerService` / `EconomyService` / `GuildService` / `WorldService` / `ProgressionService` / `CharacterService` — DB-function-only domain services
- `AuditService` — persistent PostgreSQL audit logging
- `ChatService` — chat history + pod log catch-up
## Security Notes
- Never commit `settings.yaml` to version control.
- SSH keys are copied to `%TEMP%` with restricted permissions during startup.
- All database queries use parameterized statements to prevent SQL injection.
- Dashboard authentication is required by default.
- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked.
- All mutations are audited to PostgreSQL.
- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode.
## Logging
@@ -268,3 +329,29 @@ Console output is **not** sanitized so you can see full details during operation
- Files exceeding **10 MB** are truncated (keeps last 5000 lines)
- Empty category directories are removed
- Cleanup runs automatically on every launcher start
## Development
### Frontend Development
```bash
cd frontend
npm install
npm run dev # Vite dev server with API proxy to localhost:5050
npm run build # Production build to frontend/dist/
```
### Backend Development
```bash
cd backend
pip install -r requirements.txt
python run.py # Or: flask --app run:app run
```
### Themes
The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar:
Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM.
Themes are implemented via CSS custom properties (`var(--primary)`, `var(--bg)`, etc.) and switched by setting `data-theme` on the `<html>` element.
+1
View File
@@ -0,0 +1 @@
# Backend package init.
+286
View File
@@ -0,0 +1,286 @@
"""Settings loader — reads settings.yaml with env var overrides."""
import os
import socket
import yaml
import logging
import copy
import secrets
logger = logging.getLogger(__name__)
DEFAULTS = {
"server": {
"host": "127.0.0.1",
"user": "dune",
"ssh_key": None,
"local_ip": None,
},
"dashboard": {
"host": "127.0.0.1",
"port": 5050,
"debug": False,
"secret_key": None,
"ssl_cert": None,
"ssl_key": None,
"ssl_domain": None,
"ssl_email": None,
"http_redirect": False,
"http_redirect_port": 80,
},
"database": {
"host": "127.0.0.1",
"port": 15433,
"user": "postgres",
"password": None,
"name": "dune",
"schema": "dune",
"min_connections": 2,
"max_connections": 10,
"owner": "dune",
"dashboard_schema": "dashboard",
},
"kubernetes": {
"namespace": "",
"battlegroup_script": "/home/dune/.dune/bin/battlegroup",
},
"director": {
"port": 32479,
"host": "127.0.0.1",
},
"rmq": {
"admin_host": "127.0.0.1",
"admin_port": 32686,
"game_host": "127.0.0.1",
"game_port": 32021,
"username": "admin",
"password": "@5bkR636nz3TxML@",
"vhost": "%2f",
},
"filebrowser": {
"port": 18888,
},
"firewall": {
"block_filebrowser": True,
"block_director": True,
},
"cache": {
"chat_pod_ttl": 60,
"chat_messages_ttl": 10,
"static_data_ttl": 300,
"bgd_ttl": 10,
"rmq_ttl": 15,
},
"auth": {
"enabled": True,
"username": None,
"password_hash": None,
"shell_enabled": True,
},
"logging": {
"level": "INFO",
"file": "logs/dashboard.log",
"debug_file": "logs/debug.log",
"debug_enabled": False,
"max_bytes": 10485760,
"backup_count": 5,
},
"ssl": {
"check_interval_hours": 24,
"renewal_days_before_expiry": 30,
},
"maps": {
"default_map": "HaggaBasin",
"DeepDesert": {
"image": "maps/Deep_Desert.webp",
"label": "The Deep Desert",
"bounds": {
"min_x": -1268624.82,
"max_x": 1163312.83,
"min_y": -1266548.17,
"max_y": 1162416.13,
},
"flip_y": False,
"image_size": {"width": 8000, "height": 8000},
"default_zoom": 0.15,
},
"HaggaBasin": {
"image": "maps/HaggaBasin_8k.webp",
"label": "Hagga Basin",
"bounds": {
"min_x": -456752.21,
"max_x": 354547.46,
"min_y": -450630.14,
"max_y": 353821.95,
},
"flip_y": False,
"image_size": {"width": 8000, "height": 8000},
"default_zoom": 0.15,
},
},
}
def deep_merge(base, override):
"""Deep merge override dict into base dict."""
result = base.copy()
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def _detect_local_ip():
"""Detect local IP address for VM connectivity."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
s.close()
if local_ip:
logger.debug(f"Detected local IP: {local_ip}")
return local_ip
except Exception as e:
logger.debug(f"Could not detect local IP: {e}")
return "127.0.0.1"
def _validate_server_host(settings):
"""Validate and fix server.host if invalid or placeholder."""
server = settings.setdefault("server", {})
host = server.get("host", "")
local_ip = server.get("local_ip")
if local_ip:
local_ip_str = str(local_ip).strip()
if local_ip_str and local_ip_str not in ("", "null", "None", "YOUR_SERVER_IP", "YOUR_VM_IP"):
if local_ip_str.count(".") == 3 and all(part.isdigit() and 0 <= int(part) <= 255 for part in local_ip_str.split(".")):
server["host"] = local_ip_str
logger.info(f"Using server.local_ip override: {server['host']}")
return settings
host_str = str(host).strip() if host else ""
invalid_hosts = ("", "YOUR_SERVER_IP", "YOUR_VM_IP", "null", "None")
if host_str in invalid_hosts or not host_str:
detected_ip = _detect_local_ip()
server["host"] = detected_ip
logger.warning(f"Invalid server.host detected, using auto-detected IP: {detected_ip}")
logger.warning("To fix: Edit settings.yaml and set server.host to your VM's IP address")
return settings
def _find_missing_keys(defaults, current, path=""):
"""Find keys present in defaults but missing in current."""
missing = []
for key, val in defaults.items():
new_path = f"{path}.{key}" if path else key
if key not in current:
missing.append(new_path)
elif isinstance(val, dict) and isinstance(current.get(key), dict):
missing.extend(_find_missing_keys(val, current[key], new_path))
return missing
def load_settings(settings_path=None):
"""Load settings from YAML file with defaults and env var overrides."""
if settings_path is None:
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml")
settings = copy.deepcopy(DEFAULTS)
if os.path.exists(settings_path):
try:
with open(settings_path, "r") as f:
file_settings = yaml.safe_load(f) or {}
settings = deep_merge(settings, file_settings)
logger.info(f"Settings loaded from {settings_path}")
except Exception as e:
logger.error(f"Failed to load settings from {settings_path}: {e}")
logger.warning("Using default settings")
else:
logger.warning(f"Settings file not found at {settings_path}, using defaults")
env_overrides = {}
if os.environ.get("DUNE_SERVER_HOST"):
env_overrides.setdefault("server", {})["host"] = os.environ["DUNE_SERVER_HOST"]
if os.environ.get("DUNE_SERVER_USER"):
env_overrides.setdefault("server", {})["user"] = os.environ["DUNE_SERVER_USER"]
if os.environ.get("DUNE_DB_PASSWORD"):
env_overrides.setdefault("database", {})["password"] = os.environ["DUNE_DB_PASSWORD"]
if os.environ.get("DUNE_K8S_NAMESPACE"):
env_overrides.setdefault("kubernetes", {})["namespace"] = os.environ["DUNE_K8S_NAMESPACE"]
if os.environ.get("DUNE_AUTH_PASSWORD"):
env_overrides.setdefault("auth", {})["password"] = os.environ["DUNE_AUTH_PASSWORD"]
if os.environ.get("DUNE_DASHBOARD_PORT"):
env_overrides.setdefault("dashboard", {})["port"] = int(os.environ["DUNE_DASHBOARD_PORT"])
if os.environ.get("DUNE_RMQ_PASSWORD"):
env_overrides.setdefault("rmq", {})["password"] = os.environ["DUNE_RMQ_PASSWORD"]
if env_overrides:
settings = deep_merge(settings, env_overrides)
logger.info("Environment variable overrides applied")
if not settings["dashboard"].get("secret_key"):
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
logger.info("Generated secure SECRET_KEY")
auth = settings.get("auth", {})
password_migrated = False
if auth.get("password") and not auth.get("password_hash"):
try:
from argon2 import PasswordHasher
ph = PasswordHasher(time_cost=3, memory_cost=65536)
settings["auth"]["password_hash"] = ph.hash(str(auth["password"]))
del settings["auth"]["password"]
password_migrated = True
logger.info("Migrated plaintext password to Argon2 hash")
except ImportError:
logger.error("argon2-cffi not installed. Password hashing unavailable.")
settings["auth"]["password_hash"] = None
if password_migrated:
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
logger.warning("Rotated secret_key to invalidate sessions after password migration")
settings = _validate_server_host(settings)
return settings
_settings_cache = None
def get_settings():
"""Get current settings (cached for performance)."""
global _settings_cache
if _settings_cache is None:
_settings_cache = load_settings()
return _settings_cache
def save_settings(settings):
"""Save settings to YAML file."""
global _settings_cache
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml")
try:
with open(settings_path, "w") as f:
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
_settings_cache = settings
logger.info(f"Settings saved to {settings_path}")
return True
except Exception as e:
logger.error(f"Failed to save settings to {settings_path}: {e}")
return False
def reload_settings():
"""Force reload settings from file."""
global _settings_cache
_settings_cache = load_settings()
return _settings_cache
+303
View File
@@ -0,0 +1,303 @@
# Application factory — creates and configures the Flask app.
import os
import sys
import logging
import logging.handlers
from datetime import datetime
from flask import Flask, jsonify, request, g, send_from_directory
from flask_cors import CORS
from flask_login import current_user
from flask_socketio import SocketIO
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from app.config import load_settings
from app.routes.auth import auth_bp, init_auth
from app.routes.health import health_bp
from app.routes.api import api_bp
from app.routes.director import director_bp
from app.routes.server import server_bp
from app.routes.files import files_bp
from app.routes.debug import debug_bp
from app.routes.chat import chat_bp
from app.websocket.shell import register_websocket_handlers
from app.services.database import DatabaseService
from app.services.ssh import SSHService
from app.services.k8s import K8sService
from app.services.bg_director import BgDirectorService
from app.services.rmq_admin import RmqAdminService
from app.services.rmq_game import RmqGameService
from app.services.realtime import RealtimeService
from app.services.player import PlayerService
from app.services.economy import EconomyService
from app.services.guild import GuildService
from app.services.world import WorldService
from app.services.progression import ProgressionService
from app.services.character import CharacterService
from app.services.audit import AuditService
from app.services.chat import ChatService
_services = None
def get_services():
global _services
return _services
def create_app(settings_path=None):
global _services
settings = load_settings(settings_path)
base_dir = os.path.dirname(os.path.dirname(__file__))
app = Flask(
__name__,
template_folder=os.path.join(base_dir, "frontend", "dist"),
static_folder=os.path.join(base_dir, "frontend", "dist", "assets"),
static_url_path="/assets",
)
app.config["SECRET_KEY"] = settings["dashboard"]["secret_key"]
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["WTF_CSRF_ENABLED"] = True
app.config["WTF_CSRF_TIME_LIMIT"] = None
CORS(app, resources={r"/api/*": {"origins": "*"}})
ssl_enabled = bool(
settings["dashboard"].get("ssl_cert")
and settings["dashboard"].get("ssl_key")
and settings["dashboard"]["ssl_cert"] != "null"
and settings["dashboard"]["ssl_key"] != "null"
)
app.config["SESSION_COOKIE_SECURE"] = ssl_enabled
if not settings["dashboard"]["debug"]:
@app.after_request
def add_security_headers(response):
if ssl_enabled:
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self' ws: wss:; "
"frame-ancestors 'self'; "
"base-uri 'self'; "
"form-action 'self'"
)
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
return response
# Error handlers
@app.errorhandler(Exception)
def handle_exception(e):
logging.exception("Unhandled exception: %s", e)
from app.models import ApiResponse, ErrorDetail
if settings["dashboard"].get("debug", False):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InternalError", message=str(e)),
).model_dump()), 500
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InternalError", message="An internal error occurred"),
).model_dump()), 500
@app.errorhandler(404)
def handle_not_found(e):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Resource not found"),
).model_dump()), 404
@app.errorhandler(405)
def handle_method_not_allowed(e):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="MethodNotAllowed", message="Method not allowed"),
).model_dump()), 405
# Request logging
@app.before_request
def before_request_logging():
import time as _time
g._request_start_time = _time.time()
@app.after_request
def after_request_logging(response):
import time as _time
duration = _time.time() - g.get("_request_start_time", _time.time())
user = current_user.id if current_user.is_authenticated else "anonymous"
if request.path.startswith("/api") or request.path.startswith("/server"):
logging.info("%s %s %d %.3fs user=%s", request.method, request.path, response.status_code, duration, user)
response.headers["X-Response-Time"] = f"{duration:.3f}s"
return response
_setup_logging(settings)
# ── Services ─────────────────────────────────────────────────
db_config = {
"host": settings["database"]["host"],
"port": settings["database"]["port"],
"user": settings["database"]["user"],
"password": settings["database"]["password"],
"database": settings["database"]["name"],
}
db_service = DatabaseService(
db_config,
min_conn=settings["database"]["min_connections"],
max_conn=settings["database"]["max_connections"],
dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"),
)
db_service.ensure_tables()
ssh_service = SSHService(
host=settings["server"]["host"],
user=settings["server"]["user"],
ssh_key=settings["server"].get("ssh_key"),
)
k8s_service = K8sService(
ssh_service=ssh_service,
namespace=settings["kubernetes"]["namespace"],
)
bg_director = BgDirectorService(
host=settings["director"].get("host", "127.0.0.1"),
node_port=settings["director"].get("port", 32479),
)
rmq_admin = RmqAdminService(
host=settings["rmq"]["admin_host"],
port=settings["rmq"]["admin_port"],
username=settings["rmq"]["username"],
password=settings["rmq"]["password"],
)
rmq_game = RmqGameService(
host=settings["rmq"]["game_host"],
port=settings["rmq"]["game_port"],
username=settings["rmq"]["username"],
password=settings["rmq"]["password"],
)
player_svc = PlayerService(db_service)
economy_svc = EconomyService(db_service)
guild_svc = GuildService(db_service)
world_svc = WorldService(db_service)
progression_svc = ProgressionService(db_service)
character_svc = CharacterService(db_service)
audit_svc = AuditService(db_service)
chat_svc = ChatService(db_service, k8s_service, ssh_service)
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
realtime_svc.start()
_services = {
"db": db_service,
"ssh": ssh_service,
"k8s": k8s_service,
"bg_director": bg_director,
"rmq_admin": rmq_admin,
"rmq_game": rmq_game,
"realtime": realtime_svc,
"player": player_svc,
"economy": economy_svc,
"guild": guild_svc,
"world": world_svc,
"progression": progression_svc,
"character": character_svc,
"audit": audit_svc,
"chat": chat_svc,
}
app.dune_settings = settings
app.dune_services = _services
# ── Blueprints ───────────────────────────────────────────────
init_auth(app, settings)
app.register_blueprint(auth_bp, url_prefix="/api/auth")
app.register_blueprint(health_bp, url_prefix="/api")
app.register_blueprint(api_bp, url_prefix="/api")
app.register_blueprint(director_bp, url_prefix="/api/director")
app.register_blueprint(server_bp, url_prefix="/api/server")
app.register_blueprint(files_bp, url_prefix="/api/files")
app.register_blueprint(chat_bp, url_prefix="/api/chat")
app.register_blueprint(debug_bp, url_prefix="/api/debug")
# ── SocketIO ─────────────────────────────────────────────────
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
register_websocket_handlers(socketio, settings)
app.socketio = socketio
# ── Rate Limiter ─────────────────────────────────────────────
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=[],
storage_uri="memory://",
)
app.limiter = limiter
# ── Catch-all for React SPA ─────────────────────────────────
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_react(path):
if path.startswith("api/") or path.startswith("server/") or path.startswith("static/") or path.startswith("assets/"):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Resource not found"),
).model_dump()), 404
return send_from_directory(os.path.join(base_dir, "frontend", "dist"), "index.html")
# ── Auto-detect namespace if empty ───────────────────────────
if settings["kubernetes"]["namespace"] == "":
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings["kubernetes"]["namespace"] = k8s_service.namespace
except Exception as e:
logging.warning("Could not auto-detect K8s namespace: %s", e)
return app
def _setup_logging(settings):
log_level = getattr(logging, settings["logging"]["level"].upper(), logging.INFO)
log_file = settings["logging"]["file"]
os.makedirs(os.path.dirname(log_file), exist_ok=True)
handler = logging.handlers.RotatingFileHandler(
log_file,
maxBytes=settings["logging"]["max_bytes"],
backupCount=settings["logging"]["backup_count"],
)
handler.setFormatter(logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
))
handler.setLevel(log_level)
console = logging.StreamHandler(sys.stdout)
console.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
console.setLevel(log_level)
root = logging.getLogger()
root.setLevel(log_level)
root.addHandler(handler)
root.addHandler(console)
+232
View File
@@ -0,0 +1,232 @@
# Pydantic models for the Dune Admin Dashboard API.
from pydantic import BaseModel, Field
from typing import Any, List, Optional
class ErrorDetail(BaseModel):
code: str
message: str
details: Optional[Any] = None
class ApiResponse(BaseModel):
success: bool
data: Optional[Any] = None
error: Optional[ErrorDetail] = None
# ── Player Models ───────────────────────────────────────────────
class Vitals(BaseModel):
current_health: Optional[float] = None
max_health: Optional[float] = None
current_hydration: Optional[float] = None
dehydration_penalty: Optional[float] = None
current_spice: Optional[float] = None
spice_addiction_level: Optional[float] = None
spice_tolerance: Optional[float] = None
class CurrencyBalance(BaseModel):
currency_id: int
currency_label: str
balance: float = 0.0
class Item(BaseModel):
id: Optional[int] = None
template_id: str = ""
stack_size: int = 1
quality_level: int = 0
is_new: bool = False
position_index: int = 0
stats: Optional[Any] = None
durability: Optional[float] = None
max_durability: Optional[float] = None
ammo: Optional[int] = None
class Inventory(BaseModel):
inventory_id: int
actor_id: Optional[int] = None
inventory_type: int = 0
inventory_type_label: str = ""
max_item_count: Optional[int] = None
max_item_volume: Optional[float] = None
items: List[Item] = []
class VehicleSummary(BaseModel):
id: Optional[int] = None
class_name: str = ""
display_name: str = ""
map: Optional[str] = None
class BuildingSummary(BaseModel):
id: Optional[int] = None
class_name: str = ""
map: Optional[str] = None
owner_name: str = ""
instance_count: int = 0
is_powered: bool = False
power_level: Optional[Any] = None
class Landclaim(BaseModel):
id: Optional[int] = None
class_name: str = ""
map: Optional[str] = None
class SpecializationTrack(BaseModel):
track_type: str = ""
xp_amount: int = 0
level: int = 0
class Keystone(BaseModel):
id: int
name: str = ""
class FactionReputation(BaseModel):
faction_id: Optional[int] = None
faction_name: str = ""
reputation_amount: int = 0
class LandsraadInfo(BaseModel):
daily_reward_charges: Optional[int] = None
last_viewed_term_id: Optional[int] = None
daily_reward_last_processed: Optional[Any] = None
class PlayerSummary(BaseModel):
player_controller_id: Optional[int] = None
character_name: str = "Unknown"
account_email: Optional[str] = None
funcom_id: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
map: Optional[str] = None
online_status: str = "Unknown"
life_state: Optional[str] = None
last_login_time: Optional[str] = None
last_avatar_activity: Optional[str] = None
class PlayerDetail(BaseModel):
id: Optional[int] = None
account_id: int
player_controller_id: Optional[int] = None
player_pawn_id: Optional[int] = None
character_name: str = "Unknown"
account_email: Optional[str] = None
funcom_id: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
map: Optional[str] = None
online_status: str = "Unknown"
life_state: Optional[str] = None
last_login_time: Optional[str] = None
last_avatar_activity: Optional[str] = None
vitals: Optional[Vitals] = None
currency: List[CurrencyBalance] = []
inventories: List[Inventory] = []
vehicles: List[VehicleSummary] = []
buildings: List[BuildingSummary] = []
landclaims: List[Landclaim] = []
specialization: List[SpecializationTrack] = []
keystones: List[Keystone] = []
faction_reputation: List[FactionReputation] = []
landsraad: Optional[LandsraadInfo] = None
tags: List[str] = []
is_online: bool = False
# ── Guild Models ────────────────────────────────────────────────
class GuildMember(BaseModel):
player_id: int
role_id: int = 50
role_name: str = "Member"
player_name: str = "Unknown"
online_status: str = "Unknown"
class GuildSummary(BaseModel):
guild_id: int
guild_name: str = ""
guild_description: Optional[str] = None
faction_name: Optional[str] = None
member_count: int = 0
online_count: int = 0
class GuildDetail(BaseModel):
guild_id: int
guild_name: str = ""
guild_description: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
members: List[GuildMember] = []
# ── World Models ───────────────────────────────────────────────
class PartitionInfo(BaseModel):
partition_id: int
name: str = ""
map: Optional[str] = None
player_count: int = 0
status: str = "unknown"
# ── RMQ Models ────────────────────────────────────────────────
class RmqQueueInfo(BaseModel):
name: str
messages: int = 0
consumers: int = 0
state: str = ""
class RmqOverview(BaseModel):
queues: List[RmqQueueInfo] = []
total_messages: int = 0
total_consumers: int = 0
# ── BGD Models ────────────────────────────────────────────────
class BattlegroupState(BaseModel):
battlegroup_id: Optional[int] = None
name: Optional[str] = None
status: Optional[str] = None
player_count: Optional[int] = None
servers: Optional[List[Any]] = None
# ── Request Models ─────────────────────────────────────────────
class BroadcastRequest(BaseModel):
message: str = Field(..., min_length=1, max_length=500)
server: Optional[str] = None
partition: Optional[str] = None
class TeleportRequest(BaseModel):
player_id: int
destination: str = Field(..., min_length=1)
class FunctionExecuteRequest(BaseModel):
schema_name: Optional[str] = Field(default=None, alias="schema")
function: str = Field(..., min_length=1)
args: dict = {}
class RawQueryRequest(BaseModel):
query: str = Field(..., min_length=1)
+1
View File
@@ -0,0 +1 @@
# Routes package init.
+971
View File
@@ -0,0 +1,971 @@
# Main API routes — players, guilds, economy, world, progression, character, admin.
import logging
from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from pydantic import ValidationError
from app.models import (
ApiResponse, ErrorDetail, PlayerDetail, BroadcastRequest,
TeleportRequest, FunctionExecuteRequest, RawQueryRequest,
)
api_bp = Blueprint("api", __name__)
logger = logging.getLogger(__name__)
def _audit(action: str, details: dict | None = None, target_player_id: int | None = None, severity: str = "info"):
from app.factory import get_services
services = get_services()
audit = services.get("audit")
if audit:
audit.log(
action=action,
user=current_user.id if current_user.is_authenticated else "anonymous",
details=details,
target_player_id=target_player_id,
severity=severity,
source_ip=request.remote_addr,
)
@api_bp.errorhandler(ValidationError)
def handle_validation_error(e):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
# ── Player Endpoints ──────────────────────────────────────────────
@api_bp.route("/players", methods=["GET"])
@login_required
def list_players():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 50))
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term, limit=limit)
return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump())
@api_bp.route("/players/search", methods=["POST"])
@login_required
def search_players():
data = request.get_json() or {}
term = data.get("term", "")
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term)
return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump())
@api_bp.route("/players/<int:account_id>", methods=["GET"])
@login_required
def get_player(account_id):
from app.factory import get_services
svc = get_services()["player"]
detail = svc.get_detail(account_id)
if not detail:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=detail.model_dump()).model_dump())
@api_bp.route("/players/<int:account_id>/inventory", methods=["GET"])
@login_required
def get_player_inventory(account_id):
from app.factory import get_services
svc = get_services()["economy"]
inventories = svc.get_inventory(account_id)
return jsonify(ApiResponse(success=True, data=[inv.model_dump() for inv in inventories]).model_dump())
@api_bp.route("/players/<int:account_id>/currency", methods=["GET"])
@login_required
def get_player_currency(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
if not detail or not detail.player_controller_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player controller not found"),
).model_dump()), 404
econ = get_services()["economy"]
currency = econ.get_currency(detail.player_controller_id)
return jsonify(ApiResponse(success=True, data=[c.model_dump() for c in currency]).model_dump())
@api_bp.route("/players/<int:account_id>/vitals", methods=["GET"])
@login_required
def get_player_vitals(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
if not detail or not detail.player_pawn_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player pawn not found"),
).model_dump()), 404
econ = get_services()["economy"]
vitals = econ.get_vitals(detail.player_pawn_id)
return jsonify(ApiResponse(success=True, data=vitals.model_dump()).model_dump())
# ── Economy Mutations ────────────────────────────────────────────
@api_bp.route("/items/add", methods=["POST"])
@login_required
def add_item():
data = request.get_json() or {}
inventory_id = data.get("inventory_id")
template_id = data.get("template_id")
stack_size = data.get("stack_size", 1)
quality_level = data.get("quality_level", 0)
if not inventory_id or not template_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing inventory_id or template_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
item_id = svc.add_item(inventory_id, template_id, stack_size, quality_level)
_audit("item_add", {"inventory_id": inventory_id, "template_id": template_id, "item_id": item_id})
return jsonify(ApiResponse(success=True, data={"item_id": item_id}).model_dump())
@api_bp.route("/items/<int:item_id>", methods=["DELETE"])
@login_required
def delete_item(item_id):
from app.factory import get_services
svc = get_services()["economy"]
svc.delete_item(item_id)
_audit("item_delete", {"item_id": item_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/items/<int:item_id>", methods=["PATCH"])
@login_required
def edit_item(item_id):
data = request.get_json() or {}
field = data.get("field")
value = data.get("value")
if not field or value is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing field or value"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.edit_item_field(item_id, field, value)
_audit("item_edit", {"item_id": item_id, "field": field, "value": value})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/currency/adjust", methods=["POST"])
@login_required
def adjust_currency():
data = request.get_json() or {}
controller_id = data.get("controller_id")
currency_id = data.get("currency_id")
delta = data.get("delta")
if controller_id is None or currency_id is None or delta is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
new_balance = svc.adjust_currency(controller_id, currency_id, delta)
_audit("currency_adjust", {"controller_id": controller_id, "currency_id": currency_id, "delta": delta, "new_balance": new_balance}, target_player_id=controller_id)
return jsonify(ApiResponse(success=True, data={"new_balance": new_balance}).model_dump())
@api_bp.route("/currency/set", methods=["POST"])
@login_required
def set_currency():
data = request.get_json() or {}
controller_id = data.get("controller_id")
currency_id = data.get("currency_id")
balance = data.get("balance")
if controller_id is None or currency_id is None or balance is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.set_currency(controller_id, currency_id, balance)
_audit("currency_set", {"controller_id": controller_id, "currency_id": currency_id, "balance": balance}, target_player_id=controller_id)
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/vitals/set", methods=["POST"])
@login_required
def set_vitals():
data = request.get_json() or {}
pawn_id = data.get("pawn_id")
health = data.get("health")
max_health = data.get("max_health")
hydration = data.get("hydration")
spice = data.get("spice")
if pawn_id is None or hydration is None or spice is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.set_vitals(pawn_id, health, max_health, hydration, spice)
_audit("vitals_edit", {"pawn_id": pawn_id, "health": health, "max_health": max_health, "hydration": hydration, "spice": spice})
return jsonify(ApiResponse(success=True).model_dump())
# ── Guild Endpoints ──────────────────────────────────────────────
@api_bp.route("/guilds", methods=["GET"])
@login_required
def list_guilds():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 50))
from app.factory import get_services
svc = get_services()["guild"]
guilds = svc.list_all()
if term:
guilds = [g for g in guilds if term.lower() in g.guild_name.lower()]
return jsonify(ApiResponse(success=True, data=[g.model_dump() for g in guilds[:limit]]).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["GET"])
@login_required
def get_guild(guild_id):
from app.factory import get_services
svc = get_services()["guild"]
guild = svc.get_detail(guild_id)
if not guild:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Guild not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=guild.model_dump()).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["DELETE"])
@login_required
def disband_guild(guild_id):
from app.factory import get_services
svc = get_services()["guild"]
svc.disband(guild_id)
_audit("guild_disband", {"guild_id": guild_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>", methods=["DELETE"])
@login_required
def remove_guild_member(guild_id, player_id):
from app.factory import get_services
svc = get_services()["guild"]
svc.remove_member(guild_id, player_id)
_audit("guild_kick", {"guild_id": guild_id, "player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>/role", methods=["PUT"])
@login_required
def set_guild_role(guild_id, player_id):
data = request.get_json() or {}
role_id = data.get("role_id")
action = data.get("action", "promote")
if role_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing role_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["guild"]
if action == "promote":
svc.promote(guild_id, player_id, role_id)
else:
svc.demote(guild_id, player_id, role_id)
_audit(f"guild_{action}", {"guild_id": guild_id, "player_id": player_id, "role_id": role_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── World Endpoints ──────────────────────────────────────────────
@api_bp.route("/partitions", methods=["GET"])
@login_required
def list_partitions():
map_name = request.args.get("map", "")
from app.factory import get_services
svc = get_services()["world"]
partitions = svc.get_partitions(map_name)
return jsonify(ApiResponse(success=True, data=[p.model_dump() for p in partitions]).model_dump())
@api_bp.route("/teleport", methods=["POST"])
@login_required
def teleport():
data = request.get_json() or {}
try:
req = TeleportRequest(**data)
except ValidationError as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.teleport(req.fls_id, req.partition_id, req.x, req.y, req.z)
_audit("player_teleport", {"fls_id": req.fls_id, "partition_id": req.partition_id, "coords": [req.x, req.y, req.z]})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/spice/reset", methods=["POST"])
@login_required
def reset_spice():
data = request.get_json() or {}
map_name = data.get("map_name")
dimension_index = data.get("dimension_index", 0)
if not map_name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing map_name"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.reset_spice(map_name, dimension_index)
_audit("spice_reset", {"map": map_name, "dimension": dimension_index})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/spice/spawn", methods=["POST"])
@login_required
def force_spice_spawn():
data = request.get_json() or {}
server_id = data.get("server_id")
spicefield_type_id = data.get("spicefield_type_id")
if not server_id or spicefield_type_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.force_spice_spawn(server_id, spicefield_type_id)
_audit("spice_spawn", {"server_id": server_id, "spicefield_type_id": spicefield_type_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── Progression Endpoints ────────────────────────────────────────
@api_bp.route("/progression/journey", methods=["POST"])
@login_required
def journey_action():
data = request.get_json() or {}
player_id = data.get("player_id")
node_ids = data.get("node_ids", [])
action = data.get("action", "complete")
if not player_id or not node_ids:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id or node_ids"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
if action == "complete":
svc.complete_nodes(player_id, node_ids)
elif action == "reveal":
svc.reveal_nodes(player_id, node_ids)
elif action == "reset":
svc.reset_nodes(player_id, node_ids)
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Invalid action"),
).model_dump()), 400
_audit(f"journey_{action}", {"player_id": player_id, "node_ids": node_ids})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/progression/specialization", methods=["POST"])
@login_required
def set_specialization():
data = request.get_json() or {}
player_id = data.get("player_id")
track_type = data.get("track_type")
xp = data.get("xp")
level = data.get("level")
if player_id is None or not track_type or xp is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
svc.set_specialization(player_id, track_type, xp, level or 0)
_audit("specialization_set", {"player_id": player_id, "track": track_type, "xp": xp, "level": level})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/progression/specialization/reset", methods=["POST"])
@login_required
def reset_specializations():
data = request.get_json() or {}
player_id = data.get("player_id")
if player_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
svc.reset_specializations(player_id)
_audit("specialization_reset", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── Character Management Endpoints ──────────────────────────────
@api_bp.route("/characters/<int:account_id>/name", methods=["PUT"])
@login_required
def rename_character(account_id):
data = request.get_json() or {}
name = data.get("name", "").strip()
if not name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing name"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.rename(account_id, name)
_audit("character_rename", {"account_id": account_id, "new_name": name})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/characters/<int:actor_id>", methods=["DELETE"])
@login_required
def delete_character(actor_id):
from app.factory import get_services
svc = get_services()["character"]
svc.delete_character(actor_id)
_audit("character_delete", {"actor_id": actor_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/accounts/<user_id>", methods=["DELETE"])
@login_required
def delete_account(user_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
from app.factory import get_services
svc = get_services()["character"]
svc.delete_account(user_id, reason)
_audit("account_delete", {"user_id": user_id, "reason": reason})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/accounts/<user_id>/demo", methods=["PUT"])
@login_required
def set_demo_state(user_id):
data = request.get_json() or {}
state = data.get("demo")
if state is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing demo"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.set_demo(user_id, state)
_audit("demo_set", {"user_id": user_id, "state": state})
return jsonify(ApiResponse(success=True).model_dump())
# ── Vehicles ────────────────────────────────────────────────────
@api_bp.route("/vehicles", methods=["GET"])
@login_required
def list_vehicles():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map, c.character_name as owner_name
FROM dune.actors a
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
LEFT JOIN public.characters c ON vi.owner_id = c.id
WHERE a.class ILIKE %s OR c.character_name ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
)
vehicles = [{
"id": r["id"],
"class_name": r["class"],
"display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "),
"map": r["map"],
"owner_name": r["owner_name"] or "Unknown",
} for r in rows]
return jsonify(ApiResponse(success=True, data=vehicles).model_dump())
@api_bp.route("/vehicles/<int:vehicle_id>/<action>", methods=["POST"])
@login_required
def vehicle_action(vehicle_id, action):
from app.factory import get_services
db = get_services()["db"]
if action == "repair":
db.call_procedure("repair_vehicle", [vehicle_id])
_audit("vehicle_repair", {"vehicle_id": vehicle_id})
elif action == "destroy":
db.call_procedure("destroy_vehicle", [vehicle_id])
_audit("vehicle_destroy", {"vehicle_id": vehicle_id})
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
).model_dump()), 400
return jsonify(ApiResponse(success=True).model_dump())
# ── Buildings ───────────────────────────────────────────────────
@api_bp.route("/buildings", methods=["GET"])
@login_required
def list_buildings():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level,
c.character_name as owner_name
FROM dune.actors a
JOIN dune.buildings b ON a.id = b.id
LEFT JOIN public.characters c ON b.owner_id = c.id
WHERE a.class ILIKE %s OR c.character_name ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
)
buildings = [{
"id": r["id"],
"class_name": r["class"],
"map": r["map"],
"owner_name": r["owner_name"] or "Unknown",
"is_powered": r.get("is_powered") == "True",
"power_level": r.get("power_level"),
"instance_count": 1,
} for r in rows]
return jsonify(ApiResponse(success=True, data=buildings).model_dump())
# ── Accounts ────────────────────────────────────────────────────
@api_bp.route("/accounts", methods=["GET"])
@login_required
def list_accounts():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.email, a.funcom_id,
(SELECT COUNT(*) FROM public.characters c WHERE c.account_id = a.id) as character_count,
a.is_demo, a.is_cheater, a.last_login
FROM public.accounts a
WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s
ORDER BY a.last_login DESC NULLS LAST LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
)
accounts = [{
"id": r["id"],
"email": r["email"],
"funcom_id": r["funcom_id"],
"character_count": r["character_count"],
"is_demo": r["is_demo"],
"is_cheater": r["is_cheater"],
"last_login": r["last_login"].isoformat() if r["last_login"] else None,
} for r in rows]
return jsonify(ApiResponse(success=True, data=accounts).model_dump())
@api_bp.route("/players/<int:account_id>/cheater", methods=["POST"])
@login_required
def flag_cheater(account_id):
data = request.get_json() or {}
cheat_type = data.get("cheat_type")
if not cheat_type:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing cheat_type"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.flag_cheater(account_id, cheat_type)
_audit("cheater_flag", {"account_id": account_id, "cheat_type": cheat_type})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:account_id>/tags", methods=["GET"])
@login_required
def get_player_tags(account_id):
from app.factory import get_services
svc = get_services()["character"]
tags = svc.get_tags(account_id)
return jsonify(ApiResponse(success=True, data={"tags": tags}).model_dump())
@api_bp.route("/players/<int:account_id>/tags", methods=["PUT"])
@login_required
def update_player_tags(account_id):
data = request.get_json() or {}
add = data.get("add", [])
remove = data.get("remove", [])
from app.factory import get_services
svc = get_services()["character"]
svc.update_tags(account_id, add, remove)
_audit("tags_update", {"account_id": account_id, "add": add, "remove": remove})
return jsonify(ApiResponse(success=True).model_dump())
# ── Broadcast ───────────────────────────────────────────────────
@api_bp.route("/broadcast", methods=["POST"])
@login_required
def send_broadcast():
data = request.get_json() or {}
try:
req = BroadcastRequest(**data)
except ValidationError as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["rmq_game"]
success = svc.send_broadcast(req.message, server=req.server, partition=req.partition)
if success:
_audit("broadcast_sent", {"message": req.message, "server": req.server, "partition": req.partition})
return jsonify(ApiResponse(success=True).model_dump())
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="BroadcastFailed", message="Failed to send broadcast via RMQ"),
).model_dump()), 502
# ── Vendor / Economy ────────────────────────────────────────────
@api_bp.route("/vendors/clean", methods=["POST"])
@login_required
def clean_vendor_stock():
data = request.get_json() or {}
player_id = data.get("player_id")
if not player_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.clean_vendor_stock(player_id)
_audit("vendor_clean", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/tax/invoices", methods=["POST"])
@login_required
def get_tax_invoices():
data = request.get_json() or {}
player_id = data.get("player_id")
if not player_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
invoices = svc.get_tax_invoices(player_id)
return jsonify(ApiResponse(success=True, data=invoices).model_dump())
# ── Function Explorer ────────────────────────────────────────────
@api_bp.route("/functions", methods=["GET"])
@login_required
def list_functions():
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"""SELECT p.proname as name,
pg_get_function_identity_arguments(p.oid) as args,
l.lanname as language,
p.prokind as kind
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
JOIN pg_language l ON l.oid = p.prolang
WHERE n.nspname = 'dune' AND p.prokind = 'f'
ORDER BY p.proname"""
)
return jsonify(ApiResponse(success=True, data=rows).model_dump())
@api_bp.route("/functions/<name>", methods=["GET"])
@login_required
def get_function_detail(name):
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"""SELECT pg_get_functiondef(p.oid) as definition,
p.proname as name,
pg_get_function_identity_arguments(p.oid) as args
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f'""",
[name],
)
if not rows:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Function not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=rows[0]).model_dump())
@api_bp.route("/functions/execute", methods=["POST"])
@login_required
def execute_function_v2():
data = request.get_json() or {}
schema = data.get("schema")
func_name = data.get("function", "")
args = data.get("args", {})
if not func_name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing function name"),
).model_dump()), 400
from app.factory import get_services
db = get_services()["db"]
try:
full_name = f"{schema}.{func_name}" if schema else func_name
if isinstance(args, dict):
params = list(args.values())
elif isinstance(args, list):
params = args
else:
params = [args]
result = db.call_function(full_name, params)
_audit("function_execute", {"function": full_name, "params": params})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
logger.exception("Function execution failed")
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ExecutionError", message=str(e)),
).model_dump()), 500
@api_bp.route("/functions/<name>/execute", methods=["POST"])
@login_required
def execute_function(name):
data = request.get_json() or {}
params = data.get("params", [])
from app.factory import get_services
db = get_services()["db"]
try:
result = db.call_function(name, params)
_audit("function_execute", {"function": name, "params": params})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
logger.exception("Function execution failed")
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ExecutionError", message=str(e)),
).model_dump()), 500
# ── Raw Query (SELECT only) ──────────────────────────────────────
@api_bp.route("/query", methods=["POST"])
@login_required
def raw_query():
data = request.get_json() or {}
sql = (data.get("query") or data.get("sql", "")).strip()
if not sql:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing SQL"),
).model_dump()), 400
upper = sql.upper()
if any(kw in upper for kw in ("INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "GRANT", "TRUNCATE")):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="Forbidden", message="Only SELECT queries are allowed"),
).model_dump()), 403
from app.factory import get_services
db = get_services()["db"]
try:
result = db.execute_readonly(sql)
_audit("raw_query", {"sql": sql[:200]})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="QueryError", message=str(e)),
).model_dump()), 500
# ── Audit Logs ──────────────────────────────────────────────────
@api_bp.route("/audit/logs", methods=["GET"])
@login_required
def get_audit_logs():
action = request.args.get("action")
user = request.args.get("user")
limit = int(request.args.get("limit", 100))
offset = int(request.args.get("offset", 0))
from app.factory import get_services
svc = get_services()["audit"]
logs = svc.get_logs(action=action, user=user, limit=limit, offset=offset)
return jsonify(ApiResponse(success=True, data=logs).model_dump())
@api_bp.route("/stats", methods=["GET"])
@login_required
def get_stats():
from app.factory import get_services
db = get_services()["db"]
try:
stats = db.execute_readonly("""
SELECT
(SELECT COUNT(*) FROM public.characters) AS total_players,
(SELECT COUNT(*) FROM public.characters WHERE is_online = true) AS online_players,
(SELECT COUNT(*) FROM public.guilds) AS guild_count,
(SELECT COUNT(*) FROM public.guilds WHERE active = true) AS active_guilds,
(SELECT COUNT(*) FROM public.game_servers) AS server_count,
(SELECT COUNT(*) FROM public.partitions) AS partition_count,
(SELECT COALESCE(SUM(worth), 0) FROM public.player_economy) AS total_worth,
(SELECT COUNT(*) FROM public.flavor_text) AS total_flavor_text
""")
return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump())
except Exception as e:
logger.exception("Failed to get stats")
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="StatsError", message=str(e))).model_dump()), 500
@api_bp.route("/audit/stats", methods=["GET"])
@login_required
def get_audit_stats():
from app.factory import get_services
svc = get_services()["audit"]
stats = svc.get_stats()
return jsonify(ApiResponse(success=True, data=stats).model_dump())
# ── Settings ────────────────────────────────────────────────────
@api_bp.route("/settings", methods=["GET"])
@login_required
def get_settings():
from app.factory import get_services
settings = get_services()["db"].execute_readonly(
"SELECT key, value, updated_at FROM dashboard.settings ORDER BY key"
)
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
@api_bp.route("/settings", methods=["POST"])
@login_required
def update_settings():
data = request.get_json() or {}
if not isinstance(data, dict):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
).model_dump()), 400
from app.factory import get_services
db = get_services()["db"]
for key, value in data.items():
db.execute_mutation(
"""INSERT INTO dashboard.settings (key, value, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
[key, str(value)],
)
_audit("settings_update", {"keys": list(data.keys())})
return jsonify(ApiResponse(success=True).model_dump())
# ── Moderation (Ban / Kick) ────────────────────────────────────
@api_bp.route("/players/<int:player_id>/ban", methods=["POST"])
@login_required
def ban_player(player_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
duration = data.get("duration_hours", 0)
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"""INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
[player_id, reason, duration, duration, duration],
)
_audit("player_ban", {"player_id": player_id, "reason": reason, "duration": duration})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/unban", methods=["POST"])
@login_required
def unban_player(player_id):
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s",
[player_id],
)
_audit("player_unban", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/ban", methods=["GET"])
@login_required
def get_player_ban(player_id):
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE",
[player_id],
)
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
@api_bp.route("/players/<int:player_id>/kick", methods=["POST"])
@login_required
def kick_player(player_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
_audit("player_kick", {"player_id": player_id, "reason": reason})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/history", methods=["GET"])
@login_required
def get_player_history(player_id):
from app.factory import get_services
db = get_services()["db"]
logs = db.execute_readonly(
"""SELECT * FROM dashboard.audit_log
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
ORDER BY created_at DESC LIMIT 100""",
[player_id, player_id],
)
return jsonify(ApiResponse(success=True, data=logs).model_dump())
+131
View File
@@ -0,0 +1,131 @@
# Authentication routes — login, logout.
import time
import threading
from functools import wraps
from flask import Blueprint, request, jsonify, session
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from app.models import ApiResponse, ErrorDetail
auth_bp = Blueprint("auth", __name__)
login_manager = LoginManager()
_failed_attempts = {}
_failed_lock = threading.Lock()
_MAX_FAILED_ATTEMPTS = 5
_BLOCK_DURATION = 900
class AdminUser(UserMixin):
def __init__(self, username):
self.id = username
def _is_ip_blocked(ip):
with _failed_lock:
record = _failed_attempts.get(ip)
if record and record["count"] >= _MAX_FAILED_ATTEMPTS:
elapsed = time.time() - record["first_attempt"]
if elapsed < _BLOCK_DURATION:
return True
del _failed_attempts[ip]
return False
def _record_failed_attempt(ip):
with _failed_lock:
now = time.time()
record = _failed_attempts.get(ip)
if record:
record["count"] += 1
else:
_failed_attempts[ip] = {"count": 1, "first_attempt": now}
return _failed_attempts[ip]["count"] >= _MAX_FAILED_ATTEMPTS
def _clear_failed_attempts(ip):
with _failed_lock:
_failed_attempts.pop(ip, None)
def init_auth(app, settings):
login_manager.init_app(app)
login_manager.login_view = "auth.login"
login_manager.login_message = "Please log in."
@login_manager.user_loader
def load_user(user_id):
auth = settings.get("auth", {})
if str(auth.get("username")) == str(user_id):
return AdminUser(user_id)
return None
def get_audit_user():
return current_user.id if current_user.is_authenticated else "anonymous"
@auth_bp.route("/login", methods=["POST"])
def login():
data = request.get_json() or {}
username = data.get("username", "").strip()
password = data.get("password", "")
client_ip = request.remote_addr or "unknown"
if _is_ip_blocked(client_ip):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="IpBlocked", message="Too many failed attempts. Try again later."),
).model_dump()), 429
auth = request.app.dune_settings.get("auth", {})
cfg_u = str(auth.get("username", ""))
password_hash = auth.get("password_hash")
if username != cfg_u:
_record_failed_attempt(client_ip)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
).model_dump()), 401
if password_hash:
try:
from argon2 import PasswordHasher, exceptions
ph = PasswordHasher(time_cost=3, memory_cost=65536)
ph.verify(password_hash, password)
_clear_failed_attempts(client_ip)
login_user(AdminUser(username))
return jsonify(ApiResponse(success=True, data={"user": username}).model_dump())
except exceptions.VerifyMismatchError:
_record_failed_attempt(client_ip)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
).model_dump()), 401
except Exception:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AuthError", message="Authentication error"),
).model_dump()), 500
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotConfigured", message="Authentication not configured"),
).model_dump()), 403
@auth_bp.route("/logout", methods=["POST"])
@login_required
def logout():
logout_user()
return jsonify(ApiResponse(success=True).model_dump())
@auth_bp.route("/me", methods=["GET"])
def me():
if current_user.is_authenticated:
return jsonify(ApiResponse(success=True, data={"user": current_user.id}).model_dump())
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="Unauthorized", message="Not authenticated")).model_dump()), 401
+24
View File
@@ -0,0 +1,24 @@
# Chat routes.
import logging
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
chat_bp = Blueprint("chat", __name__)
logger = logging.getLogger(__name__)
@chat_bp.route("/history", methods=["GET"])
@login_required
def chat_history():
channel = request.args.get("channel", "")
limit = int(request.args.get("limit", 100))
from app.factory import get_services
svc = get_services()["chat"]
rows = svc.get_history(limit=limit)
if channel:
rows = [r for r in rows if r.get("channel", "").lower() == channel.lower()]
return jsonify(ApiResponse(success=True, data=rows).model_dump())
+43
View File
@@ -0,0 +1,43 @@
# Debug routes — restricted to admin.
import logging
from flask import Blueprint, jsonify
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
debug_bp = Blueprint("debug", __name__)
logger = logging.getLogger(__name__)
def _get_services():
from app.factory import get_services
return get_services()
@debug_bp.route("/tables", methods=["GET"])
@login_required
def list_tables():
db = _get_services()["db"]
rows = db.execute_readonly(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'dune' ORDER BY table_name"
)
return jsonify(ApiResponse(success=True, data={"tables": [r["table_name"] for r in rows]}).model_dump())
@debug_bp.route("/vehicle/<int:vehicle_id>", methods=["GET"])
@login_required
def debug_vehicle(vehicle_id):
db = _get_services()["db"]
vehicle = db.execute_readonly(
"""SELECT a.id, a.class, a.properties
FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s""",
[vehicle_id],
)
if not vehicle:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Vehicle not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=vehicle[0]).model_dump())
+147
View File
@@ -0,0 +1,147 @@
# BGD Director proxy routes.
import logging
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
director_bp = Blueprint("director", __name__)
logger = logging.getLogger(__name__)
def _get_service():
from app.factory import get_services
return get_services()["bg_director"]
@director_bp.route("/battlegroup", methods=["GET"])
@login_required
def director_battlegroup():
try:
svc = _get_service()
data = svc.get_battlegroup()
return jsonify(ApiResponse(success=True, data=data.model_dump()).model_dump())
except Exception as e:
logger.error("Director battlegroup error: %s", e)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e), hint="Check BGD pod logs"),
).model_dump()), 503
@director_bp.route("/config", methods=["POST"])
@login_required
def director_update_config():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_server_config(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/config/clear", methods=["POST"])
@login_required
def director_clear_config():
map_name = request.get_data(as_text=True).strip()
try:
svc = _get_service()
result = svc.clear_map_config(map_name)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer", methods=["GET"])
@login_required
def director_transfer_get():
try:
svc = _get_service()
data = svc.get_transfer_rules()
return jsonify(ApiResponse(success=True, data=data).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer", methods=["POST"])
@login_required
def director_transfer_update():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_transfer_settings(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer/clear", methods=["POST"])
@login_required
def director_transfer_clear():
try:
svc = _get_service()
result = svc.clear_transfer_overrides()
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls", methods=["GET"])
@login_required
def director_fls_get():
try:
svc = _get_service()
data = svc.get_fls_settings()
return jsonify(ApiResponse(success=True, data=data).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls", methods=["POST"])
@login_required
def director_fls_update():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_fls_settings(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls/clear", methods=["POST"])
@login_required
def director_fls_clear():
try:
svc = _get_service()
result = svc.clear_fls_overrides()
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
+120
View File
@@ -0,0 +1,120 @@
# File browser routes.
import base64
import logging
import posixpath
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
files_bp = Blueprint("files", __name__)
logger = logging.getLogger(__name__)
FILEBROWSER_BASE_PATH = "/srv"
def _validate_fb_path(path: str) -> bool:
path_str = str(path or "").lstrip("/")
if ".." in path_str or "\x00" in path_str:
return False
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
def _get_services():
from app.factory import get_services
return get_services()
def _fb_exec(command: str, timeout: int = 10):
services = _get_services()
k8s = services["k8s"]
pod = k8s.get_filebrowser_pod()
if not pod:
return "", "FileBrowser pod not found", 1
full_cmd = f"sudo kubectl exec {pod} -n {k8s.namespace} -- {command}"
return k8s.ssh.run(full_cmd, timeout=timeout)
@files_bp.route("/list", methods=["POST"])
@login_required
def files_list():
data = request.get_json() or {}
path = data.get("path", "/srv")
if not _validate_fb_path(path):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
).model_dump()), 403
import shlex
safe_path = shlex.quote(path)
out, err, rc = _fb_exec(f"ls -la {safe_path}", timeout=10)
if rc != 0:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="CommandError", message=err or "Failed to list directory"),
).model_dump()), 500
files = []
for line in out.strip().split("\n")[1:]:
parts = line.split(None, 8)
if len(parts) >= 9:
name = parts[8]
if name in (".", ".."):
continue
files.append({
"name": name,
"is_dir": parts[0].startswith("d"),
"size": parts[4] if not parts[0].startswith("d") else "",
"perms": parts[0],
"date": " ".join(parts[5:8]),
})
return jsonify(ApiResponse(success=True, data={"files": files}).model_dump())
@files_bp.route("/view", methods=["GET"])
@login_required
def files_view():
path = request.args.get("path", "")
if not path or not _validate_fb_path(path):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
).model_dump()), 403
import shlex
safe_path = shlex.quote(path)
out, err, rc = _fb_exec(f"head -c 100000 {safe_path}", timeout=10)
if rc != 0:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="CommandError", message=err or "Failed to read file"),
).model_dump()), 500
return jsonify(ApiResponse(success=True, data={"content": out, "path": path}).model_dump())
@files_bp.route("/save", methods=["POST"])
@login_required
def files_save():
data = request.get_json() or {}
path = data.get("path", "")
content = data.get("content", "")
if not path or not _validate_fb_path(path):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
).model_dump()), 403
import shlex
import base64
content_b64 = base64.b64encode(content.encode()).decode()
safe_path = shlex.quote(path)
# Write via base64 decode inside pod
cmd = f"echo {content_b64} | base64 -d > {safe_path}"
out, err, rc = _fb_exec(cmd, timeout=15)
if rc != 0:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="CommandError", message=err or "Failed to save file"),
).model_dump()), 500
return jsonify(ApiResponse(success=True).model_dump())
+84
View File
@@ -0,0 +1,84 @@
# Health and SSE routes.
import asyncio
import json
import logging
from flask import Blueprint, jsonify, Response, request, stream_with_context
from flask_login import login_required, current_user
from app.models import ApiResponse, ErrorDetail
health_bp = Blueprint("health", __name__)
logger = logging.getLogger(__name__)
@health_bp.route("/health", methods=["GET"])
def health_check():
from app.factory import get_services
services = get_services()
health = {"status": "healthy", "timestamp": __import__("datetime").datetime.now().isoformat(), "checks": {}}
status_code = 200
try:
services["db"].health_check()
health["checks"]["database"] = "ok"
except Exception as e:
health["checks"]["database"] = f"error: {e}"
health["status"] = "degraded"
status_code = 503
try:
services["ssh"].check_connection()
health["checks"]["ssh"] = "ok"
except Exception as e:
health["checks"]["ssh"] = f"error: {e}"
health["status"] = "degraded"
status_code = 503
try:
services["bg_director"].get_battlegroup()
health["checks"]["bgd"] = "ok"
except Exception as e:
health["checks"]["bgd"] = f"error: {e}"
health["status"] = "degraded"
status_code = 503
try:
services["rmq_admin"].get_overview()
health["checks"]["rmq"] = "ok"
except Exception as e:
health["checks"]["rmq"] = f"error: {e}"
health["status"] = "degraded"
status_code = 503
return jsonify(health), status_code
@health_bp.route("/events/stream", methods=["GET"])
@login_required
def sse_stream():
from app.factory import get_services
services = get_services()
realtime = services["realtime"]
queue = asyncio.Queue(maxsize=100)
realtime.add_client(queue)
def event_stream():
try:
yield "event: connected\ndata: {}\n\n"
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
while True:
try:
msg = loop.run_until_complete(asyncio.wait_for(queue.get(), timeout=30))
yield msg
except asyncio.TimeoutError:
yield ":ping\n\n"
except Exception:
break
finally:
realtime.remove_client(queue)
return Response(stream_with_context(event_stream()), mimetype="text/event-stream")
+218
View File
@@ -0,0 +1,218 @@
# Server and infrastructure routes.
import logging
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
server_bp = Blueprint("server", __name__)
logger = logging.getLogger(__name__)
def _get_services():
from app.factory import get_services
return get_services()
@server_bp.route("/pods", methods=["GET"])
@login_required
def server_pods():
services = _get_services()
pods = services["k8s"].get_pods()
return jsonify(ApiResponse(success=True, data=pods).model_dump())
@server_bp.route("/deployments", methods=["GET"])
@login_required
def server_deployments():
services = _get_services()
deployments = services["k8s"].get_deployments()
return jsonify(ApiResponse(success=True, data=deployments).model_dump())
@server_bp.route("/metrics", methods=["GET"])
@login_required
def server_metrics():
services = _get_services()
raw = services["k8s"].get_node_metrics()
from datetime import datetime, timezone
metrics = []
if raw:
cpu_str = raw.get("cpu", "0m").replace("m", "").replace("%", "")
mem_str = raw.get("memory", "0Mi").replace("Mi", "").replace("Gi", "000")
try:
cpu_val = float(cpu_str)
mem_val = float(mem_str)
metrics.append({
"timestamp": datetime.now(timezone.utc).isoformat(),
"cpu_percent": min(100, round(cpu_val / 10, 1)), # rough estimate
"memory_percent": min(100, round(mem_val / 100, 1)), # rough estimate
})
except ValueError:
pass
return jsonify(ApiResponse(success=True, data=metrics).model_dump())
@server_bp.route("/deployments/<name>/restart", methods=["POST"])
@login_required
def restart_deployment(name: str):
services = _get_services()
out, err, rc = services["k8s"].run(f"rollout restart deployment/{name}")
return jsonify(ApiResponse(
success=rc == 0,
data={"output": out, "error": err, "rc": rc},
).model_dump())
@server_bp.route("/deployments/<name>/scale", methods=["POST"])
@login_required
def scale_deployment(name: str):
data = request.get_json() or {}
replicas = data.get("replicas")
if replicas is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing replicas"),
).model_dump()), 400
services = _get_services()
out, err, rc = services["k8s"].run(f"scale deployment/{name} --replicas={replicas}")
return jsonify(ApiResponse(
success=rc == 0,
data={"output": out, "error": err, "rc": rc},
).model_dump())
@server_bp.route("/action", methods=["POST"])
@login_required
def server_action():
data = request.get_json() or {}
deployment = data.get("deployment", "")
action = data.get("action", "")
if not deployment or not action:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing deployment or action"),
).model_dump()), 400
actions = {
"restart": f"rollout restart deployment/{deployment}",
"status": f"rollout status deployment/{deployment}",
"scale_0": f"scale deployment/{deployment} --replicas=0",
"scale_1": f"scale deployment/{deployment} --replicas=1",
"describe": f"describe deployment/{deployment}",
}
cmd = actions.get(action)
if not cmd:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
).model_dump()), 400
services = _get_services()
out, err, rc = services["k8s"].run(cmd)
return jsonify(ApiResponse(
success=rc == 0,
data={"output": out, "error": err, "rc": rc},
).model_dump())
@server_bp.route("/firewall", methods=["GET"])
@server_bp.route("/firewall/status", methods=["GET"])
@login_required
def firewall_status():
services = _get_services()
ssh = services["ssh"]
out, _, _ = ssh.run(
"sudo iptables -L INPUT -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
"sudo iptables -L FORWARD -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
"sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E 'dpt:(18888|32479)'",
timeout=15,
)
blocked_ports = set()
for line in out.split("\n"):
for port in ("18888", "32479"):
if f"dpt:{port}" in line and "DROP" in line:
blocked_ports.add(port)
return jsonify(ApiResponse(
success=True,
data={
"18888_blocked": "18888" in blocked_ports,
"32479_blocked": "32479" in blocked_ports,
},
).model_dump())
@server_bp.route("/firewall/toggle", methods=["POST"])
@login_required
def firewall_toggle():
data = request.get_json() or {}
port = data.get("port")
block = data.get("block", True)
if not port:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing port"),
).model_dump()), 400
services = _get_services()
ssh = services["ssh"]
if block:
cmd = (
f"sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
f"sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && "
f"sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
f"sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && "
f"sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
f"sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP"
)
else:
cmd = (
f"sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; "
f"sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
f"sudo iptables -D FORWARD -p tcp --dport {port} -j DROP 2>/dev/null; "
f"sudo iptables -D FORWARD -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -j DROP 2>/dev/null; "
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
f"echo DONE"
)
out, err, rc = ssh.run(cmd, timeout=20)
success = rc == 0 or "DONE" in out
return jsonify(ApiResponse(
success=success,
data={"output": out, "error": err},
).model_dump())
@server_bp.route("/rmq/queues", methods=["GET"])
@login_required
def rmq_queues():
services = _get_services()
try:
queues = services["rmq_admin"].get_queue_depths()
return jsonify(ApiResponse(
success=True,
data=[q.model_dump() for q in queues],
).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="RmqError", message=str(e)),
).model_dump()), 503
@server_bp.route("/rmq/overview", methods=["GET"])
@login_required
def rmq_overview():
services = _get_services()
try:
overview = services["rmq_admin"].get_overview()
return jsonify(ApiResponse(
success=True,
data=overview.model_dump(),
).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="RmqError", message=str(e)),
).model_dump()), 503
+1
View File
@@ -0,0 +1 @@
# Services package init.
+64
View File
@@ -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
+141
View File
@@ -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
+50
View File
@@ -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
+148
View File
@@ -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
+210
View File
@@ -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
+182
View File
@@ -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
+64
View File
@@ -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
+142
View File
@@ -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
+269
View File
@@ -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("_", " ")
+32
View File
@@ -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
+164
View File
@@ -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)
+146
View File
@@ -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
+126
View File
@@ -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
+103
View File
@@ -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
+35
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
# Utils package init.
+71
View File
@@ -0,0 +1,71 @@
# Shared constants and helpers.
INVENTORY_TYPE_LABELS = {
0: "Main Inventory",
1: "Equipped Items",
5: "Hotbar",
12: "Storage",
14: "Recipes",
15: "Key Items",
20: "Crafting Queue",
25: "Schematics",
27: "Emotes",
29: "Quest Items",
30: "Bank",
31: "Power Pack Slots",
32: "Module Slots",
33: "Augment Slots",
}
INVENTORY_HIDDEN_TYPES = {14, 27}
INVENTORY_UNKNOWN_TYPES = {12, 20, 25, 29, 30, 31, 32, 33}
INVENTORY_PRIMARY_TYPES = {0, 1, 5, 15}
EQUIPPED_SLOT_LABELS = {
0: "Head",
1: "Chest",
2: "Legs",
3: "Gloves",
4: "Feet",
5: "Unknown Spare Slot",
6: "Portable Light",
7: "Suspensor Belt",
8: "Power Pack",
9: "Shield",
}
QUALITY_TIERS = {
0: {"label": "Common", "color": "#9a8a7a"},
1: {"label": "Uncommon", "color": "#27ae60"},
2: {"label": "Rare", "color": "#3498db"},
3: {"label": "Epic", "color": "#9b59b6"},
4: {"label": "Legendary", "color": "#f39c12"},
}
CURRENCY_ID_LABELS = {
0: "Solari Credits",
1: "House Script",
2: "Spice",
}
GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"}
VEHICLE_TYPE_MAP = {
"BP_MediumOrnithopter_CHOAM": "Medium Ornithopter",
"BP_TransportOrnithopter_CHOAM": "Transport Ornithopter",
"BP_Buggy_CHOAM": "Buggy",
"BP_LightOrnithopter_Choam": "Light Ornithopter",
"BP_Sandbike_CHOAM": "Sandbike",
}
NAV_PAGES = [
("/", "Overview"),
("/server", "Server"),
("/players", "Players"),
("/guilds", "Guilds"),
("/vehicles", "Vehicles"),
("/map", "Map"),
("/chat", "Chat"),
("/admin", "Admin"),
("/shell", "Shell"),
]
+1
View File
@@ -0,0 +1 @@
# WebSocket package init.
+131
View File
@@ -0,0 +1,131 @@
# WebSocket shell handler — interactive terminal via SSH.
import os
import time
import threading
import logging
import re
import shlex
import paramiko
from flask import request, session
from flask_socketio import emit
logger = logging.getLogger(__name__)
shell_processes = {}
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
def quote_remote(value):
return shlex.quote(str(value))
def register_websocket_handlers(socketio, settings):
@socketio.on("shell_create")
def handle_shell_create(data):
shell_enabled = settings.get("auth", {}).get("shell_enabled", True)
if not shell_enabled:
return emit("shell_created", {"success": False, "error": "Shell access is disabled"})
auth_enabled = settings.get("auth", {}).get("enabled", True)
if auth_enabled and not session.get("_user_id"):
return emit("shell_created", {"success": False, "error": "Authentication required"})
shell_type = data.get("type", "vm")
shell_id = request.sid
try:
ssh_key = _find_ssh_key(settings)
if not ssh_key:
return emit("shell_created", {"success": False, "error": "SSH key not found"})
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
server_host = settings["server"]["host"]
server_user = settings["server"]["user"]
if shell_type == "vm":
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
chan = client.invoke_shell(term="xterm-256color", width=80, height=24)
else:
namespace = settings["kubernetes"]["namespace"]
pod = data.get("pod", "")
pod = require_k8s_name(pod, "pod")
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
transport = client.get_transport()
chan = transport.open_session()
chan.get_pty(term="xterm-256color", width=80, height=24)
safe_pod = quote_remote(pod)
safe_ns = quote_remote(namespace)
chan.exec_command(f"sudo kubectl exec -it {safe_pod} -n {safe_ns} -- /bin/bash")
shell_processes[shell_id] = {"client": client, "channel": chan, "type": shell_type}
def read_channel():
time.sleep(0.5)
socketio.emit("shell_output", {"data": "\r\nConnected. Press Enter...\r\n", "type": "stdout", "target": shell_type}, room=shell_id)
while shell_id in shell_processes:
try:
while chan.recv_ready():
data = chan.recv(65535).decode("utf-8", errors="replace")
if data:
socketio.emit("shell_output", {"data": data, "type": "stdout", "target": shell_type}, room=shell_id)
while chan.recv_stderr_ready():
data = chan.recv_stderr(65535).decode("utf-8", errors="replace")
if data:
socketio.emit("shell_output", {"data": data, "type": "stderr", "target": shell_type}, room=shell_id)
if chan.closed:
socketio.emit("shell_output", {"data": "\r\n[Disconnected]\r\n", "type": "stdout", "target": shell_type}, room=shell_id)
break
except Exception as e:
logger.error("Shell read error: %s", e)
break
time.sleep(0.1)
threading.Thread(target=read_channel, daemon=True).start()
socketio.emit("shell_created", {"success": True, "shell_id": shell_id}, room=shell_id)
except Exception as e:
logger.error("Shell creation failed: %s", e)
socketio.emit("shell_created", {"success": False, "error": str(e)}, room=shell_id)
@socketio.on("shell_input")
def handle_shell_input(data):
shell_id = request.sid
if shell_id in shell_processes:
try:
chan = shell_processes[shell_id]["channel"]
if chan and chan.send_ready():
chan.send(data.get("data", ""))
except Exception as e:
logger.error("Shell input error: %s", e)
@socketio.on("shell_disconnect")
def handle_shell_disconnect(data=None):
shell_id = request.sid
if shell_id in shell_processes:
try:
if "client" in shell_processes[shell_id]:
shell_processes[shell_id]["client"].close()
except Exception as e:
logger.error("Shell disconnect error: %s", e)
del shell_processes[shell_id]
def _find_ssh_key(settings):
ssh_key = settings["server"].get("ssh_key")
if ssh_key:
return ssh_key
local_appdata = os.environ.get("LOCALAPPDATA")
if local_appdata:
default_key = os.path.join(local_appdata, "DuneAwakeningServer", "sshKey")
if os.path.exists(default_key):
return default_key
return None
+17
View File
@@ -0,0 +1,17 @@
flask>=3.0.0
flask-socketio>=5.3.0
flask-login>=0.6.3
flask-limiter>=3.5.0
flask-cors>=4.0.0
flask-wtf>=1.2.0
pydantic>=2.5.0
httpx>=0.27.0
psycopg>=3.1.0
psycopg_pool>=3.2.0
cachetools>=5.3.0
argon2-cffi>=23.1.0
pyyaml>=6.0
python-socketio>=5.10.0
paramiko>=3.4.0
Werkzeug>=3.0.0
itsdangerous>=2.1.0
+22
View File
@@ -0,0 +1,22 @@
"""Entry point for the new backend."""
import sys
import os
# Add backend to path
backend_dir = os.path.dirname(os.path.abspath(__file__))
if backend_dir not in sys.path:
sys.path.insert(0, backend_dir)
from app.factory import create_app
app = create_app()
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.INFO)
app.run(
host=app.dune_settings["dashboard"]["host"],
port=app.dune_settings["dashboard"]["port"],
debug=app.dune_settings["dashboard"]["debug"],
)
+94
View File
@@ -0,0 +1,94 @@
function Kp(e,t){for(var r=0;r<t.length;r++){const s=t[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in e)){const o=Object.getOwnPropertyDescriptor(s,i);o&&Object.defineProperty(e,i,o.get?o:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();function Xp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Th={exports:{}},Zn={},Lh={exports:{}},re={};/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var xi=Symbol.for("react.element"),Gp=Symbol.for("react.portal"),Jp=Symbol.for("react.fragment"),Qp=Symbol.for("react.strict_mode"),Yp=Symbol.for("react.profiler"),Zp=Symbol.for("react.provider"),em=Symbol.for("react.context"),tm=Symbol.for("react.forward_ref"),rm=Symbol.for("react.suspense"),sm=Symbol.for("react.memo"),im=Symbol.for("react.lazy"),Ic=Symbol.iterator;function nm(e){return e===null||typeof e!="object"?null:(e=Ic&&e[Ic]||e["@@iterator"],typeof e=="function"?e:null)}var Dh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ah=Object.assign,Oh={};function ws(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}ws.prototype.isReactComponent={};ws.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ws.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Nh(){}Nh.prototype=ws.prototype;function Rl(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}var Tl=Rl.prototype=new Nh;Tl.constructor=Rl;Ah(Tl,ws.prototype);Tl.isPureReactComponent=!0;var Fc=Array.isArray,Ph=Object.prototype.hasOwnProperty,Ll={current:null},Bh={key:!0,ref:!0,__self:!0,__source:!0};function jh(e,t,r){var s,i={},o=null,c=null;if(t!=null)for(s in t.ref!==void 0&&(c=t.ref),t.key!==void 0&&(o=""+t.key),t)Ph.call(t,s)&&!Bh.hasOwnProperty(s)&&(i[s]=t[s]);var n=arguments.length-2;if(n===1)i.children=r;else if(1<n){for(var a=Array(n),f=0;f<n;f++)a[f]=arguments[f+2];i.children=a}if(e&&e.defaultProps)for(s in n=e.defaultProps,n)i[s]===void 0&&(i[s]=n[s]);return{$$typeof:xi,type:e,key:o,ref:c,props:i,_owner:Ll.current}}function om(e,t){return{$$typeof:xi,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Dl(e){return typeof e=="object"&&e!==null&&e.$$typeof===xi}function am(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Hc=/\/+/g;function Eo(e,t){return typeof e=="object"&&e!==null&&e.key!=null?am(""+e.key):t.toString(36)}function ln(e,t,r,s,i){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var c=!1;if(e===null)c=!0;else switch(o){case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case xi:case Gp:c=!0}}if(c)return c=e,i=i(c),e=s===""?"."+Eo(c,0):s,Fc(i)?(r="",e!=null&&(r=e.replace(Hc,"$&/")+"/"),ln(i,t,r,"",function(f){return f})):i!=null&&(Dl(i)&&(i=om(i,r+(!i.key||c&&c.key===i.key?"":(""+i.key).replace(Hc,"$&/")+"/")+e)),t.push(i)),1;if(c=0,s=s===""?".":s+":",Fc(e))for(var n=0;n<e.length;n++){o=e[n];var a=s+Eo(o,n);c+=ln(o,t,r,a,i)}else if(a=nm(e),typeof a=="function")for(e=a.call(e),n=0;!(o=e.next()).done;)o=o.value,a=s+Eo(o,n++),c+=ln(o,t,r,a,i);else if(o==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return c}function ji(e,t,r){if(e==null)return e;var s=[],i=0;return ln(e,s,"","",function(o){return t.call(r,o,i++)}),s}function lm(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var Ze={current:null},cn={transition:null},cm={ReactCurrentDispatcher:Ze,ReactCurrentBatchConfig:cn,ReactCurrentOwner:Ll};function Mh(){throw Error("act(...) is not supported in production builds of React.")}re.Children={map:ji,forEach:function(e,t,r){ji(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return ji(e,function(){t++}),t},toArray:function(e){return ji(e,function(t){return t})||[]},only:function(e){if(!Dl(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};re.Component=ws;re.Fragment=Jp;re.Profiler=Yp;re.PureComponent=Rl;re.StrictMode=Qp;re.Suspense=rm;re.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=cm;re.act=Mh;re.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var s=Ah({},e.props),i=e.key,o=e.ref,c=e._owner;if(t!=null){if(t.ref!==void 0&&(o=t.ref,c=Ll.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var n=e.type.defaultProps;for(a in t)Ph.call(t,a)&&!Bh.hasOwnProperty(a)&&(s[a]=t[a]===void 0&&n!==void 0?n[a]:t[a])}var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){n=Array(a);for(var f=0;f<a;f++)n[f]=arguments[f+2];s.children=n}return{$$typeof:xi,type:e.type,key:i,ref:o,props:s,_owner:c}};re.createContext=function(e){return e={$$typeof:em,_currentValue:e,_currentValue2:e,_threadCountLine truncated
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var hm=M,dm=Symbol.for("react.element"),fm=Symbol.for("react.fragment"),pm=Object.prototype.hasOwnProperty,mm=hm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,_m={key:!0,ref:!0,__self:!0,__source:!0};function Ih(e,t,r){var s,i={},o=null,c=null;r!==void 0&&(o=""+r),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(c=t.ref);for(s in t)pm.call(t,s)&&!_m.hasOwnProperty(s)&&(i[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps,t)i[s]===void 0&&(i[s]=t[s]);return{$$typeof:dm,type:e,key:o,ref:c,props:i,_owner:mm.current}}Zn.Fragment=fm;Zn.jsx=Ih;Zn.jsxs=Ih;Th.exports=Zn;var v=Th.exports,da={},Fh={exports:{}},ft={},Hh={exports:{}},Uh={};/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/(function(e){function t(R,D){var A=R.length;R.push(D);e:for(;0<A;){var B=A-1>>>1,H=R[B];if(0<i(H,D))R[B]=D,R[A]=H,A=B;else break e}}function r(R){return R.length===0?null:R[0]}function s(R){if(R.length===0)return null;var D=R[0],A=R.pop();if(A!==D){R[0]=A;e:for(var B=0,H=R.length,q=H>>>1;B<q;){var G=2*(B+1)-1,X=R[G],te=G+1,T=R[te];if(0>i(X,A))te<H&&0>i(T,X)?(R[B]=T,R[te]=A,B=te):(R[B]=X,R[G]=A,B=G);else if(te<H&&0>i(T,A))R[B]=T,R[te]=A,B=te;else break e}}return D}function i(R,D){var A=R.sortIndex-D.sortIndex;return A!==0?A:R.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,n=c.now();e.unstable_now=function(){return c.now()-n}}var a=[],f=[],m=1,p=null,_=3,S=!1,b=!1,y=!1,u=typeof setTimeout=="function"?setTimeout:null,h=typeof clearTimeout=="function"?clearTimeout:null,l=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(R){for(var D=r(f);D!==null;){if(D.callback===null)s(f);else if(D.startTime<=R)s(f),D.sortIndex=D.expirationTime,t(a,D);else break;D=r(f)}}function g(R){if(y=!1,d(R),!b)if(r(a)!==null)b=!0,W(x);else{var D=r(f);D!==null&&V(g,D.startTime-R)}}function x(R,D){b=!1,y&&(y=!1,h(w),w=-1),S=!0;var A=_;try{for(d(D),p=r(a);p!==null&&(!(p.expirationTime>D)||R&&!N());){var B=p.callback;if(typeof B=="function"){p.callback=null,_=p.priorityLevel;var H=B(p.expirationTime<=D);D=e.unstable_now(),typeof H=="function"?p.callback=H:p===r(a)&&s(a),d(D)}else s(a);p=r(a)}if(p!==null)var q=!0;else{var G=r(f);G!==null&&V(g,G.startTime-D),q=!1}return q}finally{p=null,_=A,S=!1}}var C=!1,k=null,w=-1,E=5,L=-1;function N(){return!(e.unstable_now()-L<E)}function O(){if(k!==null){var R=e.unstable_now();L=R;var D=!0;try{D=k(!0,R)}finally{D?P():(C=!1,k=null)}}else C=!1}var P;if(typeof l=="function")P=function(){l(O)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,z=F.port2;F.port1.onmessage=O,P=function(){z.postMessage(null)}}else P=function(){u(O,0)};function W(R){k=R,C||(C=!0,P())}function V(R,D){w=u(function(){R(e.unstable_now())},D)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_continueExecution=function(){b||S||(b=!0,W(x))},e.unstable_forceFrameRate=function(R){0>R||125<R?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<R?Math.floor(1e3/R):5},e.unstable_getCurrentPriorityLevel=function(){return _},e.unstable_getFirstCallbackNode=function(){return r(a)},e.unstable_next=function(R){switch(_){case 1:case 2:case 3:var D=3;break;default:D=_}var A=_;_=D;try{return R()}finally{_=A}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(R,D){switch(R){case 1:case 2:case 3:case 4:case 5:break;default:R=3}var A=_;_=R;try{return D()}finally{_=A}},e.unstable_scheduleCallback=function(R,D,A){var B=e.unstable_now();switch(typeof A=="object"&&A!==null?(A=A.delay,A=typeof A=="number"&&0<A?B+A:B):A=B,R){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=A+H,R={id:m++,callback:D,priorityLevel:R,startTime:A,expirationTime:H,sortIndex:-1},A>B?(R.sortIndex=A,t(f,R),r(a)===null&&R===r(f)&&(y?(h(w),w=-1):y=!0,V(g,A-B))):(R.sortIndex=H,t(a,R),b||S||(b=!0,W(x))),R},e.unstable_shouldYield=N,e.unstable_wrapCallback=function(R){var D=_;return function(){var A=_;_=D;try{return R.apply(this,arguments)}finally{_=A}}}})(Uh);Hh.exports=Uh;var gm=Hh.exports;/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var vm=M,dt=gm;function K(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var zh=new Set,ri={};function $r(e,t){ps(e,t),ps(e+"Capture",t)}function ps(e,t){for(ri[e]=t,e=0;e<t.length;e++)zh.add(t[e])}var Qt=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fa=Object.prototype.hasOwnProperty,ym=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Uc={},zc={};function Sm(e){return fa.call(zc,e)?!0:fa.call(Uc,e)?!1:ym.test(e)?zc[e]=!0:(Uc[e]=!0,!1)}function xm(e,t,r,s){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return s?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function bm(e,t,r,s){if(t===null||typeof t>"u"||xm(e,t,r,s))return!0;if(s)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function et(e,t,r,s,i,o,c){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=s,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=c}var Ie={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ie[e]=new et(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ie[t]=new et(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ie[e]=new et(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ie[e]=new et(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ie[e]=new et(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ie[e]=new et(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ie[e]=new et(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ie[e]=new et(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ie[e]=new et(e,5,!1,e.toLowerCase(),null,!1,!1)});var Al=/[\-:]([a-z])/g;function Ol(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!1,!1)});Ie.xlinkHref=new et("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!0,!0)});function Nl(e,t,r,s){var i=Ie.hasOwnProperty(t)?Ie[t]:null;(i!==null?i.type!==0:s||!(2<t.length)||t[0]!=="o"&&t[0]!==" Line truncated
`+ko+e}var Ro=!1;function To(e,t){if(!e||Ro)return"";Ro=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(f){var s=f}Reflect.construct(e,[],t)}else{try{t.call()}catch(f){s=f}e.call(t.prototype)}else{try{throw Error()}catch(f){s=f}e()}}catch(f){if(f&&s&&typeof f.stack=="string"){for(var i=f.stack.split(`
`),o=s.stack.split(`
`),c=i.length-1,n=o.length-1;1<=c&&0<=n&&i[c]!==o[n];)n--;for(;1<=c&&0<=n;c--,n--)if(i[c]!==o[n]){if(c!==1||n!==1)do if(c--,n--,0>n||i[c]!==o[n]){var a=`
`+i[c].replace(" at new "," at ");return e.displayName&&a.includes("<anonymous>")&&(a=a.replace("<anonymous>",e.displayName)),a}while(1<=c&&0<=n);break}}}finally{Ro=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?zs(e):""}function wm(e){switch(e.tag){case 5:return zs(e.type);case 16:return zs("Lazy");case 13:return zs("Suspense");case 19:return zs("SuspenseList");case 0:case 2:case 15:return e=To(e.type,!1),e;case 11:return e=To(e.type.render,!1),e;case 1:return e=To(e.type,!0),e;default:return""}}function ga(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Jr:return"Fragment";case Gr:return"Portal";case pa:return"Profiler";case Pl:return"StrictMode";case ma:return"Suspense";case _a:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Wh:return(e.displayName||"Context")+".Consumer";case $h:return(e._context.displayName||"Context")+".Provider";case Bl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case jl:return t=e.displayName||null,t!==null?t:ga(e.type)||"Memo";case sr:t=e._payload,e=e._init;try{return ga(e(t))}catch{}}return null}function Cm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ga(t);case 8:return t===Pl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Sr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function qh(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Em(e){var t=qh(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),s=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(c){s=""+c,o.call(this,c)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return s},setValue:function(c){s=""+c},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ii(e){e._valueTracker||(e._valueTracker=Em(e))}function Kh(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),s="";return e&&(s=qh(e)?e.checked?"true":"false":e.value),e=s,e!==r?(t.setValue(e),!0):!1}function Rn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function va(e,t){var r=t.checked;return xe({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Wc(e,t){var r=t.defaultValue==null?"":t.defaultValue,s=t.checked!=null?t.checked:t.defaultChecked;r=Sr(t.value!=null?t.value:r),e._wrapperState={initialChecked:s,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Xh(e,t){t=t.checked,t!=null&&Nl(e,"checked",t,!1)}function ya(e,t){Xh(e,t);var r=Sr(t.value),s=t.type;if(r!=null)s==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(s==="submit"||s==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Sa(e,t.type,r):t.hasOwnProperty("defaultValue")&&Sa(e,t.type,Sr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Vc(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var s=t.type;if(!(s!=="submit"&&s!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function Sa(e,t,r){(t!=="number"||Rn(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var $s=Array.isArray;function as(e,t,r,s){if(e=e.options,t){t={};for(var i=0;i<r.length;i++)t["$"+r[i]]=!0;for(r=0;r<e.length;r++)i=t.hasOwnProperty("$"+e[r].value),e[r].selected!==i&&(e[r].selected=i),i&&s&&(e[r].defaultSelected=!0)}else{for(r=""+Sr(r),t=null,i=0;i<e.length;i++){if(e[i].value===r){e[i].selected=!0,s&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function xa(e,t){if(t.dan Line truncated
`).replace(B_,"")}function qi(e,t,r){if(t=pu(t),pu(e)!==t&&r)throw Error(K(425))}function Bn(){}var Pa=null,Ba=null;function ja(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Ma=typeof setTimeout=="function"?setTimeout:void 0,j_=typeof clearTimeout=="function"?clearTimeout:void 0,mu=typeof Promise=="function"?Promise:void 0,M_=typeof queueMicrotask=="function"?queueMicrotask:typeof mu<"u"?function(e){return mu.resolve(null).then(e).catch(I_)}:Ma;function I_(e){setTimeout(function(){throw e})}function Uo(e,t){var r=t,s=0;do{var i=r.nextSibling;if(e.removeChild(r),i&&i.nodeType===8)if(r=i.data,r==="/$"){if(s===0){e.removeChild(i),ai(t);return}s--}else r!=="$"&&r!=="$?"&&r!=="$!"||s++;r=i}while(r);ai(t)}function fr(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function _u(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var Es=Math.random().toString(36).slice(2),Mt="__reactFiber$"+Es,di="__reactProps$"+Es,Yt="__reactContainer$"+Es,Ia="__reactEvents$"+Es,F_="__reactListeners$"+Es,H_="__reactHandles$"+Es;function Dr(e){var t=e[Mt];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Yt]||r[Mt]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=_u(e);e!==null;){if(r=e[Mt])return r;e=_u(e)}return t}e=r,r=e.parentNode}return null}function Ei(e){return e=e[Mt]||e[Yt],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function es(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(K(33))}function io(e){return e[di]||null}var Fa=[],ts=-1;function Cr(e){return{current:e}}function ge(e){0>ts||(e.current=Fa[ts],Fa[ts]=null,ts--)}function de(e,t){ts++,Fa[ts]=e.current,e.current=t}var xr={},Ge=Cr(xr),it=Cr(!1),Mr=xr;function ms(e,t){var r=e.type.contextTypes;if(!r)return xr;var s=e.stateNode;if(s&&s.__reactInternalMemoizedUnmaskedChildContext===t)return s.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=t[o];return s&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function nt(e){return e=e.childContextTypes,e!=null}function jn(){ge(it),ge(Ge)}function gu(e,t,r){if(Ge.current!==xr)throw Error(K(168));de(Ge,t),de(it,r)}function jd(e,t,r){var s=e.stateNode;if(t=t.childContextTypes,typeof s.getChildContext!="function")return r;s=s.getChildContext();for(var i in s)if(!(i in t))throw Error(K(108,Cm(e)||"Unknown",i));return xe({},r,s)}function Mn(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||xr,Mr=Ge.current,de(Ge,e),de(it,it.current),!0}function vu(e,t,r){var s=e.stateNode;if(!s)throw Error(K(169));r?(e=jd(e,t,Mr),s.__reactInternalMemoizedMergedChildContext=e,ge(it),ge(Ge),de(Ge,e)):ge(it),de(it,r)}var Vt=null,no=!1,zo=!1;function Md(e){Vt===null?Vt=[e]:Vt.push(e)}function U_(e){no=!0,Md(e)}function Er(){if(!zo&&Vt!==null){zo=!0;var e=0,t=ue;try{var r=Vt;for(ue=1;e<r.length;e++){var s=r[e];do s=s(!0);while(s!==null)}Vt=null,no=!1}catch(i){throw Vt!==null&&(Vt=Vt.slice(e+1)),ld(Il,Er),i}finally{ue=t,zo=!1}}return null}var rs=[],ss=0,In=null,Fn=0,_t=[],gt=0,Ir=null,Kt=1,Xt="";function Tr(e,t){rs[ss++]=Fn,rs[ss++]=In,In=e,Fn=t}function Id(e,t,r){_t[gt++]=Kt,_t[gt++]=Xt,_t[gt++]=Ir,Ir=e;var s=Kt;e=Xt;var i=32-Dt(s)-1;s&=~(1<<i),r+=1;var o=32-Dt(t)+i;if(30<o){var c=i-i%5;o=(s&(1<<c)-1).toString(32),s>>=c,i-=c,Kt=1<<32-Dt(t)+i|r<<i|s,Xt=o+e}else Kt=1<<o|r<<i|s,Xt=e}function Kl(e){e.return!==null&&(Tr(e,1),Id(e,1,0))}function Xl(e){for(;e===In;)In=rs[--ss],rs[ss]=null,Fn=rs[--ss],rs[ss]=null;for(;e===Ir;)Ir=_t[--gt],_t[gt]=null,Xt=_t[--gt],_t[gt]=null,Kt=_t[--gt],_t[gt]=null}var ht=null,ut=null,ve=!1,Lt=null;function Fd(e,t){var r=yt(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function yu(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,ht=e,ut=fr(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,ht=e,ut=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=Ir!==null?{id:Kt,overflow:Xt}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=yt(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,ht=e,ut=null,!0):!1;default:return!1}}function Ha(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Ua(e){if(ve){var t=ut;if(t){var r=t;if(!yu(e,t)){if(Ha(e))throw Error(K(418));t=fr(r.nextSibling);var s=ht;t&&yu(e,t)?Fd(s,r):(e.flags=e.flags&-4097|2,ve=!1,ht=e)}}else{if(Ha(e))throw Error(K(418));e.flags=e.flags&-4097|2,ve=!1,ht=e}}}function Su(e){for(e=e Line truncated
Error generating stack: `+o.message+`
`+o.stack}return{value:e,source:t,stack:i,digest:null}}function Ko(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Va(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var J_=typeof WeakMap=="function"?WeakMap:Map;function ff(e,t,r){r=Jt(-1,r),r.tag=3,r.payload={element:null};var s=t.value;return r.callback=function(){Kn||(Kn=!0,tl=s),Va(e,t)},r}function pf(e,t,r){r=Jt(-1,r),r.tag=3;var s=e.type.getDerivedStateFromError;if(typeof s=="function"){var i=t.value;r.payload=function(){return s(i)},r.callback=function(){Va(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(r.callback=function(){Va(e,t),typeof s!="function"&&(mr===null?mr=new Set([this]):mr.add(this));var c=t.stack;this.componentDidCatch(t.value,{componentStack:c!==null?c:""})}),r}function Tu(e,t,r){var s=e.pingCache;if(s===null){s=e.pingCache=new J_;var i=new Set;s.set(t,i)}else i=s.get(t),i===void 0&&(i=new Set,s.set(t,i));i.has(r)||(i.add(r),e=ug.bind(null,e,t,r),t.then(e,e))}function Lu(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Du(e,t,r,s,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Jt(-1,1),t.tag=2,pr(r,t,1))),r.lanes|=1),e)}var Q_=tr.ReactCurrentOwner,st=!1;function Je(e,t,r,s){t.child=e===null?zd(t,null,r,s):gs(t,e.child,r,s)}function Au(e,t,r,s,i){r=r.render;var o=t.ref;return hs(t,i),s=nc(e,t,r,s,o,i),r=oc(),e!==null&&!st?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,er(e,t,i)):(ve&&r&&Kl(t),t.flags|=1,Je(e,t,s,i),t.child)}function Ou(e,t,r,s,i){if(e===null){var o=r.type;return typeof o=="function"&&!_c(o)&&o.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=o,mf(e,t,o,s,i)):(e=yn(r.type,null,s,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,!(e.lanes&i)){var c=o.memoizedProps;if(r=r.compare,r=r!==null?r:ci,r(c,s)&&e.ref===t.ref)return er(e,t,i)}return t.flags|=1,e=gr(o,s),e.ref=t.ref,e.return=t,t.child=e}function mf(e,t,r,s,i){if(e!==null){var o=e.memoizedProps;if(ci(o,s)&&e.ref===t.ref)if(st=!1,t.pendingProps=s=o,(e.lanes&i)!==0)e.flags&131072&&(st=!0);else return t.lanes=e.lanes,er(e,t,i)}return qa(e,t,r,s,i)}function _f(e,t,r){var s=t.pendingProps,i=s.children,o=e!==null?e.memoizedState:null;if(s.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},de(os,lt),lt|=r;else{if(!(r&1073741824))return e=o!==null?o.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,de(os,lt),lt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},s=o!==null?o.baseLanes:r,de(os,lt),lt|=s}else o!==null?(s=o.baseLanes|r,t.memoizedState=null):s=r,de(os,lt),lt|=s;return Je(e,t,i,r),t.child}function gf(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function qa(e,t,r,s,i){var o=nt(r)?Mr:Ge.current;return o=ms(t,o),hs(t,i),r=nc(e,t,r,s,o,i),s=oc(),e!==null&&!st?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,er(e,t,i)):(ve&&s&&Kl(t),t.flags|=1,Je(e,t,r,i),t.child)}function Nu(e,t,r,s,i){if(nt(r)){var o=!0;Mn(t)}else o=!1;if(hs(t,i),t.stateNode===null)_n(e,t),df(t,r,s),Wa(t,r,s,i),s=!0;else if(e===null){var c=t.stateNode,n=t.memoizedProps;c.props=n;var a=c.context,f=r.contextType;typeof f=="object"&&f!==null?f=xt(f):(f=nt(r)?Mr:Ge.current,f=ms(t,f));var m=r.getDerivedStateFromProps,p=typeof m=="function"||typeof c.getSnapshotBeforeUpdate=="function";p||typeof c.UNSAFE_componentWillReceiveProps!="function"&&typeof c.componentWillReceiveProps!="function"||(n!==s||a!==f)&&Ru(t,c,s,f),ir=!1;var _=t.memoizedState;c.state=_,zn(t,s,c,i),a=t.memoizedState,n!==s||_!==a||it.current||ir?(typeof m=="function"&&($a(t,r,m,s),a=t.memoizedState),(n=ir||ku(t,r,n,s,_,a,f))?(p||typeof c.UNSAFE_componentWillMount!="function"&&typeof c.componentWillMount!="function"||(typeof c.componentWillMount=="function"&&c.componentWillMount(),typeof c.UNSAFE_componentWillMount=="function"&&c.UNSAFE_componentWillMount()),typeof c.componentDidMount=="function"&&(t.flags|=4194308)):(typeof c.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=s,t.memoizedState=a),c.props=s,c.state=a,c.context=f,s=n):(typeof c.componentDidMount=="function"&&(t.flags|=4194308),s=!1)}else{c=t.stateNode,Wd(e,t),n=t.memoizedProps,f=t.type===t.elementType?n:kt(t.type,n),c.props=f,p=t.pendingProps,_=c.context,a=r.contextType,typeof a=="object"&&a!==null?a=xt(a):(a=nt(r)?Mr:Ge.current,a=ms(t,a));var S=r.getDerivedStateFromProps;(m=typeof S=="function"||typeof c.getSnapshotBeforeUpdate=="function")||typeof c.UNSAFE_componentWillReceiveProps!="function"&&typeof c.componentWillReceiveProps!="function"||(n!==p||_!==a)&&Ru(t,c,s,a),ir=!1,_=t.memoizedState,c.state=_,zn(t,s,c,i);var b=t.memoizedS Line truncated
* @remix-run/router v1.23.2
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function yi(){return yi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},yi.apply(this,arguments)}var cr;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(cr||(cr={}));const Ku="popstate";function bg(e){e===void 0&&(e={});function t(s,i){let{pathname:o,search:c,hash:n}=s.location;return nl("",{pathname:o,search:c,hash:n},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Qn(i)}return Cg(t,r,null,e)}function Re(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function xc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function wg(){return Math.random().toString(36).substr(2,8)}function Xu(e,t){return{usr:e.state,key:e.key,idx:t}}function nl(e,t,r,s){return r===void 0&&(r=null),yi({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ks(t):t,{state:r,key:t&&t.key||s||wg()})}function Qn(e){let{pathname:t="/",search:r="",hash:s=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),s&&s!=="#"&&(t+=s.charAt(0)==="#"?s:"#"+s),t}function ks(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let s=e.indexOf("?");s>=0&&(t.search=e.substr(s),e=e.substr(0,s)),e&&(t.pathname=e)}return t}function Cg(e,t,r,s){s===void 0&&(s={});let{window:i=document.defaultView,v5Compat:o=!1}=s,c=i.history,n=cr.Pop,a=null,f=m();f==null&&(f=0,c.replaceState(yi({},c.state,{idx:f}),""));function m(){return(c.state||{idx:null}).idx}function p(){n=cr.Pop;let u=m(),h=u==null?null:u-f;f=u,a&&a({action:n,location:y.location,delta:h})}function _(u,h){n=cr.Push;let l=nl(y.location,u,h);f=m()+1;let d=Xu(l,f),g=y.createHref(l);try{c.pushState(d,"",g)}catch(x){if(x instanceof DOMException&&x.name==="DataCloneError")throw x;i.location.assign(g)}o&&a&&a({action:n,location:y.location,delta:1})}function S(u,h){n=cr.Replace;let l=nl(y.location,u,h);f=m();let d=Xu(l,f),g=y.createHref(l);c.replaceState(d,"",g),o&&a&&a({action:n,location:y.location,delta:0})}function b(u){let h=i.location.origin!=="null"?i.location.origin:i.location.href,l=typeof u=="string"?u:Qn(u);return l=l.replace(/ $/,"%20"),Re(h,"No window.location.(origin|href) available to create URL for href: "+l),new URL(l,h)}let y={get action(){return n},get location(){return e(i,c)},listen(u){if(a)throw new Error("A history only accepts one active listener");return i.addEventListener(Ku,p),a=u,()=>{i.removeEventListener(Ku,p),a=null}},createHref(u){return t(i,u)},createURL:b,encodeLocation(u){let h=b(u);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:_,replace:S,go(u){return c.go(u)}};return y}var Gu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Gu||(Gu={}));function Eg(e,t,r){return r===void 0&&(r="/"),kg(e,t,r)}function kg(e,t,r,s){let i=typeof t=="string"?ks(t):t,o=bc(i.pathname||"/",r);if(o==null)return null;let c=Uf(e);Rg(c);let n=null;for(let a=0;n==null&&a<c.length;++a){let f=Fg(o);n=jg(c[a],f)}return n}function Uf(e,t,r,s){t===void 0&&(t=[]),r===void 0&&(r=[]),s===void 0&&(s="");let i=(o,c,n)=>{let a={relativePath:n===void 0?o.path||"":n,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};a.relativePath.startsWith("/")&&(Re(a.relativePath.startsWith(s),'Absolute route path "'+a.relativePath+'" nested under path '+('"'+s+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),a.relativePath=a.relativePath.slice(s.length));let f=vr([s,a.relativePath]),m=r.concat(a);o.children&&o.children.length>0&&(Re(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+f+'".')),Uf(o.children,t,m,f)),!(o.path==null&&!o.index)&&t.push({path:f,score:Pg(f,o.index),routesMeta:m})};return e.forEach((o,c)=>{var n;if(o.path===""||!((n=o.path)!=null&&n.includes("?")))i(o,c);else for(let a of zf(o.path))i(o,c,a)}),t}function zf(e){let t=e.split("/");if(t.length===0)return[];let[r,...s]=t,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(s.length===0)return i?[o,""]:[o];let c=zf(s.join("/")),n=[];return n.push(...c.map(a=>a===""?o:[o,a].join("/"))),i&&n.push(...c),n.map(a=>e.startsWith("/")&&a===""?"/":a)}function Rg(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:Bg(t.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}const Tg=/^:[\w-]+$/,Lg=3,Dg=2,Ag=1,Og=10,Ng=-2,Ju=e=>e==="*";function Pg(e,t){let r=e.split("/"),s=r.length;return r.some(Ju)&&(s+=Ng),t&&(s+=Dg),r.filter(i=>!Ju(i)).reduce((i,o)=>i+(Tg.test(o)?Lg:o===""?Ag:Og),s)}function Bg(e,t){return e.length===t.length&&e.slice(0,-1).every((s,i)=>s===t[i])?e[e.length-1]-t[t.length-1]:0}function jg(e,t,r){let{routesMeta:s}=e,i={},o="/",c=[];for(let n=0;n<s.length;++n){let a=s[n],f=n===s.length-1,m=o==="/"?t:t.slice(o.length)||"/",p=Mg({path:a.relativePath,caseSensitive:a.caseSeLine truncated
* React Router v6.30.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function Si(){return Si=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Si.apply(this,arguments)}const wc=M.createContext(null),Gg=M.createContext(null),Vr=M.createContext(null),_o=M.createContext(null),kr=M.createContext({outlet:null,matches:[],isDataRoute:!1}),qf=M.createContext(null);function Jg(e,t){let{relative:r}=t===void 0?{}:t;Ri()||Re(!1);let{basename:s,navigator:i}=M.useContext(Vr),{hash:o,pathname:c,search:n}=Xf(e,{relative:r}),a=c;return s!=="/"&&(a=c==="/"?s:vr([s,c])),i.createHref({pathname:a,search:n,hash:o})}function Ri(){return M.useContext(_o)!=null}function Ti(){return Ri()||Re(!1),M.useContext(_o).location}function Kf(e){M.useContext(Vr).static||M.useLayoutEffect(e)}function Cc(){let{isDataRoute:e}=M.useContext(kr);return e?uv():Qg()}function Qg(){Ri()||Re(!1);let e=M.useContext(wc),{basename:t,future:r,navigator:s}=M.useContext(Vr),{matches:i}=M.useContext(kr),{pathname:o}=Ti(),c=JSON.stringify($f(i,r.v7_relativeSplatPath)),n=M.useRef(!1);return Kf(()=>{n.current=!0}),M.useCallback(function(f,m){if(m===void 0&&(m={}),!n.current)return;if(typeof f=="number"){s.go(f);return}let p=Wf(f,JSON.parse(c),o,m.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:vr([t,p.pathname])),(m.replace?s.replace:s.push)(p,m.state,m)},[t,s,c,o,e])}function Yg(){let{matches:e}=M.useContext(kr),t=e[e.length-1];return t?t.params:{}}function Xf(e,t){let{relative:r}=t===void 0?{}:t,{future:s}=M.useContext(Vr),{matches:i}=M.useContext(kr),{pathname:o}=Ti(),c=JSON.stringify($f(i,s.v7_relativeSplatPath));return M.useMemo(()=>Wf(e,JSON.parse(c),o,r==="path"),[e,c,o,r])}function Zg(e,t){return ev(e,t)}function ev(e,t,r,s){Ri()||Re(!1);let{navigator:i}=M.useContext(Vr),{matches:o}=M.useContext(kr),c=o[o.length-1],n=c?c.params:{};c&&c.pathname;let a=c?c.pathnameBase:"/";c&&c.route;let f=Ti(),m;if(t){var p;let u=typeof t=="string"?ks(t):t;a==="/"||(p=u.pathname)!=null&&p.startsWith(a)||Re(!1),m=u}else m=f;let _=m.pathname||"/",S=_;if(a!=="/"){let u=a.replace(/^\//,"").split("/");S="/"+_.replace(/^\//,"").split("/").slice(u.length).join("/")}let b=Eg(e,{pathname:S}),y=nv(b&&b.map(u=>Object.assign({},u,{params:Object.assign({},n,u.params),pathname:vr([a,i.encodeLocation?i.encodeLocation(u.pathname).pathname:u.pathname]),pathnameBase:u.pathnameBase==="/"?a:vr([a,i.encodeLocation?i.encodeLocation(u.pathnameBase).pathname:u.pathnameBase])})),o,r,s);return t&&y?M.createElement(_o.Provider,{value:{location:Si({pathname:"/",search:"",hash:"",state:null,key:"default"},m),navigationType:cr.Pop}},y):y}function tv(){let e=cv(),t=Kg(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return M.createElement(M.Fragment,null,M.createElement("h2",null,"Unexpected Application Error!"),M.createElement("h3",{style:{fontStyle:"italic"}},t),r?M.createElement("pre",{style:i},r):null,null)}const rv=M.createElement(tv,null);class sv extends M.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?M.createElement(kr.Provider,{value:this.props.routeContext},M.createElement(qf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function iv(e){let{routeContext:t,match:r,children:s}=e,i=M.useContext(wc);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),M.createElement(kr.Provider,{value:t},s)}function nv(e,t,r,s){var i;if(t===void 0&&(t=[]),r===void 0&&(r=null),s===void 0&&(s=null),e==null){var o;if(!r)return null;if(r.errors)e=r.matches;else if((o=s)!=null&&o.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let c=e,n=(i=r)==null?void 0:i.errors;if(n!=null){let m=c.findIndex(p=>p.route.id&&(n==null?void 0:n[p.route.id])!==void 0);m>=0||Re(!1),c=c.slice(0,Math.min(c.length,m+1))}let a=!1,f=-1;if(r&&s&&s.v7_partialHydration)for(let m=0;m<c.length;m++){let p=c[m];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(f=m),p.route.id){let{loaderData:_,errors:S}=r,b=p.route.loader&&_[p.route.id]===void 0&&(!S||S[p.route.id]===void 0);if(p.route.lazy||b){a=!0,f>=0?c=c.slice(0,f+1):c=[c[0]];break}}}return c.reduceRight((m,p,_)=>{let S,b=!1,y=null,u=null;r&&(S=n&&p.route.id?n[p.route.id]:Line truncated
* React Router DOM v6.30.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function al(){return al=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},al.apply(this,arguments)}function mv(e,t){if(e==null)return{};var r={},s=Object.keys(e),i,o;for(o=0;o<s.length;o++)i=s[o],!(t.indexOf(i)>=0)&&(r[i]=e[i]);return r}function _v(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function gv(e,t){return e.button===0&&(!t||t==="_self")&&!_v(e)}const vv=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],yv="6";try{window.__reactRouterVersion=yv}catch{}const Sv="startTransition",Zu=um[Sv];function xv(e){let{basename:t,children:r,future:s,window:i}=e,o=M.useRef();o.current==null&&(o.current=bg({window:i,v5Compat:!0}));let c=o.current,[n,a]=M.useState({action:c.action,location:c.location}),{v7_startTransition:f}=s||{},m=M.useCallback(p=>{f&&Zu?Zu(()=>a(p)):a(p)},[a,f]);return M.useLayoutEffect(()=>c.listen(m),[c,m]),M.useEffect(()=>dv(s),[s]),M.createElement(fv,{basename:t,children:r,location:n.location,navigationType:n.action,navigator:c,future:s})}const bv=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",wv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Cv=M.forwardRef(function(t,r){let{onClick:s,relative:i,reloadDocument:o,replace:c,state:n,target:a,to:f,preventScrollReset:m,viewTransition:p}=t,_=mv(t,vv),{basename:S}=M.useContext(Vr),b,y=!1;if(typeof f=="string"&&wv.test(f)&&(b=f,bv))try{let d=new URL(window.location.href),g=f.startsWith("//")?new URL(d.protocol+f):new URL(f),x=bc(g.pathname,S);g.origin===d.origin&&x!=null?f=x+g.search+g.hash:y=!0}catch{}let u=Jg(f,{relative:i}),h=Ev(f,{replace:c,state:n,target:a,preventScrollReset:m,relative:i,viewTransition:p});function l(d){s&&s(d),d.defaultPrevented||h(d)}return M.createElement("a",al({},_,{href:b||u,onClick:y||o?s:l,ref:r,target:a}))});var eh;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(eh||(eh={}));var th;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(th||(th={}));function Ev(e,t){let{target:r,replace:s,state:i,preventScrollReset:o,relative:c,viewTransition:n}=t===void 0?{}:t,a=Cc(),f=Ti(),m=Xf(e,{relative:c});return M.useCallback(p=>{if(gv(p,r)){p.preventDefault();let _=s!==void 0?s:Qn(f)===Qn(m);a(e,{replace:_,state:i,preventScrollReset:o,relative:c,viewTransition:n})}},[f,a,m,s,i,r,e,o,c,n])}const kv={user:null,theme:localStorage.getItem("dune-theme")||"emperor",connectionStatus:{database:!0,ssh:!0,bgd:!0,rmq:!0},toasts:[]};let Rv=0;function Tv(e,t){switch(t.type){case"SET_USER":return{...e,user:t.payload};case"SET_THEME":return{...e,theme:t.payload};case"SET_CONNECTION":return{...e,connectionStatus:{...e.connectionStatus,...t.payload}};case"ADD_TOAST":return{...e,toasts:[...e.toasts.slice(-2),{...t.payload,id:++Rv}]};case"REMOVE_TOAST":return{...e,toasts:e.toasts.filter(r=>r.id!==t.payload)};default:return e}}const Yf=M.createContext(null);function Lv({children:e}){const[t,r]=M.useReducer(Tv,kv);return M.useEffect(()=>{document.documentElement.dataset.theme=t.theme,localStorage.setItem("dune-theme",t.theme)},[t.theme]),v.jsx(Yf.Provider,{value:{state:t,dispatch:r},children:e})}function Fe(){const e=M.useContext(Yf);if(!e)throw new Error("useApp must be used within AppProvider");return e}function Dv(){const{dispatch:e}=Fe(),t=M.useRef(null);M.useEffect(()=>{const r=new EventSource("/api/events/stream");return t.current=r,r.onopen=()=>{console.log("[SSE] Connected")},r.addEventListener("battlegroup_update",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] battlegroup_update",i)}catch{}}),r.addEventListener("rmq_health",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] rmq_health",i)}catch{}}),r.addEventListener("connection_status",s=>{try{const i=JSON.parse(s.data);e({type:"SET_CONNECTION",payload:i})}catch{}}),r.addEventListener("chat_message",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] chat_message",i)}catch{}}),r.onerror=()=>{console.warn("[SSE] Connection error")},()=>{r.close()}},[e])}const Av=[{key:"default",label:"Classic Dune"},{key:"atreides",label:"House Atreides"},{key:"harkonnen",label:"House Harkonnen"},{key:"fremen",label:"Fremen"},{key:"bene-gesserit",label:"Bene Gesserit"},{key:"spacing-guild",label:"Spacing Guild"},{key:"emperor",label:"Emperor"},{key:"corrino",label:"House Corrino"},{key:"mentat",label:"Mentat"},{key:"sardaukar",label:"Sardaukar"},{key:"tleilax",label:"Bene Tleilax"},{key:"ordos",label:"House Ordos"},{key:"ix",label:"Ix"},{key:"choam",label:"CHOAM"}];function Ov(){const{state:e,dispatch:t}=Fe(),[r,s]=M.useState(!1),i=M.useRef(null);return M.useEffect(()=>{function o(c){i.current&&!i.current.contains(c.target)&&s(!1)}return document.addEventLiLine truncated
`).forEach(function(c){i=c.indexOf(":"),r=c.substring(0,i).trim().toLowerCase(),s=c.substring(i+1).trim(),!(!r||t[r]&&ky[r])&&(r==="set-cookie"?t[r]?t[r].push(s):t[r]=[s]:t[r]=t[r]?t[r]+", "+s:s)}),t};function Ty(e){let t=0,r=e.length;for(;t<r;){const s=e.charCodeAt(t);if(s!==9&&s!==32)break;t+=1}for(;r>t;){const s=e.charCodeAt(r-1);if(s!==9&&s!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}const Ly=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Dy=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Ec(e,t){return I.isArray(e)?e.map(r=>Ec(r,t)):Ty(String(e).replace(t,""))}const Ay=e=>Ec(e,Ly),Oy=e=>Ec(e,Dy);function ap(e){const t=Object.create(null);return I.forEach(e.toJSON(),(r,s)=>{t[s]=Oy(r)}),t}const ih=Symbol("internals");function Is(e){return e&&String(e).trim().toLowerCase()}function xn(e){return e===!1||e==null?e:I.isArray(e)?e.map(xn):Ay(String(e))}function Ny(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(e);)t[s[1]]=s[2];return t}const Py=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Yo(e,t,r,s,i){if(I.isFunction(s))return s.call(this,t,r);if(i&&(t=r),!!I.isString(t)){if(I.isString(s))return t.indexOf(s)!==-1;if(I.isRegExp(s))return s.test(t)}}function By(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,s)=>r.toUpperCase()+s)}function jy(e,t){const r=I.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+r,{__proto__:null,value:function(i,o,c){return this[s].call(this,t,i,o,c)},configurable:!0})})}let Ye=class{constructor(t){t&&this.set(t)}set(t,r,s){const i=this;function o(n,a,f){const m=Is(a);if(!m)throw new Error("header name must be a non-empty string");const p=I.findKey(i,m);(!p||i[p]===void 0||f===!0||f===void 0&&i[p]!==!1)&&(i[p||a]=xn(n))}const c=(n,a)=>I.forEach(n,(f,m)=>o(f,m,a));if(I.isPlainObject(t)||t instanceof this.constructor)c(t,r);else if(I.isString(t)&&(t=t.trim())&&!Py(t))c(Ry(t),r);else if(I.isObject(t)&&I.isIterable(t)){let n={},a,f;for(const m of t){if(!I.isArray(m))throw TypeError("Object iterator must return a key-value pair");n[f=m[0]]=(a=n[f])?I.isArray(a)?[...a,m[1]]:[a,m[1]]:m[1]}c(n,r)}else t!=null&&o(r,t,s);return this}get(t,r){if(t=Is(t),t){const s=I.findKey(this,t);if(s){const i=this[s];if(!r)return i;if(r===!0)return Ny(i);if(I.isFunction(r))return r.call(this,i,s);if(I.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Is(t),t){const s=I.findKey(this,t);return!!(s&&this[s]!==void 0&&(!r||Yo(this,this[s],s,r)))}return!1}delete(t,r){const s=this;let i=!1;function o(c){if(c=Is(c),c){const n=I.findKey(s,c);n&&(!r||Yo(s,s[n],n,r))&&(delete s[n],i=!0)}}return I.isArray(t)?t.forEach(o):o(t),i}clear(t){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const o=r[s];(!t||Yo(this,this[o],o,t,!0))&&(delete this[o],i=!0)}return i}normalize(t){const r=this,s={};return I.forEach(this,(i,o)=>{const c=I.findKey(s,o);if(c){r[c]=xn(i),delete r[o];return}const n=t?By(o):String(o).trim();n!==o&&delete r[o],r[n]=xn(i),s[n]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const r=Object.create(null);return I.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=t&&I.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const s=new this(t);return r.forEach(i=>s.set(i)),s}static accessor(t){const s=(this[ih]=this[ih]={accessors:{}}).accessors,i=this.prototype;function o(c){const n=Is(c);s[n]||(jy(i,c),s[n]=!0)}return I.isArray(t)?t.forEach(o):o(t),this}};Ye.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);I.reduceDescriptors(Ye.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[r]=s}}});I.freezeMethods(Ye);const My="[REDACTED ****]";function Iy(e){if(I.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(I.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function Fy(e,t){const r=new Set(t.map(o=>String(o).toLowerCase())),s=[],i=o=>{if(o===null||typeof o!="object"||I.isBuffer(o))return o;if(s.indexOf(o)!==-1)return;o instanceof Ye&&(o=o.toJSON()),s.push(o);let c;if(I.isArray(o))c=[],o.forEach((n,a)=>{const f=i(n);I.isUndefined(f)||(c[a]=f)});else{if(!I.isPlainObject(o)&&Iy(o))return s.pop(),o;c=Object.create(null);for(const[n,a]of Object.entries(o)){const f=r.has(n.toLowerCase())?My:i(a);I.isUndefined(f)||(c[n]=f)}}return s.pop(),c};return i(e)}let Z=class lp extends Error{static from(t,r,s,i,o,c){const n=new lp(t.message,r||t.code,s,i,o);return n.cause=t,n.name=t.name,t.status!=null&&n.status==null&&(n.status=t.status),c&&Object.assign(n,c),n}constructor(t,r,s,i,o){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),s&&(this.config=s),i&&(this.request=i),o&&(this.response=o,this.status=o.status)}toJSON(){const t=this.config,r=t&&I.hasOwnProp(t,"redact")?t.redact:void 0,s=I.isArray(r)&&r.length>0?Fy(t,r):I.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};Z.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Z.ERR_BAD_OPTION="ERR_BAD_OPTION";Z.ECONNABORTED="ECONNABORTED";Z.ETIMEDOUT="ETIMEDOUT";Z.ECONNREFUSED="ECONNREFUSED";Z.ERR_NETWORK="ERR_NETWORK";Z.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Z.ERR_DEPRECATED="ERR_DEPRECATED";Z.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Z.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Z.ERR_CANCELED="ERR_CANCELED";Z.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Z.ERR_INVALID_URL="ERR_INVALID_URL";Z.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const Hy=null;function ul(e){return I.isPlainObject(e)||I.isArray(e)}function cp(e){return I.endsWith(e,"[]")?e.slice(0,-2):e}function Zo(e,t,r){return e?e.concat(t).map(function(i,o){return i=cp(i),!r&&o?"["+i+"]":i}).join(r?".":""):t}function Uy(e){return I.isArray(e)&&!e.some(ul)}const zy=I.toFlatObject(I,{},null,function(t){return/^is[A-Z]/.test(t)});function xo(e,t,r){if(!I.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,r=I.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,h){return!I.isUndefined(h[u])});const s=r.metaTokens,i=r.visitor||p,o=r.dots,c=r.indexes,n=r.Blob||typeof Blob<"u"&&Blob,a=r.maxDepth===void 0?100:r.maxDepth,f=n&&I.isSpecCompliantForm(t);if(!I.isFunction(i))throw new TypeError("visitor must be a function");function m(y){if(y===null)return"";if(I.isDate(y))return y.toISOString();if(I.isBoolean(y))return y.toString();if(!f&&I.isBlob(y))throw new Z("Blob is not supported. Use a Buffer instead.");return I.isArrayBuffer(y)||I.isTypedArray(y)?f&&typeof Blob=="function"?new Blob([y]):Buffer.from(y):y}function p(y,u,h){let l=y;if(I.isReactNative(t)&&I.isReactNativeBlob(y))return t.append(Zo(h,u,o),m(y)),!1;if(y&&!h&&typeof y=="object"){if(I.endsWith(u,"{}"))u=s?u:u.slice(0,-2),y=JSON.stringify(y);else if(I.isArray(y)&&Uy(y)||(I.isFileList(y)||I.endsWith(u,"[]"))&&(l=I.toArray(y)))return u=cp(u),l.forEach(function(g,x){!(I.isUndefined(g)||g===null)&&t.append(c===!0?Zo([u],x,o):c===null?u:u+"[]",m(g))}),!1}return ul(y)?!0:(t.append(Zo(h,u,o),m(y)),!1)}const _=[],S=Object.assign(zy,{defaultVisitor:p,convertValue:m,isVisitable:ul});function b(y,u,h=0){if(!I.isUndefined(y)){if(h>a)throw new Z("Object is too deeply nested ("+h+" levels). Max depth: "+a,Z.ERR_FORM_DATA_DEPTH_EXCEEDED);if(_.indexOf(y)!==-1)throw Error("Circular reference detected in "+u.join("."));_.push(y),I.forEach(y,function(d,g){(!(I.isUndefined(d)||d===null)&&i.call(t,d,I.isString(g)?g.trim():g,u,S))===!0&&b(d,u?u.concat(g):[g],h+1)}),_.pop()}}if(!I.isObject(e))throw new TypeError("data must be an object");return b(e),t}function nh(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(s){return t[s]})}function kc(e,t){t Line truncated
`+c.map(fh).join(`
`):" "+fh(c[0]):"as no adapter specified";throw new Z("There is no suitable adapter to dispatch the request "+n,"ERR_NOT_SUPPORT")}return i}const vp={getAdapter:b0,adapters:Dc};function ta(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ni(null,e)}function ph(e){return ta(e),e.headers=Ye.from(e.headers),e.data=ea.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),vp.getAdapter(e.adapter||Oi.adapter,e)(e).then(function(s){ta(e),e.response=s;try{s.data=ea.call(e,e.transformResponse,s)}finally{delete e.response}return s.headers=Ye.from(s.headers),s},function(s){if(!fp(s)&&(ta(e),s&&s.response)){e.response=s.response;try{s.response.data=ea.call(e,e.transformResponse,s.response)}finally{delete e.response}s.response.headers=Ye.from(s.response.headers)}return Promise.reject(s)})}const bo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{bo[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const mh={};bo.transitional=function(t,r,s){function i(o,c){return"[Axios v"+Lc+"] Transitional option '"+o+"'"+c+(s?". "+s:"")}return(o,c,n)=>{if(t===!1)throw new Z(i(c," has been removed"+(r?" in "+r:"")),Z.ERR_DEPRECATED);return r&&!mh[c]&&(mh[c]=!0,console.warn(i(c," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,c,n):!0}};bo.spelling=function(t){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function w0(e,t,r){if(typeof e!="object")throw new Z("options must be an object",Z.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let i=s.length;for(;i-- >0;){const o=s[i],c=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(c){const n=e[o],a=n===void 0||c(n,o,e);if(a!==!0)throw new Z("option "+o+" must be "+a,Z.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Z("Unknown option "+o,Z.ERR_BAD_OPTION)}}const bn={assertOptions:w0,validators:bo},mt=bn.validators;let jr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new oh,response:new oh}}async request(t,r){try{return await this._request(t,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const o=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(`
`);return c===-1?"":i.stack.slice(c+1)})();try{if(!s.stack)s.stack=o;else if(o){const c=o.indexOf(`
`),n=c===-1?-1:o.indexOf(`
`,c+1),a=n===-1?"":o.slice(n+1);String(s.stack).endsWith(a)||(s.stack+=`
`+o)}}catch{}}throw s}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=zr(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:o}=r;s!==void 0&&bn.assertOptions(s,{silentJSONParsing:mt.transitional(mt.boolean),forcedJSONParsing:mt.transitional(mt.boolean),clarifyTimeoutError:mt.transitional(mt.boolean),legacyInterceptorReqResOrdering:mt.transitional(mt.boolean)},!1),i!=null&&(I.isFunction(i)?r.paramsSerializer={serialize:i}:bn.assertOptions(i,{encode:mt.function,serialize:mt.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),bn.assertOptions(r,{baseUrl:mt.spelling("baseURL"),withXsrfToken:mt.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let c=o&&I.merge(o.common,o[r.method]);o&&I.forEach(["delete","get","head","post","put","patch","query","common"],b=>{delete o[b]}),r.headers=Ye.concat(c,o);const n=[];let a=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;a=a&&y.synchronous;const u=r.transitional||Rc;u&&u.legacyInterceptorReqResOrdering?n.unshift(y.fulfilled,y.rejected):n.push(y.fulfilled,y.rejected)});const f=[];this.interceptors.response.forEach(function(y){f.push(y.fulfilled,y.rejected)});let m,p=0,_;if(!a){const b=[ph.bind(this),void 0];for(b.unshift(...n),b.push(...f),_=b.length,m=Promise.resolve(r);p<_;)m=m.then(b[p++],b[p++]);return m}_=n.length;let S=r;for(;p<_;){const b=n[p++],y=n[p++];try{S=b(S)}catch(u){y.call(this,u);break}}try{m=ph.call(this,S)}catch(b){return Promise.reject(b)}for(p=0,_=f.length;p<_;)m=m.then(f[p++],f[p++]);return m}getUri(t){t=zr(this.defaults,t);const r=mp(t.baseURL,t.url,t.allowAbsoluteUrls);return hp(r,t.params,t.paramsSerializer)}};I.forEach(["delete","get","head","options"],function(t){jr.prototype[t]=function(r,s){return this.request(zr(s||{},{method:t,url:r,data:(s||{}).data}))}});I.forEach(["post","put","patch","query"],function(t){function r(s){return function(o,c,n){return this.request(zr(n||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:c}))}}jr.prototype[t]=r(),t!=="query"&&(jr.prototype[t+"Form"]=r(!0))});let C0=class yp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const s=this;this.promise.then(i=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](i);s._listeners=null}),this.promise.then=i=>{let o;const c=new Promise(n=>{s.subscribe(n),o=n}).then(i);return c.cancel=function(){s.unsubscribe(o)},c},t(function(o,c,n){s.reason||(s.reason=new Ni(o,c,n),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=s=>{t.abort(s)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new yp(function(i){t=i}),cancel:t}}};function E0(e){return function(r){return e.apply(null,r)}}function k0(e){return I.isObject(e)&&e.isAxiosError===!0}const dl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(dl).forEach(([e,t])=>{dl[t]=e});function Sp(e){const t=new jr(e),r=Zf(jr.prototype.request,t);return I.extend(r,jr.prototype,t,{allOwnKeys:!0}),I.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Sp(zr(e,i))},r}const Ce=Sp(Oi);Ce.Axios=jr;Ce.CanceledError=Ni;Ce.CancelToken=C0;Ce.isCa Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var bs=M;function T0(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var L0=typeof Object.is=="function"?Object.is:T0,D0=bs.useState,A0=bs.useEffect,O0=bs.useLayoutEffect,N0=bs.useDebugValue;function P0(e,t){var r=t(),s=D0({inst:{value:r,getSnapshot:t}}),i=s[0].inst,o=s[1];return O0(function(){i.value=r,i.getSnapshot=t,ra(i)&&o({inst:i})},[e,r,t]),A0(function(){return ra(i)&&o({inst:i}),e(function(){ra(i)&&o({inst:i})})},[e]),N0(r),r}function ra(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!L0(e,r)}catch{return!0}}function B0(e,t){return t()}var j0=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?B0:P0;bp.useSyncExternalStore=bs.useSyncExternalStore!==void 0?bs.useSyncExternalStore:j0;xp.exports=bp;var _h=xp.exports;const wp=0,Cp=1,Ep=2,gh=3;var vh=Object.prototype.hasOwnProperty;function fl(e,t){var r,s;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((s=e.length)===t.length)for(;s--&&fl(e[s],t[s]););return s===-1}if(!r||typeof e=="object"){s=0;for(r in e)if(vh.call(e,r)&&++s&&!vh.call(t,r)||!(r in t)||!fl(e[r],t[r]))return!1;return Object.keys(t).length===s}}return e!==e&&t!==t}const qt=new WeakMap,Gt=()=>{},Ke=Gt(),pl=Object,se=e=>e===Ke,It=e=>typeof e=="function",br=(e,t)=>({...e,...t}),kp=e=>It(e.then),sa={},rn={},Ac="undefined",Pi=typeof window!=Ac,ml=typeof document!=Ac,M0=Pi&&"Deno"in window,I0=()=>Pi&&typeof window.requestAnimationFrame!=Ac,Rp=(e,t)=>{const r=qt.get(e);return[()=>!se(t)&&e.get(t)||sa,s=>{if(!se(t)){const i=e.get(t);t in rn||(rn[t]=i),r[5](t,br(i,s),i||sa)}},r[6],()=>!se(t)&&t in rn?rn[t]:!se(t)&&e.get(t)||sa]};let _l=!0;const F0=()=>_l,[gl,vl]=Pi&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[Gt,Gt],H0=()=>{const e=ml&&document.visibilityState;return se(e)||e!=="hidden"},U0=e=>(ml&&document.addEventListener("visibilitychange",e),gl("focus",e),()=>{ml&&document.removeEventListener("visibilitychange",e),vl("focus",e)}),z0=e=>{const t=()=>{_l=!0,e()},r=()=>{_l=!1};return gl("online",t),gl("offline",r),()=>{vl("online",t),vl("offline",r)}},$0={isOnline:F0,isVisible:H0},W0={initFocus:U0,initReconnect:z0},yh=!bi.useId,fs=!Pi||M0,V0=e=>I0()?window.requestAnimationFrame(e):setTimeout(e,1),ia=fs?M.useEffect:M.useLayoutEffect,na=typeof navigator<"u"&&navigator.connection,Sh=!fs&&na&&(["slow-2g","2g"].includes(na.effectiveType)||na.saveData),sn=new WeakMap,q0=e=>pl.prototype.toString.call(e),oa=(e,t)=>e===`[object ${t}]`;let K0=0;const yl=e=>{const t=typeof e,r=q0(e),s=oa(r,"Date"),i=oa(r,"RegExp"),o=oa(r,"Object");let c,n;if(pl(e)===e&&!s&&!i){if(c=sn.get(e),c)return c;if(c=++K0+"~",sn.set(e,c),Array.isArray(e)){for(c="@",n=0;n<e.length;n++)c+=yl(e[n])+",";sn.set(e,c)}if(o){c="#";const a=pl.keys(e).sort();for(;!se(n=a.pop());)se(e[n])||(c+=n+":"+yl(e[n])+",");sn.set(e,c)}}else c=s?e.toJSON():t=="symbol"?e.toString():t=="string"?JSON.stringify(e):""+e;return c},Oc=e=>{if(It(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?yl(e):"",[e,t]};let X0=0;const Sl=()=>++X0;async function Tp(...e){const[t,r,s,i]=e,o=br({populateCache:!0,throwOnError:!0},typeof i=="boolean"?{revalidate:i}:i||{});let c=o.populateCache;const n=o.rollbackOnError;let a=o.optimisticData;const f=_=>typeof n=="function"?n(_):n!==!1,m=o.throwOnError;if(It(r)){const _=r,S=[],b=t.keys();for(const y of b)!/^\$(inf|sub)\$/.test(y)&&_(t.get(y)._k)&&S.push(y);return Promise.all(S.map(p))}return p(r);async function p(_){const[S]=Oc(_);if(!S)return;const[b,y]=Rp(t,S),[u,h,l,d]=qt.get(t),g=()=>{const F=u[S];return(It(o.revalidate)?o.revalidate(b().data,_):o.revalidate!==!1)&&(delete l[S],delete d[S],F&&F[0])?F[0](Ep).then(()=>b().data):b().data};if(e.length<3)return g();let x=s,C,k=!1;const w=Sl();h[S]=[w,0];const E=!se(a),L=b(),N=L.data,O=L._c,P=se(O)?N:O;if(E&&(a=It(a)?a(P,N):a,y({data:a,_c:P})),It(x))try{x=x(P)}catch(F){C=F,k=!0}if(x&&kp(x))if(x=await x.catch(F=>{C=F,k=!0}),w!==h[S][0]){if(k)throw C;return x}else k&&E&&f(C)&&(c=!0,y({data:P,_c:Ke}));if(c&&!k)if(It(c)){const F=c(x,P);y({data:F,error:Ke,_c:Ke})}else y({data:x,error:Ke,_c:Ke});if(h[S][1]=Sl(),Promise.resolve(g()).then(()=>{y({_c:Ke})}),k){if(m)throw C;return}return x}}const xh=(e,t)=>{for(const r in e)e[r][0]&&e[r][0](t)},G0=(e,t)=>{if(!qt.has(e)){const r=br(W0,t),s=Object.create(null),i=Tp.bind(Ke,e);let o=Gt;const c=Object.create(null),n=(m,p)=>{const _=c[m]||[];return c[m]=_,_.push(p),()=>_.splice(_.indexOf(p),1)},a=(m,p,_)=>{e.set(m,p);const S=c[m];if(S)for(const b of S)b(p,_)},f=()=>{if(!qt.has(e)&&(qt.set(e,[s,Object.create(null),Object.create(null),Object.create(null),i,a,n]),!fs)){const m=r.initFocus(setTimeout.bind(Ke,xh.bind(Ke,s,wp))),p=r.initReconnect(setTimeout.bind(Ke,xh.bind(Ke,s,Cp)));o=()=>{m&&m(),p&&p(),qt.delete(e)}}};return f(),[e,i,f,o]}return[e,qt.get(e)[4]]},J0=(e,t,r,s,Line truncated
`))),this.register(this._terminal.onA11yTab(x=>this._handleTab(x))),this.register(this._terminal.onKey(x=>this._handleKey(x.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._screenDprMonitor=new y.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener(()=>this._refreshRowsDimensions()),this.register((0,h.addDisposableDomListener)(window,"resize",()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,b.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(d){for(let g=0;g<d;g++)this._handleChar(" ")}_handleChar(d){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==d&&(this._charsToAnnounce+=d):this._charsToAnnounce+=d,d===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=p.tooMuchOutput)),_.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(()=>{this._accessibilityContainer.appendChild(this._liveRegion)},0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,_.isMac&&this._liveRegion.remove()}_handleKey(d){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(d)||this._charsToConsume.push(d)}_refreshRows(d,g){this._liveRegionDebouncer.refresh(d,g,this._terminal.rows)}_renderRows(d,g){const x=this._terminal.buffer,C=x.lines.length.toString();for(let k=d;k<=g;k++){const w=x.translateBufferLineToString(x.ydisp+k,!0),E=(x.ydisp+k+1).toString(),L=this._rowElements[k];L&&(w.length===0?L.innerText=" ":L.textContent=w,L.setAttribute("aria-posinset",E),L.setAttribute("aria-setsize",C))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(d,g){const x=d.target,C=this._rowElements[g===0?1:this._rowElements.length-2];if(x.getAttribute("aria-posinset")===(g===0?"1":`${this._terminal.buffer.lines.length}`)||d.relatedTarget!==C)return;let k,w;if(g===0?(k=x,w=this._rowElements.pop(),this._rowContainer.removeChild(w)):(k=this._rowElements.shift(),w=x,this._rowContainer.removeChild(k)),k.removeEventListener("focus",this._topBoundaryFocusListener),w.removeEventListener("focus",this._bottomBoundaryFocusListener),g===0){const E=this._createAccessibilityTreeNode();this._rowElements.unshift(E),this._rowContainer.insertAdjacentElement("afterbegin",E)}else{const E=this._createAccessibilityTreeNode();this._rowElements.push(E),this._rowContainer.appendChild(E)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(g===0?-1:1),this._rowElements[g===0?1:this._rowElements.length-2].focus(),d.preventDefault(),d.stopImmediatePropagation()}_handleResize(d){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let g=this._rowContainer.children.length;g<this._terminal.rows;g++)this._rowElements[g]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[g]);for(;this._rowElements.length>d;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const d=document.createElement("div");return d.setAttribute("role","listitem"),d.tabIndex=-1,this._refreshRowDimensions(d),d}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let d=0;d<this._terminal.rows;d++)this._refreshRowDimensions(this._rowElements[d])}}_refreshRowDimensions(d){d.style.height=`${this._renderService.dimensions.css.cell.height}px`}};n.AccessibilityManager=l=f([m(1,u.IRenderService)],l)},3614:(c,n)=>{function a(_){return _.replace(/\r?\n/g,"\r")}function f(_,S){return S?"\x1B[200~"+_+"\x1B[201~":_}function m(_,S,b,y){_=f(_=a(_),b.decPrivateModes.bracketedPasteMode&&y.rawOptions.ignoreBracketedPasteMode!==!0),b.triggerDataEvent(_,!0),S.value=""}function p(_,S,b){const y=b.getBoundingClientRect(),u=_.clientX-y.left-10,h=_.clientY-y.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${u}px`,S.style.top=`${h}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(n,"__esModule",{value:!0}),n.rightClickHandler=n.moveTextAreaUnderMouseCursor=n.paste=n.handlePasteEvent=n.copyHandler=n.bracketTextForPaste=n.prepareTextForTerminal=void 0,n.prepareTextForTerminal=a,n.bracketTextForPaste=f,n.copyHandler=function(_,S){_.clipboardData&&_.clipboardData.setData("text/plain",S.selectionText),_.preventDefault()},n.handlePasteEvent=function(_,S,b,y){_.stopPropagation(),_.clipboardData&&m(_.clipboardData.getData("text/plain"),S,b,y)},n.paste=m,n.moveTextAreaUnderMouseCursor=p,n.rightClickHandler=function(_,S,b,y,u){p(_,S,b),u&&y.rightClickSelect(_),S.value=y.selectionText,S.select()}},7239:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorContrastCache=void 0;const f=a(1505);n.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(m,p,_){this._css.set(m,p,_)}getCss(m,p){return this._css.get(m,p)}setColor(m,p,_){this._color.set(m,p,_)}getColor(m,p){return this._color.get(m,p)}clear(){this._color.clear(),this._css.clear()}}},3656:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.addDisposableDomListener=void 0,n.addDisposableDomListener=function(a,f,m,p) Line truncated
WARNING: This link could potentially be dangerous`)){const h=window.open();if(h){try{h.opener=null}catch{}h.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}}n.OscLinkProvider=S=f([m(0,_.IBufferService),m(1,_.IOptionsService),m(2,_.IOscLinkService)],S)},6193:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.RenderDebouncer=void 0,n.RenderDebouncer=class{constructor(a,f){this._parentWindow=a,this._renderCallback=f,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(a){return this._refreshCallbacks.push(a),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(a,f,m){this._rowCount=m,a=a!==void 0?a:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,a):a,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const a=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(a,f),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const a of this._refreshCallbacks)a(0);this._refreshCallbacks=[]}}},5596:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ScreenDprMonitor=void 0;const f=a(844);class m extends f.Disposable{constructor(_){super(),this._parentWindow=_,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,f.toDisposable)(()=>{this.clearListener()}))}setListener(_){this._listener&&this.clearListener(),this._listener=_,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var _;this._outerListener&&((_=this._resolutionMediaMatchList)===null||_===void 0||_.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}n.ScreenDprMonitor=m},3236:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;const f=a(3614),m=a(3656),p=a(6465),_=a(9042),S=a(3730),b=a(1680),y=a(3107),u=a(5744),h=a(2950),l=a(1296),d=a(428),g=a(4269),x=a(5114),C=a(8934),k=a(3230),w=a(9312),E=a(4725),L=a(6731),N=a(8055),O=a(8969),P=a(8460),F=a(844),z=a(6114),W=a(8437),V=a(2584),R=a(7399),D=a(5941),A=a(9074),B=a(2585),H=a(5435),q=a(4567),G=typeof window<"u"?window.document:null;class X extends O.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(T={}){super(T),this.browser=z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new F.MutableDisposable),this._onCursorMove=this.register(new P.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new P.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new P.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new P.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new P.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new P.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new P.EventEmitter),this._onBlur=this.register(new P.EventEmitter),this._onA11yCharEmitter=this.register(new P.EventEmitter),this._onA11yTabEmitter=this.register(new P.EventEmitter),this._onWillOpen=this.register(new P.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(p.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(S.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((j,$)=>this.refresh(j,$))),this.r Line truncated
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(w){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),h.isLinux&&w&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(w){const E=this._getMouseBufferCoords(w),L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!!(L&&N&&E)&&this._areCoordsInSelection(E,L,N)}isCellInSelection(w,E){const L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!(!L||!N)&&this._areCoordsInSelection([w,E],L,N)}_areCoordsInSelection(w,E,L){return w[1]>E[1]&&w[1]<L[1]||E[1]===L[1]&&w[1]===E[1]&&w[0]>=E[0]&&w[0]<L[0]||E[1]<L[1]&&w[1]===L[1]&&w[0]<L[0]||E[1]<L[1]&&w[1]===E[1]&&w[0]>=E[0]}_selectWordAtCursor(w,E){var L,N;const O=(N=(L=this._linkifier.currentLink)===null||L===void 0?void 0:L.link)===null||N===void 0?void 0:N.range;if(O)return this._model.selectionStart=[O.start.x-1,O.start.y-1],this._model.selectionStartLength=(0,l.getRangeLength)(O,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const P=this._getMouseBufferCoords(w);return!!P&&(this._selectWordAt(P,E),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(w,E){this._model.clearSelection(),w=Math.max(w,0),E=Math.min(E,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,w],this._model.selectionEnd=[this._bufferService.cols,E],this.refresh(),this._onSelectionChange.fire()}_handleTrim(w){this._model.handleTrim(w)&&this.refresh()}_getMouseBufferCoords(w){const E=this._mouseService.getCoords(w,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(E)return E[0]--,E[1]--,E[1]+=this._bufferService.buffer.ydisp,E}_getMouseEventScrollAmount(w){let E=(0,p.getCoordsRelativeToElement)(this._coreBrowserService.window,w,this._screenElement)[1];const L=this._renderService.dimensions.css.canvas.height;return E>=0&&E<=L?0:(E>L&&(E-=L),E=Math.min(Math.max(E,-50),50),E/=50,E/Math.abs(E)+Math.round(14*E))}shouldForceSelection(w){return h.isMac?w.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:w.shiftKey}handleMouseDown(w){if(this._mouseDownTimeStamp=w.timeStamp,(w.button!==2||!this.hasSelection)&&w.button===0){if(!this._enabled){if(!this.shouldForceSelection(w))return;w.stopPropagation()}w.preventDefault(),this._dragScrollAmount=0,this._enabled&&w.shiftKey?this._handleIncrementalClick(w):w.detail===1?this._handleSingleClick(w):w.detail===2?this._handleDoubleClick(w):w.detail===3&&this._handleTripleClick(w),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(w){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(w))}_handleSingleClick(w){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(w)?3:0,this._model.selectionStart=this._getMouseBufferCoords(w),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const E=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);E&&E.length!==this._model.selectionStart[0]&&E.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(w){this._selectWordAtCursor(w,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(w){const E=this._getMouseBufferCoords(w);E&&(this._activeSelectionMode=2,this._selectLineAt(E[1]))}shouldColumnSelect(w){return w.altKey&&!(h.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(w){if(w.stopImmediatePropagation(),!this._model.selectionStart)return;const E=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(w),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.sele Line truncated
`,p.VT="\v",p.FF="\f",p.CR="\r",p.SO="",p.SI="",p.DLE="",p.DC1="",p.DC2="",p.DC3="",p.DC4="",p.NAK="",p.SYN="",p.ETB="",p.CAN="",p.EM="",p.SUB="",p.ESC="\x1B",p.FS="",p.GS="",p.RS="",p.US="",p.SP=" ",p.DEL=""}(a||(n.C0=a={})),function(p){p.PAD="€",p.HOP="",p.BPH="‚",p.NBH="ƒ",p.IND="„",p.NEL="…",p.SSA="†",p.ESA="‡",p.HTS="ˆ",p.HTJ="‰",p.VTS="Š",p.PLD="‹",p.PLU="Œ",p.RI="",p.SS2="Ž",p.SS3="",p.DCS="",p.PU1="‘",p.PU2="’",p.STS="“",p.CCH="”",p.MW="•",p.SPA="–",p.EPA="—",p.SOS="˜",p.SGCI="™",p.SCI="š",p.CSI="›",p.ST="œ",p.OSC="",p.PM="ž",p.APC="Ÿ"}(f||(n.C1=f={})),function(p){p.ST=`${a.ESC}\\`}(m||(n.C1_ESCAPED=m={}))},7399:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.evaluateKeyboardEvent=void 0;const f=a(2584),m={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};n.evaluateKeyboardEvent=function(p,_,S,b){const y={type:0,cancel:!1,key:void 0},u=(p.shiftKey?1:0)|(p.altKey?2:0)|(p.ctrlKey?4:0)|(p.metaKey?8:0);switch(p.keyCode){case 0:p.key==="UIKeyInputUpArrow"?y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A":p.key==="UIKeyInputLeftArrow"?y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D":p.key==="UIKeyInputRightArrow"?y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C":p.key==="UIKeyInputDownArrow"&&(y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:if(p.altKey){y.key=f.C0.ESC+f.C0.DEL;break}y.key=f.C0.DEL;break;case 9:if(p.shiftKey){y.key=f.C0.ESC+"[Z";break}y.key=f.C0.HT,y.cancel=!0;break;case 13:y.key=p.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,y.cancel=!0;break;case 27:y.key=f.C0.ESC,p.altKey&&(y.key=f.C0.ESC+f.C0.ESC),y.cancel=!0;break;case 37:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"D",y.key===f.C0.ESC+"[1;3D"&&(y.key=f.C0.ESC+(S?"b":"[1;5D"))):y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"C",y.key===f.C0.ESC+"[1;3C"&&(y.key=f.C0.ESC+(S?"f":"[1;5C"))):y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"A",S||y.key!==f.C0.ESC+"[1;3A"||(y.key=f.C0.ESC+"[1;5A")):y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"B",S||y.key!==f.C0.ESC+"[1;3B"||(y.key=f.C0.ESC+"[1;5B")):y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:p.shiftKey||p.ctrlKey||(y.key=f.C0.ESC+"[2~");break;case 46:y.key=u?f.C0.ESC+"[3;"+(u+1)+"~":f.C0.ESC+"[3~";break;case 36:y.key=u?f.C0.ESC+"[1;"+(u+1)+"H":_?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:y.key=u?f.C0.ESC+"[1;"+(u+1)+"F":_?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:p.shiftKey?y.type=2:p.ctrlKey?y.key=f.C0.ESC+"[5;"+(u+1)+"~":y.key=f.C0.ESC+"[5~";break;case 34:p.shiftKey?y.type=3:p.ctrlKey?y.key=f.C0.ESC+"[6;"+(u+1)+"~":y.key=f.C0.ESC+"[6~";break;case 112:y.key=u?f.C0.ESC+"[1;"+(u+1)+"P":f.C0.ESC+"OP";break;case 113:y.key=u?f.C0.ESC+"[1;"+(u+1)+"Q":f.C0.ESC+"OQ";break;case 114:y.key=u?f.C0.ESC+"[1;"+(u+1)+"R":f.C0.ESC+"OR";break;case 115:y.key=u?f.C0.ESC+"[1;"+(u+1)+"S":f.C0.ESC+"OS";break;case 116:y.key=u?f.C0.ESC+"[15;"+(u+1)+"~":f.C0.ESC+"[15~";break;case 117:y.key=u?f.C0.ESC+"[17;"+(u+1)+"~":f.C0.ESC+"[17~";break;case 118:y.key=u?f.C0.ESC+"[18;"+(u+1)+"~":f.C0.ESC+"[18~";break;case 119:y.key=u?f.C0.ESC+"[19;"+(u+1)+"~":f.C0.ESC+"[19~";break;case 120:y.key=u?f.C0.ESC+"[20;"+(u+1)+"~":f.C0.ESC+"[20~";break;case 121:y.key=u?f.C0.ESC+"[21;"+(u+1)+"~":f.C0.ESC+"[21~";break;case 122:y.key=u?f.C0.ESC+"[23;"+(u+1)+"~":f.C0.ESC+"[23~";break;case 123:y.key=u?f.C0.ESC+"[24;"+(u+1)+"~":f.C0.ESC+"[24~";break;default:if(!p.ctrlKey||p.shiftKey||p.altKey||p.metaKey)if(S&&!b||!p.altKey||p.metaKey)!S||p.altKey||p.ctrlKey||p.shiftKey||!p.metaKey?p.key&&!p.ctrlKey&&!p.altKey&&!p.metaKey&&p.keyCode>=48&&p.key.length===1?y.key=p.key:p.key&&p.ctrlKey&&(p.key==="_"&&(y.key=f.C0.US),p.key==="@"&&(y.key=f.C0.NUL)):p.keyCode===65&&(y.type=1);else{const h=m[p.keyCode],l=h==null?void 0:h[p.shiftKey?1:0];if(l)y.key=f.C0.ESC+l;else if(p.keyCode>=65&&p.keyCode<=90){const d=p.ctrlKey?p.keyCode-64:p.keyCode+32;let g=String.fromCharCode(d);p.shiftKey&&(g=g.toUpperCase()),y.key=f.C0.ESC+g}else if(p.keyCode===32)y.key=f.C0.ESC+(p.ctrlKey?f.C0.NUL:" ");else if(p.key==="Dead"&&p.code.startsWith("Key")){let d=p.code.slice(3,4);p.shiftKey||(d=d.toLowerCase()),y.key=f.C0.ESC+d,y.cancel=!0}}else p.keyCode>=65&&p.keyCode<=90?y.key=String.fromCharCode(p.keyCode-64):p.keyCode===32?y.key=f.C0.NUL:p.keyCode>=51&&p.keyCode<=55?y.key=String.fromCharCode(p.keyCode-51+27):p.keyCode===56?y.key=f.C0.DEL:p.keyCode===219?y.key=f.C0.ESC:p.keyCode===220?y.key=f.C0.FS:p.keyCode===221&&(y.key=f.C0.GS)}return y}},482:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=n.utf32ToString=n.stringFromCodePoint=void 0,n.stringFromCodePoint=function(a){return a>65535?(a-=65536,String.fromCharCode(55296+(a>>10Line truncated
`,l)}paste(h){this._core.paste(h)}refresh(h,l){this._verifyIntegers(h,l),this._core.refresh(h,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(h){this._addonManager.loadAddon(this,h)}static get strings(){return n}_verifyIntegers(...h){for(const l of h)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...h){for(const l of h)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}c.Terminal=y})(),o})())})(Ap);var GS=Ap.exports,Np={exports:{}};(function(e,t){(function(r,s){e.exports=s()})(self,()=>(()=>{var r={};return(()=>{var s=r;Object.defineProperty(s,"__esModule",{value:!0}),s.FitAddon=void 0,s.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const o=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(o._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,o=i._renderService.dimensions;if(o.css.cell.width===0||o.css.cell.height===0)return;const c=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),a=parseInt(n.getPropertyValue("height")),f=Math.max(0,parseInt(n.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),p=a-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),_=f-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-c;return{cols:Math.max(2,Math.floor(_/o.css.cell.width)),rows:Math.max(1,Math.floor(p/o.css.cell.height))}}}})(),r})())})(Np);var JS=Np.exports;const zt=Object.create(null);zt.open="0";zt.close="1";zt.ping="2";zt.pong="3";zt.message="4";zt.upgrade="5";zt.noop="6";const wn=Object.create(null);Object.keys(zt).forEach(e=>{wn[zt[e]]=e});const xl={type:"error",data:"parser error"},Pp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Bp=typeof ArrayBuffer=="function",jp=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Nc=({type:e,data:t},r,s)=>Pp&&t instanceof Blob?r?s(t):wh(t,s):Bp&&(t instanceof ArrayBuffer||jp(t))?r?s(t):wh(new Blob([t]),s):s(zt[e]+(t||"")),wh=(e,t)=>{const r=new FileReader;return r.onload=function(){const s=r.result.split(",")[1];t("b"+(s||""))},r.readAsDataURL(e)};function Ch(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ca;function QS(e,t){if(Pp&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ch).then(t);if(Bp&&(e.data instanceof ArrayBuffer||jp(e.data)))return t(Ch(e.data));Nc(e,!1,r=>{ca||(ca=new TextEncoder),t(ca.encode(r))})}const Eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",qs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Eh.length;e++)qs[Eh.charCodeAt(e)]=e;const YS=e=>{let t=e.length*.75,r=e.length,s,i=0,o,c,n,a;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(s=0;s<r;s+=4)o=qs[e.charCodeAt(s)],c=qs[e.charCodeAt(s+1)],n=qs[e.charCodeAt(s+2)],a=qs[e.charCodeAt(s+3)],m[i++]=o<<2|c>>4,m[i++]=(c&15)<<4|n>>2,m[i++]=(n&3)<<6|a&63;return f},ZS=typeof ArrayBuffer=="function",Pc=(e,t)=>{if(typeof e!="string")return{type:"message",data:Mp(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:ex(e.substring(1),t)}:wn[r]?e.length>1?{type:wn[r],data:e.substring(1)}:{type:wn[r]}:xl},ex=(e,t)=>{if(ZS){const r=YS(e);return Mp(r,t)}else return{base64:!0,data:e}},Mp=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Ip="",tx=(e,t)=>{const r=e.length,s=new Array(r);let i=0;e.forEach((o,c)=>{Nc(o,!1,n=>{s[c]=n,++i===r&&t(s.join(Ip))})})},rx=(e,t)=>{const r=e.split(Ip),s=[];for(let i=0;i<r.length;i++){const o=Pc(r[i],t);if(s.push(o),o.type==="error")break}return s};function sx(){return new TransformStream({transform(e,t){QS(e,r=>{const s=r.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,s)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let ua;function on(e){return e.reduce((t,r)=>t+r.length,0)}function an(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)r[i]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),r}function ix(e,t){ua||(ua=new TextDecoder);const Line truncated
Connected to remote shell.`):i.writeln(`\r
Failed to create shell: ${a.error||"Unknown error"}`)}),c.on("shell_output",a=>{a.data&&i.write(a.data)}),c.on("disconnect",()=>{i.writeln(`\r
[Disconnected]`)}),i.onData(a=>{c.emit("shell_input",{data:a})});const n=()=>{o.fit()};return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n),c.emit("shell_disconnect"),c.disconnect(),i.dispose()}},[]),v.jsxs("div",{className:"h-[calc(100vh-140px)] flex flex-col",children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-4",children:"Remote Shell"}),v.jsx("div",{ref:e,className:"flex-1 bg-[#1a1a1a] rounded-lg border border-border overflow-hidden"})]})}function Vx(){const[e,t]=M.useState("/"),[r,s]=M.useState([]),[i,o]=M.useState(!1),[c,n]=M.useState(null),{dispatch:a}=Fe(),f=async _=>{var S,b;o(!0);try{const y=await ne.post("/files/list",{path:_});y.data.success?(s(y.data.data),t(_)):a({type:"ADD_TOAST",payload:{message:y.data.error||"Failed",type:"error"}})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}finally{o(!1)}};M.useEffect(()=>{f("/")},[]);const m=async _=>{var S,b;try{const y=await ne.get(`/files/view?path=${encodeURIComponent(_)}`);y.data.success&&n({path:_,content:y.data.data})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}},p=e.split("/").filter(Boolean);return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"File Browser"}),v.jsxs("div",{className:"flex items-center gap-2 mb-4 text-sm",children:[v.jsx("button",{onClick:()=>f("/"),className:"text-primary hover:underline",children:"/"}),p.map((_,S)=>{const b="/"+p.slice(0,S+1).join("/");return v.jsxs("span",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-text-muted",children:"/"}),v.jsx("button",{onClick:()=>f(b),className:"text-primary hover:underline",children:_})]},S)})]}),v.jsx("div",{className:"bg-card-bg border border-border rounded-lg overflow-hidden",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Size"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Modified"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Actions"})]})}),v.jsxs("tbody",{children:[e!=="/"&&v.jsxs("tr",{className:"border-b border-border hover:bg-hover/50 cursor-pointer",onClick:()=>{const _=e.substring(0,e.lastIndexOf("/"))||"/";f(_)},children:[v.jsx("td",{className:"px-4 py-3 text-text-primary",children:".."}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"})]}),i?v.jsx("tr",{children:v.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-text-muted",children:"Loading..."})}):r.map(_=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50 cursor-pointer",onClick:()=>_.is_dir&&f(_.path),children:[v.jsxs("td",{className:"px-4 py-3 text-text-primary",children:[_.is_dir?"📁":"📄"," ",_.name]}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:_.is_dir?"-":qx(_.size)}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:new Date(_.mod_time).toLocaleString()}),v.jsx("td",{className:"px-4 py-3",children:!_.is_dir&&v.jsx("button",{onClick:S=>{S.stopPropagation(),m(_.path)},className:"text-xs text-primary hover:underline",children:"View"})})]},_.path))]})]})}),c&&v.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4 max-w-4xl max-h-[80vh] flex flex-col",children:[v.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border",children:[v.jsx("h3",{className:"font-serif text-lg text-text-primary truncate",children:c.path}),v.jsx("button",{onClick:()=>n(null),className:"text-text-muted hover:text-text-primary text-xl leading-none",children:"×"})]}),v.jsx("pre",{className:"p-5 overflow-auto flex-1 text-xs font-mono text-text-secondary bg-code-bg",children:c.content})]})})]})}function qx(e){if(e===0)return"0 B";const t=1024,r=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+r[s]}const Kx=e=>ne.get(e).then(t=>t.data);function Xx(){const[e,t]=M.useState("battlegroup"),{dispatch:r}=Fe(),{data:s}=ct("/director/battlegroup",Kx,{refreshInterval:15e3}),i=async(o,c)=>{var n,a;try{const f=await ne.post(o,c);f.data.success?r({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):r({type:"ADD_TOAST",payload:{message:f.data.error||"Failed",type:"error"}})}catch(f){r({type:"ADD_TOAST",pa Line truncated
+32
View File
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/.xterm{cursor:text;position:relative;-moz-user-select:none;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility,.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:double underline;text-decoration:double underline}.xterm-underline-3{-webkit-text-decoration:wavy underline;text-decoration:wavy underline}.xterm-underline-4{-webkit-text-decoration:dotted underline;text-decoration:dotted underline}.xterm-underline-5{-webkit-text-decoration:dashed underline;text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}[data-theme=default]{--primary: #c9a24e;--primary-dark: #a8862e;--primary-light: #e0c97a;--bg: #f4f1ea;--card-bg: #ffffff;--text: #2c1810;--text-light: #6b5a4a;--text-muted: #9a8a7a;--border: #e0d5c7;--accent: #8b4513;--danger: #c0392b;--success: #27ae60;--nav-bg: #1a1a2e;--nav-text: #c9c4d0;--nav-active: #c9a24e;--hover: #f0ebe0;--shadow: 0 2px 8px rgba(44,24,16,.08)}[data-theme=atreides]{--primary: #2d5a27;--primary-dark: #1e3d19;--primary-light: #4a8c42;--bg: #f0f5ed;--card-bg: #ffffff;--text: #1a2e1a;--text-light: #3d4d3d;--text-muted: #6b7c6b;--border: #d4ddd4;--accent: #1e3d19;--danger: #8b2500;--success: #2d5a27;--nav-bg: #1a2e1a;--nav-text: #d4ddd4;--nav-active: #6abf6a;--hover: #e2ebe2;--shadow: 0 2px 8px rgba(30,61,25,.1)}[data-theme=harkonnen]{--primary: #ff6b00;--primary-dark: #cc5500;--primary-light: #ff8c33;--bg: #1a1a1a;--card-bg: #2d2d2d;--text: #e8e8e8;--text-light: #b0b0b0;--text-muted: #808080;--border: #404040;--accent: #ff4500;--danger: #ff0000;--success: #00cc44;--nav-bg: #000000;--nav-text: #cccccc;--nav-active: #ff6b00;--hover: #333333;--shadow: 0 2px 8px rgba(0,0,0,.4)}[data-theme=fremen]{--primary: #d4a853;--primary-dark: #b8913f;--primary-light: #e8c87a;--bg: #e8dcc8;--card-bg: #f5efe3;--text: #3d3428;--text-light: #5c4f3d;--text-muted: #8a7d66;--border: #d4cbb8;--accent: #8b6914;--danger: #a04000;--success: #6b8e23;--nav-bg: #2c2418;--nav-text: #d4cbb8;--nav-active: #d4a853;--hover: #e8dcc8;--shadow: 0 2px 8px rgba(44,36,24,.1)}[data-theme=bene-gesserit]{--primary: #a8a8a8;--primary-dark: #888888;--primary-light: #c8c8c8;--bg: #f8f8f8;--card-bg: #ffffff;--text: #2a2a2a;--text-light: #505050;--text-muted: #787878;--border: #e0e0e0;--accent: #606060;--danger: #c41e3a;--success: #2e8b57;--nav-bg: #1a1a1a;--nav-text: #d0d0d0;--nav-active: #ffffff;--hover: #f0f0f0;--shadow: 0 2px 8px rgba(0,0,0,.08)}[data-theme=spacing-guild]{--primary: #4a90d9;--primary-dark: #2e6ab3;--primary-light: #6baee8;--bg: #1a1a2e;--card-bg: #252540;--text: #e0e0f0;--text-light: #a0a0c0;--text-muted: #707090;--border: #3a3a50;--accent: #6b5b95;--danger: #d94545;--success: #45d985;--nav-bg: #0f0f1a;--nav-text: #b0b0d0;--nav-active: #4a90d9;--hover: #2a2a40;--shadow: 0 2px 8px rgba(0,0,0,Line truncated
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en" data-theme="emperor">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dune Admin Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<script type="module" crossorigin src="/assets/index-9_PploUA.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BwISaj0y.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en" data-theme="emperor">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dune Admin Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+31
View File
@@ -0,0 +1,31 @@
{
"name": "dune-dashboard-frontend",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0",
"axios": "^1.6.7",
"swr": "^2.2.4",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0",
"socket.io-client": "^4.7.4"
},
"devDependencies": {
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.17",
"postcss": "^8.4.35",
"tailwindcss": "^3.4.1",
"typescript": "^5.3.3",
"vite": "^5.1.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+39
View File
@@ -0,0 +1,39 @@
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AppProvider } from './stores/AppContext'
import { useRealtime } from './hooks/useRealtime'
import AppShell from './components/layout/AppShell'
import Overview from './components/overview/Overview'
import PlayerExplorer from './components/players/PlayerExplorer'
import GuildManager from './components/guilds/GuildManager'
import ServerControl from './components/server/ServerControl'
import AdminTools from './components/admin/AdminTools'
import ChatMonitor from './components/chat/ChatMonitor'
import Terminal from './components/shell/Terminal'
function RealtimeInit() {
useRealtime()
return null
}
function App() {
return (
<AppProvider>
<BrowserRouter>
<RealtimeInit />
<AppShell>
<Routes>
<Route path="/" element={<Overview />} />
<Route path="/players" element={<PlayerExplorer />} />
<Route path="/guilds" element={<GuildManager />} />
<Route path="/server" element={<ServerControl />} />
<Route path="/admin" element={<AdminTools />} />
<Route path="/chat" element={<ChatMonitor />} />
<Route path="/shell" element={<Terminal />} />
</Routes>
</AppShell>
</BrowserRouter>
</AppProvider>
)
}
export default App
+21
View File
@@ -0,0 +1,21 @@
import axios from 'axios'
const client = axios.create({
baseURL: '/api',
headers: {
'Content-Type': 'application/json',
},
timeout: 30000,
})
client.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export default client
@@ -0,0 +1,419 @@
import { useState } from 'react'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
const SCOPE_OPTIONS = ['all', 'server', 'partition']
const SERVER_OPTIONS = ['na', 'eu', 'sea', 'sa', 'oc']
const PARTITION_OPTIONS = ['parrish', 'sietch', 'bazar']
export default function AdminTools() {
const [tab, setTab] = useState<'broadcast' | 'economy' | 'world' | 'character' | 'functions' | 'raw' | 'audit'>('broadcast')
const { dispatch } = useApp()
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Admin Tools</h1>
<div className="flex gap-1 mb-6 border-b border-border overflow-x-auto no-scrollbar">
{([
{ key: 'broadcast', label: 'Broadcast' },
{ key: 'economy', label: 'Economy' },
{ key: 'world', label: 'World' },
{ key: 'character', label: 'Character' },
{ key: 'functions', label: 'Functions' },
{ key: 'raw', label: 'Raw Query' },
{ key: 'audit', label: 'Audit Log' },
] as const).map((t) => (
<button
key={t.key}
onClick={() => setTab(t.key as any)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
tab === t.key
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
>
{t.label}
</button>
))}
</div>
{tab === 'broadcast' && <BroadcastTab dispatch={dispatch} />}
{tab === 'economy' && <EconomyTab dispatch={dispatch} />}
{tab === 'world' && <WorldTab dispatch={dispatch} />}
{tab === 'character' && <CharacterTab dispatch={dispatch} />}
{tab === 'functions' && <FunctionsTab dispatch={dispatch} />}
{tab === 'raw' && <RawQueryTab dispatch={dispatch} />}
{tab === 'audit' && <AuditLogTab dispatch={dispatch} />}
</div>
)
}
function BroadcastTab({ dispatch }: { dispatch: any }) {
const [message, setMessage] = useState('')
const [scope, setScope] = useState('all')
const [server, setServer] = useState('na')
const [partition, setPartition] = useState('parrish')
const [sending, setSending] = useState(false)
const handleSend = async () => {
if (!message.trim()) return
setSending(true)
try {
const payload: any = { message: message.trim() }
if (scope === 'server') payload.server = server
if (scope === 'partition') {
payload.server = server
payload.partition = partition
}
const res = await client.post('/broadcast', payload)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Broadcast sent', type: 'success' } })
setMessage('')
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
} finally {
setSending(false)
}
}
return (
<div className="max-w-xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div>
<label className="block text-sm text-text-muted mb-2">Scope</label>
<div className="flex gap-2">
{SCOPE_OPTIONS.map((s) => (
<button
key={s}
onClick={() => setScope(s)}
className={`px-3 py-1.5 rounded text-xs font-medium border capitalize ${
scope === s
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
>
{s}
</button>
))}
</div>
</div>
{scope !== 'all' && (
<div>
<label className="block text-sm text-text-muted mb-2">Server</label>
<select value={server} onChange={(e) => setServer(e.target.value)} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{SERVER_OPTIONS.map((s) => <option key={s} value={s}>{s.toUpperCase()}</option>)}
</select>
</div>
)}
{scope === 'partition' && (
<div>
<label className="block text-sm text-text-muted mb-2">Partition</label>
<select value={partition} onChange={(e) => setPartition(e.target.value)} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{PARTITION_OPTIONS.map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</div>
)}
<div>
<label className="block text-sm text-text-muted mb-2">Message</label>
<textarea value={message} onChange={(e) => setMessage(e.target.value)} rows={4} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" placeholder="Enter broadcast message..." />
</div>
<button onClick={handleSend} disabled={sending || !message.trim()} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{sending ? 'Sending...' : 'Send Broadcast'}
</button>
</div>
</div>
)
}
function EconomyTab({ dispatch }: { dispatch: any }) {
const [playerId, setPlayerId] = useState('')
const [itemForm, setItemForm] = useState({ template_id: '', stack_size: '1', quality: '0', inventory_id: '' })
const [editForm, setEditForm] = useState({ item_id: '', field: 'stack_size', value: '' })
const post = async (endpoint: string, payload: any) => {
try {
const res = await client.post(endpoint, payload)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Add Item</h3>
<input value={playerId} onChange={(e) => setPlayerId(e.target.value)} placeholder="Player ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.template_id} onChange={(e) => setItemForm({ ...itemForm, template_id: e.target.value })} placeholder="Template ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.stack_size} onChange={(e) => setItemForm({ ...itemForm, stack_size: e.target.value })} placeholder="Stack Size" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.quality} onChange={(e) => setItemForm({ ...itemForm, quality: e.target.value })} placeholder="Quality" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.inventory_id} onChange={(e) => setItemForm({ ...itemForm, inventory_id: e.target.value })} placeholder="Inventory ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<button onClick={() => post('/items/add', { player_id: parseInt(playerId), template_id: itemForm.template_id, stack_size: parseInt(itemForm.stack_size), quality_level: parseInt(itemForm.quality), inventory_id: parseInt(itemForm.inventory_id) || undefined })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Add Item</button>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Edit Item</h3>
<input value={editForm.item_id} onChange={(e) => setEditForm({ ...editForm, item_id: e.target.value })} placeholder="Item ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<select value={editForm.field} onChange={(e) => setEditForm({ ...editForm, field: e.target.value })} className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm">
{['stack_size', 'quality_level', 'durability', 'ammo'].map((f) => <option key={f} value={f}>{f}</option>)}
</select>
<input value={editForm.value} onChange={(e) => setEditForm({ ...editForm, value: e.target.value })} placeholder="New value" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<div className="flex gap-2">
<button onClick={() => post(`/items/${editForm.item_id}`, { [editForm.field]: editForm.value })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Update</button>
<button onClick={() => post(`/items/${editForm.item_id}`, {})} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete</button>
</div>
</div>
</div>
)
}
function WorldTab({ dispatch }: { dispatch: any }) {
const [tpForm, setTpForm] = useState({ fls_id: '', partition: '', x: '', y: '', z: '' })
const post = async (endpoint: string, payload: any) => {
try {
const res = await client.post(endpoint, payload)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Teleport Player</h3>
<input value={tpForm.fls_id} onChange={(e) => setTpForm({ ...tpForm, fls_id: e.target.value })} placeholder="FLS ID / Account ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={tpForm.partition} onChange={(e) => setTpForm({ ...tpForm, partition: e.target.value })} placeholder="Partition ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<div className="grid grid-cols-3 gap-2">
<input type="number" value={tpForm.x} onChange={(e) => setTpForm({ ...tpForm, x: e.target.value })} placeholder="X" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input type="number" value={tpForm.y} onChange={(e) => setTpForm({ ...tpForm, y: e.target.value })} placeholder="Y" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input type="number" value={tpForm.z} onChange={(e) => setTpForm({ ...tpForm, z: e.target.value })} placeholder="Z" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
</div>
<button onClick={() => post('/teleport', { fls_id: parseInt(tpForm.fls_id), partition_id: tpForm.partition, x: parseFloat(tpForm.x) || 0, y: parseFloat(tpForm.y) || 0, z: parseFloat(tpForm.z) || 0 })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Teleport</button>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Spice Control</h3>
<div className="flex gap-2">
<button onClick={() => post('/spice/reset', {})} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Reset Spice Fields</button>
<button onClick={() => post('/spice/spawn', {})} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Force Spawn</button>
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Partitions</h3>
<button onClick={() => client.get('/partitions').then((r) => dispatch({ type: 'ADD_TOAST', payload: { message: `Partitions loaded`, type: 'info' } }))} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">List Partitions</button>
</div>
</div>
)
}
function CharacterTab({ dispatch }: { dispatch: any }) {
const [charId, setCharId] = useState('')
const [newName, setNewName] = useState('')
const [demoState, setDemoState] = useState('true')
const post = async (endpoint: string, payload: any) => {
try {
const res = await client.post(endpoint, payload)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Rename Character</h3>
<input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID / Character ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="New Name" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<button onClick={() => post(`/characters/${charId}/name`, { name: newName })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Rename</button>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Demo State</h3>
<input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<select value={demoState} onChange={(e) => setDemoState(e.target.value)} className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm">
<option value="true">Demo</option>
<option value="false">Normal</option>
</select>
<button onClick={() => post(`/accounts/${charId}/demo`, { demo: demoState === 'true' })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Set Demo State</button>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Danger Zone</h3>
<div className="flex flex-wrap gap-2">
<button onClick={() => { if (confirm('Delete character?')) post(`/characters/${charId}`, {}) }} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete Character</button>
<button onClick={() => { if (confirm('Delete account?')) post(`/accounts/${charId}`, {}) }} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete Account</button>
</div>
</div>
</div>
)
}
function FunctionsTab({ dispatch }: { dispatch: any }) {
const [schema, setSchema] = useState('')
const [funcName, setFuncName] = useState('')
const [args, setArgs] = useState('{}')
const [result, setResult] = useState('')
const [running, setRunning] = useState(false)
const handleExecute = async () => {
setRunning(true)
try {
const parsedArgs = JSON.parse(args || '{}')
const res = await client.post('/functions/execute', { schema: schema || undefined, function: funcName, args: parsedArgs })
if (res.data.success) {
setResult(JSON.stringify(res.data.data, null, 2))
dispatch({ type: 'ADD_TOAST', payload: { message: 'Function executed', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.message, type: 'error' } })
} finally {
setRunning(false)
}
}
return (
<div className="max-w-2xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm text-text-muted mb-2">Schema (optional)</label>
<input value={schema} onChange={(e) => setSchema(e.target.value)} className="w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary" placeholder="e.g., public" />
</div>
<div>
<label className="block text-sm text-text-muted mb-2">Function Name</label>
<input value={funcName} onChange={(e) => setFuncName(e.target.value)} className="w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary" placeholder="e.g., get_player_stats" />
</div>
</div>
<div>
<label className="block text-sm text-text-muted mb-2">Arguments (JSON)</label>
<textarea value={args} onChange={(e) => setArgs(e.target.value)} rows={4} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" />
</div>
<button onClick={handleExecute} disabled={running || !funcName} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{running ? 'Running...' : 'Execute'}
</button>
{result && <pre className="mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary">{result}</pre>}
</div>
</div>
)
}
function RawQueryTab({ dispatch }: { dispatch: any }) {
const [query, setQuery] = useState('')
const [result, setResult] = useState('')
const [running, setRunning] = useState(false)
const handleRun = async () => {
setRunning(true)
try {
const res = await client.post('/query', { query })
if (res.data.success) {
setResult(JSON.stringify(res.data.data, null, 2))
dispatch({ type: 'ADD_TOAST', payload: { message: 'Query executed', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || e.message, type: 'error' } })
} finally {
setRunning(false)
}
}
return (
<div className="max-w-3xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div className="flex items-center justify-between">
<label className="text-sm text-text-muted">SQL Query (Read-Only SELECT)</label>
<span className="text-[10px] text-text-muted uppercase tracking-wider bg-danger/10 px-2 py-0.5 rounded border border-danger/20">Read Only</span>
</div>
<textarea value={query} onChange={(e) => setQuery(e.target.value)} rows={6} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" placeholder="SELECT * FROM public.characters LIMIT 10;" />
<button onClick={handleRun} disabled={running || !query.trim()} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{running ? 'Running...' : 'Run Query'}
</button>
{result && <pre className="mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary">{result}</pre>}
</div>
</div>
)
}
function AuditLogTab({ dispatch }: { dispatch: any }) {
const [limit, setLimit] = useState(50)
const [logs, setLogs] = useState<any[]>([])
const [loading, setLoading] = useState(false)
const load = async () => {
setLoading(true)
try {
const res = await client.get(`/audit/logs?limit=${limit}`)
if (res.data.success) setLogs(res.data.data)
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
} finally {
setLoading(false)
}
}
return (
<div>
<div className="flex items-center gap-4 mb-4">
<button onClick={load} disabled={loading} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{loading ? 'Loading...' : 'Load Logs'}
</button>
<select value={limit} onChange={(e) => setLimit(Number(e.target.value))} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{[10, 25, 50, 100, 250].map((n) => <option key={n} value={n}>{n} entries</option>)}
</select>
</div>
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Time</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Admin</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Action</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Target</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Details</th>
</tr>
</thead>
<tbody>
{logs.map((log, i) => (
<tr key={i} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 text-text-muted text-xs">{new Date(log.timestamp).toLocaleString()}</td>
<td className="px-4 py-3">{log.admin_name}</td>
<td className="px-4 py-3"><span className="px-2 py-0.5 rounded text-[11px] font-semibold bg-primary/10 text-primary border border-primary/20">{log.action}</span></td>
<td className="px-4 py-3">{log.target_type}: {log.target_id}</td>
<td className="px-4 py-3 text-xs text-text-muted max-w-md truncate">{JSON.stringify(log.details)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
@@ -0,0 +1,72 @@
import { useState } from 'react'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
import Badge from '../common/Badge'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface Building {
id: number
class_name: string
map: string
owner_name: string
is_powered: boolean
power_level: number | null
instance_count: number
}
export default function Buildings() {
const [search, setSearch] = useState('')
const { dispatch } = useApp()
const { data: buildingsData, isLoading } = useSWR(
search.length >= 2 ? `/buildings?q=${encodeURIComponent(search)}&limit=50` : '/buildings?limit=100',
fetcher,
{ refreshInterval: 30000 }
)
const buildingList: Building[] = buildingsData?.success ? buildingsData.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Buildings</h1>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search buildings..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<DataTable
columns={[
{ header: 'Class', accessor: 'class_name' },
{ header: 'Map', accessor: 'map' },
{ header: 'Owner', accessor: 'owner_name' },
{
header: 'Power',
accessor: (row) => (
<div className="flex gap-1">
{row.is_powered ? <Badge label="Powered" variant="success" /> : <Badge label="Unpowered" variant="default" />}
{row.power_level != null && <Badge label={`Lv ${row.power_level}`} variant="default" />}
</div>
),
},
{ header: 'Instances', accessor: 'instance_count' },
]}
data={buildingList}
loading={isLoading}
/>
</div>
)
}
@@ -0,0 +1,88 @@
import { useState, useEffect, useRef } from 'react'
import client from '../../api/client'
interface ChatMessage {
id: string
channel: string
sender: string
message: string
timestamp: string
}
const CHANNELS = ['Global', 'Guild', 'System', 'Combat']
export default function ChatMonitor() {
const [channel, setChannel] = useState('Global')
const [messages, setMessages] = useState<ChatMessage[]>([])
const bottomRef = useRef<HTMLDivElement>(null)
useEffect(() => {
async function load() {
try {
const res = await client.get(`/chat/history?channel=${channel}&limit=100`)
if (res.data.success) {
setMessages(res.data.data)
}
} catch (e) {
console.error(e)
}
}
load()
}, [channel])
useEffect(() => {
const es = new EventSource('/api/events/stream')
es.addEventListener('chat_message', (e) => {
try {
const msg: ChatMessage = JSON.parse(e.data)
if (msg.channel === channel || channel === 'Global') {
setMessages((prev) => [...prev.slice(-199), msg])
}
} catch {}
})
return () => es.close()
}, [channel])
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages])
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<div className="flex items-center justify-between mb-4">
<h1 className="font-serif text-3xl text-primary">Chat Monitor</h1>
<div className="flex gap-2">
{CHANNELS.map((c) => (
<button
key={c}
onClick={() => setChannel(c)}
className={`px-3 py-1.5 rounded text-xs font-medium border ${
channel === c
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
>
{c}
</button>
))}
</div>
</div>
<div className="flex-1 bg-card-bg border border-border rounded-lg overflow-hidden flex flex-col">
<div className="flex-1 overflow-y-auto p-4 space-y-2 font-mono text-sm">
{messages.map((msg) => (
<div key={msg.id} className="flex gap-3">
<span className="text-text-muted text-xs whitespace-nowrap">
{new Date(msg.timestamp).toLocaleTimeString()}
</span>
<span className="text-primary font-semibold whitespace-nowrap">[{msg.channel}]</span>
<span className="text-accent font-semibold whitespace-nowrap">{msg.sender}:</span>
<span className="text-text-secondary break-all">{msg.message}</span>
</div>
))}
<div ref={bottomRef} />
</div>
</div>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
interface BadgeProps {
label: string
variant?: 'default' | 'success' | 'warning' | 'danger'
}
export default function Badge({ label, variant = 'default' }: BadgeProps) {
const classes: Record<string, string> = {
default: 'bg-primary/10 text-primary border-primary/20',
success: 'bg-success/10 text-success border-success/20',
warning: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20',
danger: 'bg-danger/10 text-danger border-danger/20',
}
return (
<span
className={`inline-block px-2 py-0.5 rounded text-[11px] font-semibold border uppercase tracking-wide ${classes[variant]}`}
>
{label}
</span>
)
}
@@ -0,0 +1,117 @@
import { ReactNode, useState } from 'react'
interface Column<T> {
header: string
accessor: keyof T | ((row: T) => ReactNode)
width?: string
}
interface DataTableProps<T> {
columns: Column<T>[]
data: T[]
onRowClick?: (row: T) => void
loading?: boolean
}
export default function DataTable<T extends object>({
columns,
data,
onRowClick,
loading,
}: DataTableProps<T>) {
const [sortCol, setSortCol] = useState<string | null>(null)
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc')
const handleSort = (header: string) => {
if (sortCol === header) {
setSortDir(sortDir === 'asc' ? 'desc' : 'asc')
} else {
setSortCol(header)
setSortDir('asc')
}
}
let sorted = [...data]
if (sortCol) {
const col = columns.find((c) => c.header === sortCol)
if (col && typeof col.accessor === 'string') {
sorted.sort((a: any, b: any) => {
const av = a[col.accessor]
const bv = b[col.accessor]
if (av == null && bv == null) return 0
if (av == null) return sortDir === 'asc' ? 1 : -1
if (bv == null) return sortDir === 'asc' ? -1 : 1
if (typeof av === 'string') {
return sortDir === 'asc'
? av.localeCompare(bv)
: bv.localeCompare(av)
}
if (typeof av === 'number') {
return sortDir === 'asc' ? av - bv : bv - av
}
return 0
})
}
}
return (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
{columns.map((col) => (
<th
key={col.header}
className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase tracking-wider cursor-pointer hover:text-text-primary select-none"
style={{ width: col.width }}
onClick={() => handleSort(col.header)}
>
<div className="flex items-center gap-1">
{col.header}
{sortCol === col.header && (
<span className="text-primary">
{sortDir === 'asc' ? ' ▲' : ' ▼'}
</span>
)}
</div>
</th>
))}
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={columns.length} className="px-4 py-8 text-center text-text-muted">
Loading...
</td>
</tr>
) : sorted.length === 0 ? (
<tr>
<td colSpan={columns.length} className="px-4 py-8 text-center text-text-muted">
No results found
</td>
</tr>
) : (
sorted.map((row, i) => (
<tr
key={i}
onClick={() => onRowClick?.(row)}
className={`border-b border-border last:border-0 transition-colors ${
onRowClick ? 'cursor-pointer hover:bg-hover' : 'hover:bg-hover/50'
}`}
>
{columns.map((col) => (
<td key={col.header} className="px-4 py-3 whitespace-nowrap">
{typeof col.accessor === 'function'
? col.accessor(row)
: String(row[col.accessor] ?? '')}
</td>
))}
</tr>
))
)}
</tbody>
</table>
</div>
)
}
+30
View File
@@ -0,0 +1,30 @@
interface ModalProps {
open: boolean
title: string
onClose: () => void
children: React.ReactNode
maxWidth?: string
}
export default function Modal({ open, title, onClose, children, maxWidth = '500px' }: ModalProps) {
if (!open) return null
return (
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div
className="bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4"
style={{ maxWidth }}
>
<div className="flex items-center justify-between px-5 py-4 border-b border-border">
<h3 className="font-serif text-lg text-text-primary">{title}</h3>
<button
onClick={onClose}
className="text-text-muted hover:text-text-primary text-xl leading-none"
>
&times;
</button>
</div>
<div className="p-5 max-h-[80vh] overflow-auto">{children}</div>
</div>
</div>
)
}
@@ -0,0 +1,39 @@
import { useEffect } from 'react'
import { useApp } from '../../stores/AppContext'
export default function ToastProvider() {
const { state, dispatch } = useApp()
useEffect(() => {
if (state.toasts.length === 0) return
const timers = state.toasts.map((t) =>
setTimeout(() => {
dispatch({ type: 'REMOVE_TOAST', payload: t.id })
}, 4000)
)
return () => timers.forEach(clearTimeout)
}, [state.toasts, dispatch])
if (state.toasts.length === 0) return null
return (
<div className="fixed top-16 right-6 z-[100] flex flex-col gap-2">
{state.toasts.map((t) => (
<div
key={t.id}
className={`px-4 py-3 rounded-lg shadow-lg text-sm font-medium min-w-[240px] max-w-md border ${
t.type === 'success'
? 'bg-success/10 border-success/30 text-success'
: t.type === 'error'
? 'bg-danger/10 border-danger/30 text-danger'
: t.type === 'warning'
? 'bg-yellow-500/10 border-yellow-500/30 text-yellow-400'
: 'bg-primary/10 border-primary/30 text-primary'
}`}
>
{t.message}
</div>
))}
</div>
)
}
@@ -0,0 +1,165 @@
import { useState, useEffect } from 'react'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
interface FileEntry {
name: string
path: string
size: number
is_dir: boolean
mod_time: string
}
export default function FileBrowser() {
const [path, setPath] = useState('/')
const [files, setFiles] = useState<FileEntry[]>([])
const [loading, setLoading] = useState(false)
const [viewFile, setViewFile] = useState<{ path: string; content: string } | null>(null)
const { dispatch } = useApp()
const load = async (targetPath: string) => {
setLoading(true)
try {
const res = await client.post('/files/list', { path: targetPath })
if (res.data.success) {
setFiles(res.data.data)
setPath(targetPath)
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
} finally {
setLoading(false)
}
}
useEffect(() => {
load('/')
}, [])
const view = async (filePath: string) => {
try {
const res = await client.get(`/files/view?path=${encodeURIComponent(filePath)}`)
if (res.data.success) {
setViewFile({ path: filePath, content: res.data.data })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
const breadcrumbs = path.split('/').filter(Boolean)
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">File Browser</h1>
<div className="flex items-center gap-2 mb-4 text-sm">
<button
onClick={() => load('/')}
className="text-primary hover:underline"
>
/
</button>
{breadcrumbs.map((crumb, i) => {
const crumbPath = '/' + breadcrumbs.slice(0, i + 1).join('/')
return (
<span key={i} className="flex items-center gap-2">
<span className="text-text-muted">/</span>
<button
onClick={() => load(crumbPath)}
className="text-primary hover:underline"
>
{crumb}
</button>
</span>
)
})}
</div>
<div className="bg-card-bg border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Size</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Modified</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{path !== '/' && (
<tr
className="border-b border-border hover:bg-hover/50 cursor-pointer"
onClick={() => {
const parent = path.substring(0, path.lastIndexOf('/')) || '/'
load(parent)
}}
>
<td className="px-4 py-3 text-text-primary">..</td>
<td className="px-4 py-3">-</td>
<td className="px-4 py-3">-</td>
<td className="px-4 py-3">-</td>
</tr>
)}
{loading ? (
<tr><td colSpan={4} className="px-4 py-8 text-center text-text-muted">Loading...</td></tr>
) : (
files.map((f) => (
<tr
key={f.path}
className="border-b border-border last:border-0 hover:bg-hover/50 cursor-pointer"
onClick={() => f.is_dir && load(f.path)}
>
<td className="px-4 py-3 text-text-primary">
{f.is_dir ? '📁' : '📄'} {f.name}
</td>
<td className="px-4 py-3 text-text-muted">{f.is_dir ? '-' : formatBytes(f.size)}</td>
<td className="px-4 py-3 text-text-muted">{new Date(f.mod_time).toLocaleString()}</td>
<td className="px-4 py-3">
{!f.is_dir && (
<button
onClick={(e) => { e.stopPropagation(); view(f.path) }}
className="text-xs text-primary hover:underline"
>
View
</button>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{viewFile && (
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4 max-w-4xl max-h-[80vh] flex flex-col">
<div className="flex items-center justify-between px-5 py-4 border-b border-border">
<h3 className="font-serif text-lg text-text-primary truncate">{viewFile.path}</h3>
<button
onClick={() => setViewFile(null)}
className="text-text-muted hover:text-text-primary text-xl leading-none"
>
&times;
</button>
</div>
<pre className="p-5 overflow-auto flex-1 text-xs font-mono text-text-secondary bg-code-bg">
{viewFile.content}
</pre>
</div>
</div>
)}
</div>
)
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
@@ -0,0 +1,172 @@
import { useState } from 'react'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
import Modal from '../common/Modal'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface Guild {
guild_id: number
guild_name: string
guild_description: string | null
faction_name: string | null
member_count: number
online_count: number
}
interface GuildMember {
player_id: number
role_id: number
role_name: string
player_name: string
online_status: string
}
export default function GuildManager() {
const [search, setSearch] = useState('')
const [selected, setSelected] = useState<Guild | null>(null)
const [detail, setDetail] = useState<any>(null)
const { dispatch } = useApp()
const { data: guilds, isLoading } = useSWR(
search.length >= 2 ? `/guilds?q=${encodeURIComponent(search)}&limit=25` : null,
fetcher,
{ refreshInterval: 30000 }
)
const loadDetail = async (guildId: number) => {
try {
const res = await client.get(`/guilds/${guildId}`)
if (res.data.success) setDetail(res.data.data)
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
const handleDisband = async () => {
try {
const res = await client.delete(`/guilds/${selected!.guild_id}`)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Guild disbanded', type: 'success' } })
setSelected(null)
setDetail(null)
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
const handleMemberAction = async (action: string, playerId: number, roleId?: number) => {
try {
let res
if (action === 'remove') {
res = await client.delete(`/guilds/${selected!.guild_id}/members/${playerId}`)
} else {
res = await client.put(`/guilds/${selected!.guild_id}/members/${playerId}/role`, { action, role_id: roleId })
}
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Member updated', type: 'success' } })
loadDetail(selected!.guild_id)
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
const guildList: Guild[] = guilds?.success ? guilds.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Guild Manager</h1>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search guilds..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<DataTable
columns={[
{ header: 'Name', accessor: 'guild_name' },
{ header: 'Faction', accessor: 'faction_name' },
{ header: 'Members', accessor: 'member_count' },
{ header: 'Online', accessor: 'online_count' },
]}
data={guildList}
onRowClick={(row) => { setSelected(row); loadDetail(row.guild_id) }}
loading={isLoading}
/>
<Modal open={!!selected} title={selected?.guild_name || ''} onClose={() => { setSelected(null); setDetail(null) }} maxWidth="700px">
{selected && detail && (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4 text-sm">
<InfoRow label="Guild ID" value={selected.guild_id} />
<InfoRow label="Members" value={selected.member_count} />
<InfoRow label="Faction" value={selected.faction_name || 'None'} />
<InfoRow label="Description" value={selected.guild_description || 'None'} />
</div>
<div className="border-t border-border pt-4">
<h4 className="text-text-muted text-xs uppercase tracking-wider mb-3">Members</h4>
<div className="overflow-x-auto rounded-lg border border-border max-h-64 overflow-y-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-card-bg">
<tr className="border-b border-border">
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Name</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Role</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Status</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{(detail.members || []).map((m: GuildMember) => (
<tr key={m.player_id} className="border-b border-border last:border-0">
<td className="px-3 py-2">{m.player_name}</td>
<td className="px-3 py-2"><span className="px-2 py-0.5 rounded text-[10px] bg-primary/10 text-primary border border-primary/20">{m.role_name}</span></td>
<td className="px-3 py-2 text-xs">{m.online_status}</td>
<td className="px-3 py-2 flex gap-1">
<button onClick={() => handleMemberAction('promote', m.player_id, 90)} className="text-[10px] text-primary hover:underline">Promote</button>
<button onClick={() => handleMemberAction('demote', m.player_id, 50)} className="text-[10px] text-text-muted hover:underline">Demote</button>
<button onClick={() => handleMemberAction('remove', m.player_id)} className="text-[10px] text-danger hover:underline">Remove</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<div className="flex gap-2 pt-4 border-t border-border">
<button onClick={handleDisband} className="px-3 py-1.5 rounded text-xs font-medium bg-danger/10 border border-danger/30 text-danger hover:bg-danger/20">Disband Guild</button>
</div>
</div>
)}
</Modal>
</div>
)
}
function InfoRow({ label, value }: { label: string; value: any }) {
return (
<div>
<div className="text-text-muted text-xs uppercase tracking-wider">{label}</div>
<div className="text-text-primary font-mono">{value ?? 'N/A'}</div>
</div>
)
}
@@ -0,0 +1,15 @@
import { ReactNode } from 'react'
import NavBar from './NavBar'
import ToastProvider from '../common/ToastProvider'
export default function AppShell({ children }: { children: ReactNode }) {
return (
<div className="min-h-screen bg-background text-text-primary">
<NavBar />
<main className="p-6 max-w-[1600px] mx-auto">
<ToastProvider />
{children}
</main>
</div>
)
}
@@ -0,0 +1,21 @@
import { useApp } from '../../stores/AppContext'
export default function ConnectionBadge() {
const { state } = useApp()
const { database, ssh, bgd, rmq } = state.connectionStatus
const allOk = database && ssh && bgd && rmq
const someDown = !allOk && (database || ssh || bgd || rmq)
return (
<div className="flex items-center gap-2">
<div
className="w-2.5 h-2.5 rounded-full"
style={{
backgroundColor: allOk ? '#27ae60' : someDown ? '#f39c12' : '#c0392b',
boxShadow: `0 0 6px ${allOk ? '#27ae60' : someDown ? '#f39c12' : '#c0392b'}`,
}}
title={`DB: ${database ? 'OK' : 'DOWN'} | SSH: ${ssh ? 'OK' : 'DOWN'} | BGD: ${bgd ? 'OK' : 'DOWN'} | RMQ: ${rmq ? 'OK' : 'DOWN'}`}
/>
</div>
)
}
+52
View File
@@ -0,0 +1,52 @@
import { Link, useLocation } from 'react-router-dom'
import { useApp } from '../../stores/AppContext'
import ThemeSwitcher from './ThemeSwitcher'
import ConnectionBadge from './ConnectionBadge'
const NAV_ITEMS = [
{ path: '/', label: 'Overview' },
{ path: '/players', label: 'Players' },
{ path: '/guilds', label: 'Guilds' },
{ path: '/server', label: 'Server' },
{ path: '/chat', label: 'Chat' },
{ path: '/admin', label: 'Admin' },
{ path: '/shell', label: 'Shell' },
]
export default function NavBar() {
const location = useLocation()
const { state } = useApp()
return (
<nav className="sticky top-0 z-50 h-[52px] bg-nav-bg flex items-center px-6 shadow-md border-b border-border">
<div className="flex items-center gap-2 mr-8">
<span className="text-primary font-serif font-bold text-lg tracking-wide">Dune</span>
<span className="text-nav-text text-xs uppercase tracking-widest">Admin</span>
</div>
<div className="flex items-center gap-1">
{NAV_ITEMS.map((item) => (
<Link
key={item.path}
to={item.path}
className={`px-4 h-[52px] flex items-center text-[13px] font-medium border-b-2 transition-colors ${
location.pathname === item.path
? 'text-nav-active border-nav-active'
: 'text-nav-text border-transparent hover:text-white hover:bg-white/5'
}`}
>
{item.label}
</Link>
))}
</div>
<div className="ml-auto flex items-center gap-4">
<ConnectionBadge />
<ThemeSwitcher />
{state.user && (
<span className="text-nav-text text-xs">{state.user}</span>
)}
</div>
</nav>
)
}
@@ -0,0 +1,68 @@
import { useState, useRef, useEffect } from 'react'
import { useApp } from '../../stores/AppContext'
const THEMES = [
{ key: 'default', label: 'Classic Dune' },
{ key: 'atreides', label: 'House Atreides' },
{ key: 'harkonnen', label: 'House Harkonnen' },
{ key: 'fremen', label: 'Fremen' },
{ key: 'bene-gesserit', label: 'Bene Gesserit' },
{ key: 'spacing-guild', label: 'Spacing Guild' },
{ key: 'emperor', label: 'Emperor' },
{ key: 'corrino', label: 'House Corrino' },
{ key: 'mentat', label: 'Mentat' },
{ key: 'sardaukar', label: 'Sardaukar' },
{ key: 'tleilax', label: 'Bene Tleilax' },
{ key: 'ordos', label: 'House Ordos' },
{ key: 'ix', label: 'Ix' },
{ key: 'choam', label: 'CHOAM' },
]
export default function ThemeSwitcher() {
const { state, dispatch } = useApp()
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false)
}
}
document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [])
return (
<div className="relative" ref={ref}>
<button
onClick={() => setOpen(!open)}
className="w-6 h-6 rounded-full"
style={{ background: 'linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)' }}
title="Change theme"
/>
{open && (
<div className="absolute right-0 mt-2 w-56 bg-card-bg border border-border rounded-lg shadow-xl z-50 py-2">
{THEMES.map((t) => (
<button
key={t.key}
onClick={() => {
dispatch({ type: 'SET_THEME', payload: t.key })
setOpen(false)
}}
className={`w-full text-left px-4 py-2 text-sm flex items-center gap-3 hover:bg-hover transition-colors ${
state.theme === t.key ? 'text-primary font-semibold' : 'text-text-secondary'
}`}
>
<span
className="w-4 h-4 rounded border border-border"
style={{ background: `linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)` }}
/>
{t.label}
</button>
))}
</div>
)}
</div>
)
}
+157
View File
@@ -0,0 +1,157 @@
import { useState, useEffect, useRef } from 'react'
import useSWR from 'swr'
import client from '../../api/client'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface MapMarker {
id: string
name: string
x: number
y: number
type: 'player' | 'vehicle' | 'building' | 'landclaim'
}
export default function MapViewer() {
const canvasRef = useRef<HTMLCanvasElement>(null)
const [markers, setMarkers] = useState<MapMarker[]>([])
const [filter, setFilter] = useState<string>('all')
const [selected, setSelected] = useState<MapMarker | null>(null)
const [scale, setScale] = useState(1)
const [offset, setOffset] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
const dragStart = useRef({ x: 0, y: 0 })
const { data: mapData } = useSWR('/partitions', fetcher, { refreshInterval: 60000 })
useEffect(() => {
const allMarkers: MapMarker[] = []
if (mapData?.success) {
(mapData.data || []).forEach((p: any) => {
if (p.center_x != null && p.center_y != null) {
allMarkers.push({
id: `partition-${p.partition_id}`,
name: p.name || `Partition ${p.partition_id}`,
x: p.center_x,
y: p.center_y,
type: 'building',
})
}
})
}
setMarkers(allMarkers)
}, [mapData])
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext('2d')
if (!ctx) return
const dpr = window.devicePixelRatio || 1
const rect = canvas.getBoundingClientRect()
canvas.width = rect.width * dpr
canvas.height = rect.height * dpr
ctx.scale(dpr, dpr)
ctx.fillStyle = '#1a1a1a'
ctx.fillRect(0, 0, rect.width, rect.height)
ctx.strokeStyle = '#333'
ctx.lineWidth = 1
const gridSize = 50 * scale
for (let x = offset.x % gridSize; x < rect.width; x += gridSize) {
ctx.beginPath()
ctx.moveTo(x, 0)
ctx.lineTo(x, rect.height)
ctx.stroke()
}
for (let y = offset.y % gridSize; y < rect.height; y += gridSize) {
ctx.beginPath()
ctx.moveTo(0, y)
ctx.lineTo(rect.width, y)
ctx.stroke()
}
const filtered = filter === 'all' ? markers : markers.filter((m) => m.type === filter)
filtered.forEach((m) => {
const sx = rect.width / 2 + (m.x * 0.001 * scale) + offset.x
const sy = rect.height / 2 + (m.y * 0.001 * scale) + offset.y
ctx.beginPath()
ctx.arc(sx, sy, 6, 0, Math.PI * 2)
ctx.fillStyle = m.type === 'player' ? '#27ae60' : m.type === 'vehicle' ? '#4a90d9' : '#d4af37'
ctx.fill()
ctx.strokeStyle = '#fff'
ctx.lineWidth = 1
ctx.stroke()
ctx.fillStyle = '#c0c0c0'
ctx.font = '10px Inter'
ctx.fillText(m.name, sx + 10, sy + 3)
})
}, [markers, filter, scale, offset])
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault()
const newScale = Math.max(0.1, Math.min(10, scale + (e.deltaY > 0 ? -0.1 : 0.1)))
setScale(newScale)
}
const handleMouseDown = (e: React.MouseEvent) => {
setIsDragging(true)
dragStart.current = { x: e.clientX - offset.x, y: e.clientY - offset.y }
}
const handleMouseMove = (e: React.MouseEvent) => {
if (!isDragging) return
setOffset({ x: e.clientX - dragStart.current.x, y: e.clientY - dragStart.current.y })
}
const handleMouseUp = () => setIsDragging(false)
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<div className="flex items-center justify-between mb-4">
<h1 className="font-serif text-3xl text-primary">Map Viewer</h1>
<div className="flex gap-2">
{(['all', 'player', 'vehicle', 'building'] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 rounded text-xs font-medium border capitalize ${
filter === f
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
>
{f}
</button>
))}
<button
onClick={() => { setScale(1); setOffset({ x: 0, y: 0 }) }}
className="px-3 py-1.5 rounded text-xs font-medium border bg-card-bg border-border text-text-muted hover:text-text-primary"
>
Reset View
</button>
</div>
</div>
<div className="flex-1 bg-card-bg border border-border rounded-lg overflow-hidden relative">
<canvas
ref={canvasRef}
className="w-full h-full cursor-grab active:cursor-grabbing"
onWheel={handleWheel}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
/>
<div className="absolute bottom-4 left-4 bg-card-bg/90 border border-border rounded px-3 py-2 text-xs text-text-muted">
Zoom: {scale.toFixed(1)}x | Markers: {markers.length}
</div>
</div>
</div>
)
}
@@ -0,0 +1,128 @@
import { useState, useEffect } from 'react'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
interface Metrics {
total_players: number
online_players: number
guild_count: number
active_guilds: number
server_count: number
partition_count: number
total_worth: number
total_flavor_text: number
}
export default function Overview() {
const [metrics, setMetrics] = useState<Metrics | null>(null)
const [loading, setLoading] = useState(true)
const { dispatch } = useApp()
useEffect(() => {
async function load() {
try {
const res = await client.get('/stats')
if (res.data.success) {
setMetrics(res.data.data)
}
} catch (e) {
console.error(e)
} finally {
setLoading(false)
}
}
load()
const es = new EventSource('/api/events/stream')
es.addEventListener('metrics', (e) => {
try {
setMetrics(JSON.parse(e.data))
} catch {}
})
return () => es.close()
}, [])
const statCards = metrics
? [
{ label: 'Total Players', value: metrics.total_players.toLocaleString(), icon: '👥' },
{ label: 'Online Players', value: metrics.online_players.toLocaleString(), icon: '🟢' },
{ label: 'Guilds', value: metrics.guild_count.toLocaleString(), icon: '🛡️' },
{ label: 'Active Guilds', value: metrics.active_guilds.toLocaleString(), icon: '⚔️' },
{ label: 'Servers', value: metrics.server_count.toLocaleString(), icon: '🖥️' },
{ label: 'Partitions', value: metrics.partition_count.toLocaleString(), icon: '🗺️' },
{ label: 'Total Worth', value: '$' + Math.round(metrics.total_worth).toLocaleString(), icon: '💰' },
{ label: 'Flavor Text', value: metrics.total_flavor_text.toLocaleString(), icon: '📝' },
]
: []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Dashboard Overview</h1>
{loading ? (
<div className="text-text-muted">Loading metrics...</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{statCards.map((card) => (
<div
key={card.label}
className="bg-card-bg border border-border rounded-lg p-5 shadow-card"
>
<div className="flex items-center justify-between mb-2">
<span className="text-2xl">{card.icon}</span>
</div>
<div className="text-2xl font-bold text-text-primary mb-1">{card.value}</div>
<div className="text-sm text-text-muted">{card.label}</div>
</div>
))}
</div>
)}
<div className="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 shadow-card">
<h2 className="font-serif text-xl text-primary mb-4">Quick Actions</h2>
<div className="grid grid-cols-2 gap-3">
<QuickAction label="Broadcast Message" onClick={() => {}} />
<QuickAction label="Player Search" onClick={() => {}} />
<QuickAction label="Guild Lookup" onClick={() => {}} />
<QuickAction label="Server Restart" onClick={() => {}} />
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 shadow-card">
<h2 className="font-serif text-xl text-primary mb-4">System Health</h2>
<div className="space-y-3">
<HealthRow label="Database" status="ok" detail="Connected" />
<HealthRow label="SSH Tunnel" status="ok" detail="Connected" />
<HealthRow label="BG Director" status="ok" detail="Connected" />
<HealthRow label="RMQ Game" status="ok" detail="Connected" />
</div>
</div>
</div>
</div>
)
}
function QuickAction({ label, onClick }: { label: string; onClick: () => void }) {
return (
<button
onClick={onClick}
className="px-4 py-3 bg-primary/10 border border-primary/20 rounded-lg text-primary text-sm font-medium hover:bg-primary/20 transition-colors text-left"
>
{label}
</button>
)
}
function HealthRow({ label, status, detail }: { label: string; status: 'ok' | 'warn' | 'error'; detail: string }) {
const dotColor = status === 'ok' ? '#27ae60' : status === 'warn' ? '#f39c12' : '#c0392b'
return (
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full" style={{ backgroundColor: dotColor }} />
<span className="text-text-secondary">{label}</span>
</div>
<span className="text-text-muted">{detail}</span>
</div>
)
}
@@ -0,0 +1,575 @@
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import Badge from '../common/Badge'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
export default function PlayerDetail() {
const { accountId } = useParams<{ accountId: string }>()
const navigate = useNavigate()
const { dispatch } = useApp()
const [activeTab, setActiveTab] = useState('overview')
const { data: detail } = useSWR(
accountId ? `/players/${accountId}` : null,
fetcher,
{ refreshInterval: 30000 }
)
const player = detail?.success ? detail.data : null
const handleAction = async (endpoint: string, payload: any = {}) => {
try {
const res = await client.post(endpoint, payload)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Action failed', type: 'error' } })
}
}
if (!player) {
return <div className="text-text-muted">Loading player details...</div>
}
const tabs = [
{ key: 'overview', label: 'Overview' },
{ key: 'inventory', label: 'Inventory' },
{ key: 'vehicles', label: 'Vehicles' },
{ key: 'buildings', label: 'Buildings' },
{ key: 'progression', label: 'Progression' },
{ key: 'actions', label: 'Actions' },
]
return (
<div>
<div className="flex items-center gap-4 mb-6">
<button
onClick={() => navigate('/players')}
className="text-text-muted hover:text-text-primary text-sm"
>
&larr; Back to Players
</button>
</div>
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="font-serif text-3xl text-primary">{player.character_name}</h1>
<div className="flex items-center gap-2 mt-1">
<Badge
label={player.online_status}
variant={player.is_online ? 'success' : 'default'}
/>
{player.faction_name && (
<span className="text-sm text-text-secondary">{player.faction_name}</span>
)}
{player.tags?.map((tag: string) => (
<Badge key={tag} label={tag} variant="warning" />
))}
</div>
</div>
</div>
<div className="flex gap-1 mb-6 border-b border-border">
{tabs.map((t) => (
<button
key={t.key}
onClick={() => setActiveTab(t.key)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
activeTab === t.key
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
>
{t.label}
</button>
))}
</div>
{activeTab === 'overview' && <OverviewTab player={player} />}
{activeTab === 'inventory' && <InventoryTab player={player} />}
{activeTab === 'vehicles' && <VehiclesTab player={player} />}
{activeTab === 'buildings' && <BuildingsTab player={player} />}
{activeTab === 'progression' && <ProgressionTab player={player} />}
{activeTab === 'actions' && <ActionsTab player={player} onAction={handleAction} />}
</div>
)
}
function OverviewTab({ player }: { player: any }) {
const vitals = player.vitals || {}
const currency = player.currency || []
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Character Info</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<InfoRow label="Account ID" value={player.account_id} />
<InfoRow label="Controller ID" value={player.player_controller_id} />
<InfoRow label="Pawn ID" value={player.player_pawn_id} />
<InfoRow label="Email" value={player.account_email} />
<InfoRow label="Funcom ID" value={player.funcom_id} />
<InfoRow label="Map" value={player.map} />
<InfoRow label="Life State" value={player.life_state} />
<InfoRow label="Last Login" value={player.last_login_time} />
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Vitals</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<InfoRow label="Health" value={`${vitals.current_health ?? '?'}/${vitals.max_health ?? '?'}`} />
<InfoRow label="Hydration" value={vitals.current_hydration ?? '?'} />
<InfoRow label="Dehydration" value={vitals.dehydration_penalty ?? '?'} />
<InfoRow label="Spice" value={vitals.current_spice ?? '?'} />
<InfoRow label="Addiction" value={vitals.spice_addiction_level ?? '?'} />
<InfoRow label="Tolerance" value={vitals.spice_tolerance ?? '?'} />
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Currency</h3>
<div className="space-y-2">
{currency.length === 0 && <span className="text-text-muted text-sm">No currency data</span>}
{currency.map((c: any) => (
<div key={c.currency_id} className="flex justify-between text-sm">
<span className="text-text-secondary">{c.currency_label}</span>
<span className="text-text-primary font-mono">{c.balance}</span>
</div>
))}
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Landsraad</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
{player.landsraad ? (
<>
<InfoRow label="Daily Charges" value={player.landsraad.daily_reward_charges} />
<InfoRow label="Last Term" value={player.landsraad.last_viewed_term_id} />
</>
) : (
<span className="text-text-muted">No landsraad data</span>
)}
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Faction Reputation</h3>
<div className="space-y-2">
{(player.faction_reputation || []).length === 0 && <span className="text-text-muted text-sm">No reputation data</span>}
{(player.faction_reputation || []).map((r: any) => (
<div key={r.faction_id} className="flex justify-between text-sm">
<span className="text-text-secondary">{r.faction_name || `Faction ${r.faction_id}`}</span>
<span className="text-text-primary font-mono">{r.reputation_amount}</span>
</div>
))}
</div>
</div>
</div>
)
}
function InfoRow({ label, value }: { label: string; value: any }) {
return (
<div>
<div className="text-text-muted text-xs uppercase tracking-wider">{label}</div>
<div className="text-text-primary font-mono">{value ?? 'N/A'}</div>
</div>
)
}
function InventoryTab({ player }: { player: any }) {
const inventories = player.inventories || []
const [selectedInv, setSelectedInv] = useState<any>(null)
return (
<div>
<h3 className="font-serif text-xl text-primary mb-4">Inventories</h3>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
{inventories.map((inv: any) => (
<button
key={inv.inventory_id}
onClick={() => setSelectedInv(inv)}
className={`text-left p-4 rounded-lg border transition-colors ${
selectedInv?.inventory_id === inv.inventory_id
? 'bg-primary/10 border-primary'
: 'bg-card-bg border-border hover:bg-hover'
}`}
>
<div className="text-sm font-medium text-text-primary">{inv.inventory_type_label}</div>
<div className="text-xs text-text-muted mt-1">ID: {inv.inventory_id}</div>
<div className="text-xs text-text-muted">Items: {inv.items?.length || 0}</div>
</button>
))}
</div>
{selectedInv && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h4 className="text-text-primary font-medium mb-3">
{selectedInv.inventory_type_label} Items
</h4>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Item</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Stack</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Quality</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Durability</th>
</tr>
</thead>
<tbody>
{(selectedInv.items || []).map((item: any, i: number) => (
<tr key={i} className="border-b border-border last:border-0">
<td className="px-3 py-2">{item.template_id}</td>
<td className="px-3 py-2 font-mono">{item.stack_size}</td>
<td className="px-3 py-2 font-mono">{item.quality_level}</td>
<td className="px-3 py-2 font-mono">
{item.durability != null ? `${Math.round(item.durability)}/${Math.round(item.max_durability)}` : 'N/A'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)
}
function VehiclesTab({ player }: { player: any }) {
const vehicles = player.vehicles || []
return (
<div>
<h3 className="font-serif text-xl text-primary mb-4">Vehicles</h3>
{vehicles.length === 0 ? (
<div className="text-text-muted">No vehicles found.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{vehicles.map((v: any) => (
<div key={v.id} className="bg-card-bg border border-border rounded-lg p-4">
<div className="text-text-primary font-medium">{v.display_name || v.class_name}</div>
<div className="text-xs text-text-muted mt-1">Map: {v.map || 'Unknown'}</div>
<div className="text-xs text-text-muted font-mono">ID: {v.id}</div>
</div>
))}
</div>
)}
</div>
)
}
function BuildingsTab({ player }: { player: any }) {
const buildings = player.buildings || []
const landclaims = player.landclaims || []
return (
<div className="space-y-6">
<div>
<h3 className="font-serif text-xl text-primary mb-4">Buildings</h3>
{buildings.length === 0 ? (
<div className="text-text-muted">No buildings found.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{buildings.map((b: any) => (
<div key={b.id} className="bg-card-bg border border-border rounded-lg p-4">
<div className="text-text-primary font-medium">{b.class_name}</div>
<div className="text-xs text-text-muted mt-1">Map: {b.map || 'Unknown'}</div>
<div className="flex gap-2 mt-2">
{b.is_powered && <Badge label="Powered" variant="success" />}
{b.power_level != null && <Badge label={`Power ${b.power_level}`} variant="default" />}
</div>
</div>
))}
</div>
)}
</div>
<div>
<h3 className="font-serif text-xl text-primary mb-4">Landclaims</h3>
{landclaims.length === 0 ? (
<div className="text-text-muted">No landclaims found.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{landclaims.map((l: any) => (
<div key={l.id} className="bg-card-bg border border-border rounded-lg p-4">
<div className="text-text-primary font-medium">{l.class_name}</div>
<div className="text-xs text-text-muted mt-1">Map: {l.map || 'Unknown'}</div>
</div>
))}
</div>
)}
</div>
</div>
)
}
function ProgressionTab({ player }: { player: any }) {
const specs = player.specialization || []
const keystones = player.keystones || []
return (
<div className="space-y-6">
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Specialization Tracks</h3>
{specs.length === 0 ? (
<div className="text-text-muted">No specialization data.</div>
) : (
<div className="space-y-3">
{specs.map((s: any, i: number) => (
<div key={i} className="flex items-center justify-between">
<span className="text-text-secondary text-sm">{s.track_type}</span>
<div className="flex items-center gap-4">
<span className="text-text-muted text-xs">XP: {s.xp_amount}</span>
<Badge label={`Lv ${s.level}`} variant="default" />
</div>
</div>
))}
</div>
)}
</div>
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="font-serif text-lg text-primary mb-4">Keystones</h3>
{keystones.length === 0 ? (
<div className="text-text-muted">No keystones.</div>
) : (
<div className="flex flex-wrap gap-2">
{keystones.map((k: any) => (
<Badge key={k.id} label={k.name} variant="default" />
))}
</div>
)}
</div>
</div>
)
}
function ActionsTab({ player, onAction }: { player: any; onAction: (endpoint: string, payload?: any) => Promise<void> }) {
const accountId = player.account_id
const [newName, setNewName] = useState('')
const [currencyForm, setCurrencyForm] = useState({ currency_id: '0', amount: '' })
const [vitalsForm, setVitalsForm] = useState({ health: '', hydration: '', spice: '' })
const [teleportForm, setTeleportForm] = useState({ partition: '', x: '', y: '', z: '' })
const [banReason, setBanReason] = useState('')
const [banDuration, setBanDuration] = useState('0')
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<ActionCard title="Currency">
<div className="space-y-2">
<select
value={currencyForm.currency_id}
onChange={(e) => setCurrencyForm({ ...currencyForm, currency_id: e.target.value })}
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
>
<option value="0">Solari Credits</option>
<option value="1">House Script</option>
<option value="2">Spice</option>
</select>
<input
type="number"
value={currencyForm.amount}
onChange={(e) => setCurrencyForm({ ...currencyForm, amount: e.target.value })}
placeholder="Amount"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<div className="flex gap-2">
<button
onClick={() => onAction(`/currency/adjust`, { player_id: accountId, currency_id: parseInt(currencyForm.currency_id), amount: parseFloat(currencyForm.amount) })}
className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary"
>
Adjust
</button>
<button
onClick={() => onAction(`/currency/set`, { player_id: accountId, currency_id: parseInt(currencyForm.currency_id), amount: parseFloat(currencyForm.amount) })}
className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary"
>
Set Exact
</button>
</div>
</div>
</ActionCard>
<ActionCard title="Vitals">
<div className="space-y-2">
<input
type="number"
value={vitalsForm.health}
onChange={(e) => setVitalsForm({ ...vitalsForm, health: e.target.value })}
placeholder="Health"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<input
type="number"
value={vitalsForm.hydration}
onChange={(e) => setVitalsForm({ ...vitalsForm, hydration: e.target.value })}
placeholder="Hydration"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<input
type="number"
value={vitalsForm.spice}
onChange={(e) => setVitalsForm({ ...vitalsForm, spice: e.target.value })}
placeholder="Spice"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<button
onClick={() => onAction(`/vitals/set`, { player_id: accountId, health: parseFloat(vitalsForm.health) || undefined, hydration: parseFloat(vitalsForm.hydration) || undefined, spice: parseFloat(vitalsForm.spice) || undefined })}
className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary"
>
Set Vitals
</button>
</div>
</ActionCard>
<ActionCard title="Teleport">
<div className="space-y-2">
<input
value={teleportForm.partition}
onChange={(e) => setTeleportForm({ ...teleportForm, partition: e.target.value })}
placeholder="Partition ID"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<div className="grid grid-cols-3 gap-2">
<input
type="number"
value={teleportForm.x}
onChange={(e) => setTeleportForm({ ...teleportForm, x: e.target.value })}
placeholder="X"
className="bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<input
type="number"
value={teleportForm.y}
onChange={(e) => setTeleportForm({ ...teleportForm, y: e.target.value })}
placeholder="Y"
className="bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<input
type="number"
value={teleportForm.z}
onChange={(e) => setTeleportForm({ ...teleportForm, z: e.target.value })}
placeholder="Z"
className="bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
</div>
<button
onClick={() => onAction(`/teleport`, { fls_id: accountId, partition_id: teleportForm.partition, x: parseFloat(teleportForm.x) || 0, y: parseFloat(teleportForm.y) || 0, z: parseFloat(teleportForm.z) || 0 })}
className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary"
>
Teleport
</button>
</div>
</ActionCard>
<ActionCard title="Character">
<div className="space-y-2">
<input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="New character name"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<div className="flex flex-wrap gap-2">
<button
onClick={() => onAction(`/characters/${accountId}/name`, { name: newName })}
className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary"
>
Rename
</button>
<button
onClick={() => onAction(`/accounts/${accountId}/demo`, { demo: true })}
className="px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning"
>
Set Demo
</button>
<button
onClick={() => onAction(`/accounts/${accountId}/demo`, { demo: false })}
className="px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning"
>
Clear Demo
</button>
<button
onClick={() => {
if (confirm('Delete this character? This cannot be undone.')) {
onAction(`/characters/${accountId}`, {})
}
}}
className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger"
>
Delete Character
</button>
<button
onClick={() => {
if (confirm('Delete this entire account? This cannot be undone.')) {
onAction(`/accounts/${accountId}`, {})
}
}}
className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger"
>
Delete Account
</button>
</div>
</div>
</ActionCard>
<ActionCard title="Moderation">
<div className="space-y-2">
<input
value={banReason}
onChange={(e) => setBanReason(e.target.value)}
placeholder="Ban reason"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<input
type="number"
value={banDuration}
onChange={(e) => setBanDuration(e.target.value)}
placeholder="Duration (hours, 0 = permanent)"
className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm"
/>
<div className="flex flex-wrap gap-2">
<button
onClick={() => onAction(`/players/${accountId}/ban`, { reason: banReason, duration_hours: parseInt(banDuration) || 0 })}
className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger"
>
Ban Player
</button>
<button
onClick={() => onAction(`/players/${accountId}/unban`, {})}
className="px-3 py-1.5 rounded text-xs bg-success/10 border border-success/30 text-success"
>
Unban Player
</button>
<button
onClick={() => onAction(`/players/${accountId}/kick`, { reason: banReason })}
className="px-3 py-1.5 rounded text-xs bg-warning/10 border border-warning/20 text-warning"
>
Kick Player
</button>
</div>
</div>
</ActionCard>
</div>
)
}
function ActionCard({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h4 className="text-text-primary font-medium mb-3">{title}</h4>
{children}
</div>
)
}
@@ -0,0 +1,122 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import { useDebounce } from '../../hooks/useDebounce'
import DataTable from '../common/DataTable'
import Badge from '../common/Badge'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface Player {
player_controller_id: number | null
account_id: number | null
character_name: string
account_email: string | null
funcom_id: string | null
faction_name: string | null
map: string | null
online_status: string
life_state: string | null
last_login_time: string | null
}
export default function PlayerExplorer() {
const [search, setSearch] = useState('')
const debouncedSearch = useDebounce(search, 300)
const navigate = useNavigate()
const { dispatch } = useApp()
const { data: players, isLoading } = useSWR(
debouncedSearch.length >= 2
? `/players?q=${encodeURIComponent(debouncedSearch)}&limit=25`
: null,
fetcher,
{ refreshInterval: 30000 }
)
const handleAction = async (accountId: number, action: string, payload: Record<string, unknown> = {}) => {
try {
let res
if (action === 'cheater') {
res = await client.post(`/players/${accountId}/cheater`, payload)
} else if (action === 'tags') {
res = await client.put(`/players/${accountId}/tags`, payload)
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: `Action "${action}" not yet implemented`, type: 'warning' } })
return
}
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Action failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Action failed', type: 'error' } })
}
}
const playerList: Player[] = players?.success ? players.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Player Explorer</h1>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search by name, email, or Funcom ID..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<DataTable
columns={[
{ header: 'Name', accessor: 'character_name' },
{
header: 'Status',
accessor: (row) => (
<Badge
label={row.online_status}
variant={row.online_status === 'Online' ? 'success' : 'default'}
/>
),
},
{ header: 'Funcom ID', accessor: 'funcom_id' },
{ header: 'Faction', accessor: 'faction_name' },
{ header: 'Map', accessor: 'map' },
{
header: 'Quick Actions',
accessor: (row) => (
<div className="flex gap-2">
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.account_id || row.player_controller_id || 0, 'cheater', { cheat_type: 'exploit' }) }}
className="text-[10px] text-primary hover:underline"
>
Cheater
</button>
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.account_id || row.player_controller_id || 0, 'tags', { add: ['reviewed'] }) }}
className="text-[10px] text-primary hover:underline"
>
Tag
</button>
</div>
),
},
]}
data={playerList}
onRowClick={(row) => navigate(`/players/${row.account_id || row.player_controller_id || 0}`)}
loading={isLoading}
/>
</div>
)
}
@@ -0,0 +1,241 @@
import { useState, useEffect } from 'react'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import Badge from '../common/Badge'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface Pod {
name: string
namespace: string
status: string
restarts: number
age: string
}
interface Deployment {
name: string
namespace: string
replicas: number
available: number
}
interface MetricPoint {
timestamp: string
cpu_percent: number
memory_percent: number
}
export default function ServerControl() {
const [tab, setTab] = useState<'pods' | 'deployments' | 'metrics' | 'firewall' | 'rmq'>('pods')
const { dispatch } = useApp()
const { data: pods, mutate: mutatePods } = useSWR('/server/pods', fetcher, { refreshInterval: 15000 })
const { data: deployments } = useSWR('/server/deployments', fetcher, { refreshInterval: 30000 })
const { data: metrics } = useSWR('/server/metrics?hours=24', fetcher, { refreshInterval: 60000 })
const { data: firewall } = useSWR('/server/firewall/status', fetcher, { refreshInterval: 30000 })
const { data: rmq } = useSWR('/server/rmq/overview', fetcher, { refreshInterval: 30000 })
const podList: Pod[] = pods?.success ? pods.data : []
const deploymentList: Deployment[] = deployments?.success ? deployments.data : []
const metricList: MetricPoint[] = metrics?.success ? metrics.data : []
const handleRestart = async (deployment: string) => {
try {
const res = await client.post(`/server/deployments/${deployment}/restart`)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Restart initiated', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
const handleScale = async (deployment: string, replicas: number) => {
try {
const res = await client.post(`/server/deployments/${deployment}/scale`, { replicas })
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Scaled successfully', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Server Control</h1>
<div className="flex gap-1 mb-6 border-b border-border">
{(['pods', 'deployments', 'metrics', 'firewall', 'rmq'] as const).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors capitalize ${
tab === t
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
>
{t}
</button>
))}
</div>
{tab === 'pods' && (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Namespace</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Status</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Restarts</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Age</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{podList.map((pod) => (
<tr key={pod.name} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 font-mono text-xs">{pod.name}</td>
<td className="px-4 py-3">{pod.namespace}</td>
<td className="px-4 py-3">
<Badge
label={pod.status}
variant={pod.status === 'Running' ? 'success' : pod.status === 'Pending' ? 'warning' : 'danger'}
/>
</td>
<td className="px-4 py-3">{pod.restarts}</td>
<td className="px-4 py-3">{pod.age}</td>
<td className="px-4 py-3">
<button
onClick={() => handleRestart(pod.name)}
className="text-xs text-primary hover:underline"
>
Restart
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{tab === 'deployments' && (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Namespace</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Replicas</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Available</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{deploymentList.map((dep) => (
<tr key={dep.name} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 font-mono text-xs">{dep.name}</td>
<td className="px-4 py-3">{dep.namespace}</td>
<td className="px-4 py-3">{dep.replicas}</td>
<td className="px-4 py-3">{dep.available}</td>
<td className="px-4 py-3 flex gap-2">
<button
onClick={() => handleScale(dep.name, dep.replicas + 1)}
className="text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary"
>
+1
</button>
<button
onClick={() => handleScale(dep.name, Math.max(0, dep.replicas - 1))}
className="text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary"
>
-1
</button>
<button
onClick={() => handleRestart(dep.name)}
className="text-xs px-2 py-1 bg-danger/10 border border-danger/20 rounded text-danger"
>
Restart
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{tab === 'metrics' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Server Metrics (24h)</h3>
{metricList.length === 0 ? (
<div className="text-text-muted text-sm">No metrics available</div>
) : (
<div className="space-y-2">
{metricList.slice(-20).map((m, i) => (
<div key={i} className="flex items-center gap-4 text-sm">
<span className="text-text-muted w-32">{new Date(m.timestamp).toLocaleTimeString()}</span>
<div className="flex-1 flex items-center gap-2">
<span className="text-text-muted w-8">CPU</span>
<div className="flex-1 h-2 bg-border rounded overflow-hidden">
<div
className="h-full bg-primary"
style={{ width: `${Math.min(100, m.cpu_percent)}%` }}
/>
</div>
<span className="text-text-secondary w-10 text-right">{m.cpu_percent}%</span>
</div>
<div className="flex-1 flex items-center gap-2">
<span className="text-text-muted w-12">Mem</span>
<div className="flex-1 h-2 bg-border rounded overflow-hidden">
<div
className="h-full bg-success"
style={{ width: `${Math.min(100, m.memory_percent)}%` }}
/>
</div>
<span className="text-text-secondary w-10 text-right">{m.memory_percent}%</span>
</div>
</div>
))}
</div>
)}
</div>
)}
{tab === 'firewall' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Firewall Status</h3>
{firewall?.success ? (
<pre className="text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto">
{JSON.stringify(firewall.data, null, 2)}
</pre>
) : (
<div className="text-text-muted text-sm">No firewall data available</div>
)}
</div>
)}
{tab === 'rmq' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">RMQ Overview</h3>
{rmq?.success ? (
<pre className="text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto">
{JSON.stringify(rmq.data, null, 2)}
</pre>
) : (
<div className="text-text-muted text-sm">No RMQ data available</div>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,98 @@
import { useState, useEffect } from 'react'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
export default function Settings() {
const [settings, setSettings] = useState<Record<string, string>>({})
const [loading, setLoading] = useState(false)
const [saving, setSaving] = useState(false)
const { dispatch } = useApp()
const load = async () => {
setLoading(true)
try {
const res = await client.get('/settings')
if (res.data.success) {
setSettings(res.data.data)
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed to load settings', type: 'error' } })
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
}, [])
const handleSave = async () => {
setSaving(true)
try {
const res = await client.post('/settings', settings)
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Settings saved', type: 'success' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed to save', type: 'error' } })
} finally {
setSaving(false)
}
}
const handleChange = (key: string, value: string) => {
setSettings({ ...settings, [key]: value })
}
const addKey = () => {
const key = prompt('Enter new setting key:')
if (key) {
setSettings({ ...settings, [key]: '' })
}
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Settings</h1>
<div className="flex items-center gap-4 mb-6">
<button
onClick={load}
disabled={loading}
className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
>
{loading ? 'Loading...' : 'Reload'}
</button>
<button
onClick={handleSave}
disabled={saving}
className="px-4 py-2 bg-success text-white rounded-lg text-sm font-medium hover:bg-success/80 disabled:opacity-50"
>
{saving ? 'Saving...' : 'Save Settings'}
</button>
<button
onClick={addKey}
className="px-4 py-2 bg-card-bg border border-border text-text-primary rounded-lg text-sm font-medium hover:bg-hover"
>
Add Key
</button>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-2xl">
{Object.entries(settings).length === 0 && !loading && (
<div className="text-text-muted">No settings found.</div>
)}
{Object.entries(settings).map(([key, value]) => (
<div key={key} className="grid grid-cols-[200px_1fr] gap-4 items-center">
<label className="text-sm text-text-secondary truncate" title={key}>{key}</label>
<input
value={value}
onChange={(e) => handleChange(key, e.target.value)}
className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary"
/>
</div>
))}
</div>
</div>
)
}
+106
View File
@@ -0,0 +1,106 @@
import { useEffect, useRef } from 'react'
import { Terminal as XTerm } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { io, Socket } from 'socket.io-client'
import 'xterm/css/xterm.css'
export default function Terminal() {
const containerRef = useRef<HTMLDivElement>(null)
const termRef = useRef<XTerm | null>(null)
const fitAddonRef = useRef<FitAddon | null>(null)
const socketRef = useRef<Socket | null>(null)
useEffect(() => {
if (!containerRef.current) return
const term = new XTerm({
cursorBlink: true,
fontSize: 14,
fontFamily: 'Roboto Mono, monospace',
theme: {
background: '#1a1a1a',
foreground: '#f0f0f0',
cursor: '#d4af37',
selectionBackground: '#404040',
black: '#1a1a1a',
red: '#c0392b',
green: '#27ae60',
yellow: '#f39c12',
blue: '#4a90d9',
magenta: '#9966cc',
cyan: '#20b2aa',
white: '#f0f0f0',
brightBlack: '#404040',
brightRed: '#ff6b6b',
brightGreen: '#6abf6a',
brightYellow: '#e8c962',
brightBlue: '#6baee8',
brightMagenta: '#c8a8e8',
brightCyan: '#7de8d8',
brightWhite: '#ffffff',
},
})
const fitAddon = new FitAddon()
term.loadAddon(fitAddon)
term.open(containerRef.current)
fitAddon.fit()
termRef.current = term
fitAddonRef.current = fitAddon
const socket = io({
transports: ['websocket'],
})
socketRef.current = socket
socket.on('connect', () => {
term.writeln('Connecting to remote shell...')
socket.emit('shell_create', { type: 'vm' })
})
socket.on('shell_created', (data: any) => {
if (data.success) {
term.writeln('\r\nConnected to remote shell.')
} else {
term.writeln(`\r\nFailed to create shell: ${data.error || 'Unknown error'}`)
}
})
socket.on('shell_output', (data: any) => {
if (data.data) {
term.write(data.data)
}
})
socket.on('disconnect', () => {
term.writeln('\r\n[Disconnected]')
})
term.onData((data) => {
socket.emit('shell_input', { data })
})
const handleResize = () => {
fitAddon.fit()
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
socket.emit('shell_disconnect')
socket.disconnect()
term.dispose()
}
}, [])
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<h1 className="font-serif text-3xl text-primary mb-4">Remote Shell</h1>
<div
ref={containerRef}
className="flex-1 bg-[#1a1a1a] rounded-lg border border-border overflow-hidden"
/>
</div>
)
}
@@ -0,0 +1,93 @@
import { useState } from 'react'
import useSWR from 'swr'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
interface Vehicle {
id: number
class_name: string
display_name: string
map: string
owner_name: string
online_status: string
}
export default function Vehicles() {
const [search, setSearch] = useState('')
const { dispatch } = useApp()
const { data: vehiclesData, isLoading } = useSWR(
search.length >= 2 ? `/vehicles?q=${encodeURIComponent(search)}&limit=50` : '/vehicles?limit=100',
fetcher,
{ refreshInterval: 30000 }
)
const vehicleList: Vehicle[] = vehiclesData?.success ? vehiclesData.data : []
const handleAction = async (id: number, action: string) => {
try {
const res = await client.post(`/vehicles/${id}/${action}`, {})
if (res.data.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
}
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Vehicles</h1>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search vehicles..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<DataTable
columns={[
{ header: 'Name', accessor: 'display_name' },
{ header: 'Class', accessor: 'class_name' },
{ header: 'Map', accessor: 'map' },
{ header: 'Owner', accessor: 'owner_name' },
{
header: 'Actions',
accessor: (row) => (
<div className="flex gap-2">
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.id, 'repair') }}
className="text-xs text-primary hover:underline"
>
Repair
</button>
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.id, 'destroy') }}
className="text-xs text-danger hover:underline"
>
Destroy
</button>
</div>
),
},
]}
data={vehicleList}
loading={isLoading}
/>
</div>
)
}
+10
View File
@@ -0,0 +1,10 @@
import { useState, useEffect } from 'react'
export function useDebounce<T>(value: T, delay: number = 300): T {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay)
return () => clearTimeout(timer)
}, [value, delay])
return debounced
}
+52
View File
@@ -0,0 +1,52 @@
import { useEffect, useRef } from 'react'
import { useApp } from '../stores/AppContext'
export function useRealtime() {
const { dispatch } = useApp()
const evtSource = useRef<EventSource | null>(null)
useEffect(() => {
const es = new EventSource('/api/events/stream')
evtSource.current = es
es.onopen = () => {
console.log('[SSE] Connected')
}
es.addEventListener('battlegroup_update', (e) => {
try {
const data = JSON.parse(e.data)
console.log('[SSE] battlegroup_update', data)
} catch {}
})
es.addEventListener('rmq_health', (e) => {
try {
const data = JSON.parse(e.data)
console.log('[SSE] rmq_health', data)
} catch {}
})
es.addEventListener('connection_status', (e) => {
try {
const data = JSON.parse(e.data)
dispatch({ type: 'SET_CONNECTION', payload: data })
} catch {}
})
es.addEventListener('chat_message', (e) => {
try {
const data = JSON.parse(e.data)
console.log('[SSE] chat_message', data)
} catch {}
})
es.onerror = () => {
console.warn('[SSE] Connection error')
}
return () => {
es.close()
}
}, [dispatch])
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './styles/index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+83
View File
@@ -0,0 +1,83 @@
import React, { createContext, useContext, useReducer, useEffect } from 'react'
interface AppState {
user: string | null
theme: string
connectionStatus: {
database: boolean
ssh: boolean
bgd: boolean
rmq: boolean
}
toasts: Toast[]
}
interface Toast {
id: number
message: string
type: 'success' | 'error' | 'warning' | 'info'
}
type Action =
| { type: 'SET_USER'; payload: string | null }
| { type: 'SET_THEME'; payload: string }
| { type: 'SET_CONNECTION'; payload: Partial<AppState['connectionStatus']> }
| { type: 'ADD_TOAST'; payload: Omit<Toast, 'id'> }
| { type: 'REMOVE_TOAST'; payload: number }
const initialState: AppState = {
user: null,
theme: localStorage.getItem('dune-theme') || 'emperor',
connectionStatus: {
database: true,
ssh: true,
bgd: true,
rmq: true,
},
toasts: [],
}
let toastId = 0
function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload }
case 'SET_THEME':
return { ...state, theme: action.payload }
case 'SET_CONNECTION':
return { ...state, connectionStatus: { ...state.connectionStatus, ...action.payload } }
case 'ADD_TOAST':
return { ...state, toasts: [...state.toasts.slice(-2), { ...action.payload, id: ++toastId }] }
case 'REMOVE_TOAST':
return { ...state, toasts: state.toasts.filter((t) => t.id !== action.payload) }
default:
return state
}
}
const AppContext = createContext<{
state: AppState
dispatch: React.Dispatch<Action>
} | null>(null)
export function AppProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
document.documentElement.dataset.theme = state.theme
localStorage.setItem('dune-theme', state.theme)
}, [state.theme])
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
)
}
export function useApp() {
const ctx = useContext(AppContext)
if (!ctx) throw new Error('useApp must be used within AppProvider')
return ctx
}
+39
View File
@@ -0,0 +1,39 @@
@import './themes.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--primary: #d4af37;
--primary-dark: #b8962f;
--primary-light: #e8c962;
--bg: #1a1a1a;
--card-bg: #2a2a2a;
--text: #f0f0f0;
--text-light: #c0c0c0;
--text-muted: #808080;
--border: #404040;
--accent: #d4af37;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #0d0d0d;
--nav-text: #d4d4d4;
--nav-active: #d4af37;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
--table-header: #333333;
--code-bg: #222222;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg);
color: var(--text);
}
h1, h2, h3 {
font-family: 'Playfair Display', serif;
}
}
+281
View File
@@ -0,0 +1,281 @@
/* Dune Theme System — 14 themes */
[data-theme="default"] {
--primary: #c9a24e;
--primary-dark: #a8862e;
--primary-light: #e0c97a;
--bg: #f4f1ea;
--card-bg: #ffffff;
--text: #2c1810;
--text-light: #6b5a4a;
--text-muted: #9a8a7a;
--border: #e0d5c7;
--accent: #8b4513;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #1a1a2e;
--nav-text: #c9c4d0;
--nav-active: #c9a24e;
--hover: #f0ebe0;
--shadow: 0 2px 8px rgba(44,24,16,0.08);
}
[data-theme="atreides"] {
--primary: #2d5a27;
--primary-dark: #1e3d19;
--primary-light: #4a8c42;
--bg: #f0f5ed;
--card-bg: #ffffff;
--text: #1a2e1a;
--text-light: #3d4d3d;
--text-muted: #6b7c6b;
--border: #d4ddd4;
--accent: #1e3d19;
--danger: #8b2500;
--success: #2d5a27;
--nav-bg: #1a2e1a;
--nav-text: #d4ddd4;
--nav-active: #6abf6a;
--hover: #e2ebe2;
--shadow: 0 2px 8px rgba(30,61,25,0.1);
}
[data-theme="harkonnen"] {
--primary: #ff6b00;
--primary-dark: #cc5500;
--primary-light: #ff8c33;
--bg: #1a1a1a;
--card-bg: #2d2d2d;
--text: #e8e8e8;
--text-light: #b0b0b0;
--text-muted: #808080;
--border: #404040;
--accent: #ff4500;
--danger: #ff0000;
--success: #00cc44;
--nav-bg: #000000;
--nav-text: #cccccc;
--nav-active: #ff6b00;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="fremen"] {
--primary: #d4a853;
--primary-dark: #b8913f;
--primary-light: #e8c87a;
--bg: #e8dcc8;
--card-bg: #f5efe3;
--text: #3d3428;
--text-light: #5c4f3d;
--text-muted: #8a7d66;
--border: #d4cbb8;
--accent: #8b6914;
--danger: #a04000;
--success: #6b8e23;
--nav-bg: #2c2418;
--nav-text: #d4cbb8;
--nav-active: #d4a853;
--hover: #e8dcc8;
--shadow: 0 2px 8px rgba(44,36,24,0.1);
}
[data-theme="bene-gesserit"] {
--primary: #a8a8a8;
--primary-dark: #888888;
--primary-light: #c8c8c8;
--bg: #f8f8f8;
--card-bg: #ffffff;
--text: #2a2a2a;
--text-light: #505050;
--text-muted: #787878;
--border: #e0e0e0;
--accent: #606060;
--danger: #c41e3a;
--success: #2e8b57;
--nav-bg: #1a1a1a;
--nav-text: #d0d0d0;
--nav-active: #ffffff;
--hover: #f0f0f0;
--shadow: 0 2px 8px rgba(0,0,0,0.08);
}
[data-theme="spacing-guild"] {
--primary: #4a90d9;
--primary-dark: #2e6ab3;
--primary-light: #6baee8;
--bg: #1a1a2e;
--card-bg: #252540;
--text: #e0e0f0;
--text-light: #a0a0c0;
--text-muted: #707090;
--border: #3a3a50;
--accent: #6b5b95;
--danger: #d94545;
--success: #45d985;
--nav-bg: #0f0f1a;
--nav-text: #b0b0d0;
--nav-active: #4a90d9;
--hover: #2a2a40;
--shadow: 0 2px 8px rgba(0,0,0,0.3);
}
[data-theme="emperor"] {
--primary: #d4af37;
--primary-dark: #b8962f;
--primary-light: #e8c962;
--bg: #1a1a1a;
--card-bg: #2a2a2a;
--text: #f0f0f0;
--text-light: #c0c0c0;
--text-muted: #808080;
--border: #404040;
--accent: #d4af37;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #0d0d0d;
--nav-text: #d4d4d4;
--nav-active: #d4af37;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="corrino"] {
--primary: #8b0000;
--primary-dark: #5c0000;
--primary-light: #c43030;
--bg: #f5f0f0;
--card-bg: #ffffff;
--text: #2a1515;
--text-light: #5a3535;
--text-muted: #8a5555;
--border: #e0d5d5;
--accent: #a01010;
--danger: #8b0000;
--success: #2d5a27;
--nav-bg: #1a0a0a;
--nav-text: #d4c4c4;
--nav-active: #ff6b6b;
--hover: #f0e8e8;
--shadow: 0 2px 8px rgba(90,0,0,0.1);
}
[data-theme="mentat"] {
--primary: #008b8b;
--primary-dark: #006666;
--primary-light: #20b2aa;
--bg: #e8f4f4;
--card-bg: #ffffff;
--text: #1a2a2a;
--text-light: #3d5050;
--text-muted: #6b8080;
--border: #d4e0e0;
--accent: #006666;
--danger: #c44569;
--success: #008b8b;
--nav-bg: #0a1a1a;
--nav-text: #c4d4d4;
--nav-active: #00ced1;
--hover: #e0f0f0;
--shadow: 0 2px 8px rgba(0,60,60,0.1);
}
[data-theme="sardaukar"] {
--primary: #cd853f;
--primary-dark: #a0522d;
--primary-light: #deb887;
--bg: #f5ebe0;
--card-bg: #ffffff;
--text: #2a2018;
--text-light: #5a4a38;
--text-muted: #8a7a68;
--border: #e0d5c8;
--accent: #8b4513;
--danger: #8b0000;
--success: #6b8e23;
--nav-bg: #1a140c;
--nav-text: #d4c8b8;
--nav-active: #cd853f;
--hover: #f0e8e0;
--shadow: 0 2px 8px rgba(60,40,20,0.1);
}
[data-theme="tleilax"] {
--primary: #4a0080;
--primary-dark: #2d0050;
--primary-light: #6b20b0;
--bg: #1a1a24;
--card-bg: #252530;
--text: #e0e0e8;
--text-light: #a0a0b0;
--text-muted: #707080;
--border: #404050;
--accent: #6b0099;
--danger: #c41e3a;
--success: #00c080;
--nav-bg: #0a0a10;
--nav-text: #b0b0c0;
--nav-active: #9966cc;
--hover: #2a2a38;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="ordos"] {
--primary: #2e8b57;
--primary-dark: #1c5c3a;
--primary-light: #3cb371;
--bg: #e8f5f0;
--card-bg: #ffffff;
--text: #1a2e22;
--text-light: #3d5045;
--text-muted: #6b8075;
--border: #d4e0d8;
--accent: #1c5c3a;
--danger: #c45c3a;
--success: #2e8b57;
--nav-bg: #0a1a12;
--nav-text: #c4d8d0;
--nav-active: #3cb371;
--hover: #e0f0e8;
--shadow: 0 2px 8px rgba(20,60,40,0.1);
}
[data-theme="ix"] {
--primary: #4169e1;
--primary-dark: #2c4db8;
--primary-light: #6495ed;
--bg: #e8edf8;
--card-bg: #ffffff;
--text: #1a2248;
--text-light: #3d4470;
--text-muted: #6b7098;
--border: #d0d8e8;
--accent: #2c4db8;
--danger: #c44569;
--success: #32cd32;
--nav-bg: #0a1028;
--nav-text: #c0c8d8;
--nav-active: #6495ed;
--hover: #e0e8f0;
--shadow: 0 2px 8px rgba(30,50,100,0.15);
}
[data-theme="choam"] {
--primary: #b8860b;
--primary-dark: #8b6508;
--primary-light: #daa520;
--bg: #faf8f0;
--card-bg: #ffffff;
--text: #2a2820;
--text-light: #5a5848;
--text-muted: #8a8878;
--border: #e8e4d8;
--accent: #8b6508;
--danger: #b22222;
--success: #228b22;
--nav-bg: #1a180c;
--nav-text: #d4d0c0;
--nav-active: #daa520;
--hover: #f0ece0;
--shadow: 0 2px 8px rgba(60,50,20,0.1);
}
+36
View File
@@ -0,0 +1,36 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
darkMode: ["class", '[data-theme="emperor"]'],
theme: {
extend: {
colors: {
primary: "var(--primary)",
"primary-dark": "var(--primary-dark)",
"primary-light": "var(--primary-light)",
background: "var(--bg)",
"card-bg": "var(--card-bg)",
"text-primary": "var(--text)",
"text-secondary": "var(--text-light)",
"text-muted": "var(--text-muted)",
border: "var(--border)",
accent: "var(--accent)",
danger: "var(--danger)",
success: "var(--success)",
"nav-bg": "var(--nav-bg)",
"nav-text": "var(--nav-text)",
"nav-active": "var(--nav-active)",
hover: "var(--hover)",
},
fontFamily: {
serif: ["Playfair Display", "serif"],
sans: ["Inter", "sans-serif"],
mono: ["Roboto Mono", "monospace"],
},
boxShadow: {
card: "var(--shadow)",
},
},
},
plugins: [],
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:5050',
changeOrigin: true,
},
'/socket.io': {
target: 'http://localhost:5050',
ws: true,
},
},
},
build: {
outDir: 'dist',
emptyOutDir: true,
},
})