From 59cc98133c999621dc5d82f078d66175c47654b3 Mon Sep 17 00:00:00 2001 From: Reditus Date: Tue, 12 May 2026 01:02:58 +0100 Subject: [PATCH] Initial release - Dune Awakening Dashboard beta --- .gitignore | 64 ++++ LICENSE | 25 ++ README.md | 91 +++++ app/__init__.py | 1 + app/config.py | 109 ++++++ app/factory.py | 154 ++++++++ app/routes/__init__.py | 1 + app/routes/api.py | 700 ++++++++++++++++++++++++++++++++++ app/routes/auth.py | 50 +++ app/routes/main.py | 438 +++++++++++++++++++++ app/services/__init__.py | 1 + app/services/admin.py | 393 +++++++++++++++++++ app/services/chat.py | 156 ++++++++ app/services/database.py | 174 +++++++++ app/services/k8s.py | 77 ++++ app/services/player.py | 339 ++++++++++++++++ app/services/ssh.py | 43 +++ app/services/vehicle.py | 158 ++++++++ app/utils/__init__.py | 1 + app/utils/cache.py | 51 +++ app/utils/constants.py | 41 ++ app/websocket/__init__.py | 1 + app/websocket/shell.py | 124 ++++++ requirements.txt | 9 + run.py | 23 ++ settings.yaml.example | 54 +++ setup.ps1 | 324 ++++++++++++++++ setup.sh | 266 +++++++++++++ start.ps1 | 191 ++++++++++ start.sh | 144 +++++++ static/style.css | 631 ++++++++++++++++++++++++++++++ templates/account_detail.html | 76 ++++ templates/accounts.html | 73 ++++ templates/admin.html | 46 +++ templates/base.html | 29 ++ templates/buildings.html | 93 +++++ templates/chat.html | 139 +++++++ templates/director.html | 691 +++++++++++++++++++++++++++++++++ templates/events.html | 69 ++++ templates/file_view.html | 146 +++++++ templates/files.html | 170 +++++++++ templates/guild_detail.html | 91 +++++ templates/guilds.html | 72 ++++ templates/login.html | 125 ++++++ templates/overview.html | 116 ++++++ templates/player_detail.html | 624 ++++++++++++++++++++++++++++++ templates/players.html | 261 +++++++++++++ templates/server.html | 367 ++++++++++++++++++ templates/shell.html | 186 +++++++++ templates/vehicle_detail.html | 78 ++++ templates/vehicles.html | 142 +++++++ 51 files changed, 8428 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 app/__init__.py create mode 100644 app/config.py create mode 100644 app/factory.py create mode 100644 app/routes/__init__.py create mode 100644 app/routes/api.py create mode 100644 app/routes/auth.py create mode 100644 app/routes/main.py create mode 100644 app/services/__init__.py create mode 100644 app/services/admin.py create mode 100644 app/services/chat.py create mode 100644 app/services/database.py create mode 100644 app/services/k8s.py create mode 100644 app/services/player.py create mode 100644 app/services/ssh.py create mode 100644 app/services/vehicle.py create mode 100644 app/utils/__init__.py create mode 100644 app/utils/cache.py create mode 100644 app/utils/constants.py create mode 100644 app/websocket/__init__.py create mode 100644 app/websocket/shell.py create mode 100644 requirements.txt create mode 100644 run.py create mode 100644 settings.yaml.example create mode 100644 setup.ps1 create mode 100644 setup.sh create mode 100644 start.ps1 create mode 100644 start.sh create mode 100644 static/style.css create mode 100644 templates/account_detail.html create mode 100644 templates/accounts.html create mode 100644 templates/admin.html create mode 100644 templates/base.html create mode 100644 templates/buildings.html create mode 100644 templates/chat.html create mode 100644 templates/director.html create mode 100644 templates/events.html create mode 100644 templates/file_view.html create mode 100644 templates/files.html create mode 100644 templates/guild_detail.html create mode 100644 templates/guilds.html create mode 100644 templates/login.html create mode 100644 templates/overview.html create mode 100644 templates/player_detail.html create mode 100644 templates/players.html create mode 100644 templates/server.html create mode 100644 templates/shell.html create mode 100644 templates/vehicle_detail.html create mode 100644 templates/vehicles.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b01208 --- /dev/null +++ b/.gitignore @@ -0,0 +1,64 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ +*.egg +dist/ +build/ +*.whl + +# Virtual environments +venv/ +env/ +.venv/ + +# Local config (contains credentials) +settings.yaml +config_local.py + +# Environment files +.env +.env.local +.env.production + +# SSH keys +*.pem +*sshKey* +dune-tunnel-key +dune-awakening-server-sshKey +internal-scripts/ssh/sshKey + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db +desktop.ini + +# Logs +logs/ +*.log + +# Database +*.db +*.sqlite3 + +# Temporary files +*.tmp +*.bak + +# PowerShell profiles +Microsoft.PowerShell_profile.ps1 + +# Coverage reports +htmlcov/ +.coverage +.coverage.* +coverage.xml +.pytest_cache/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2da8d68 --- /dev/null +++ b/LICENSE @@ -0,0 +1,25 @@ +# DUNE DASHBOARD SOURCE LICENSE (DDSL) v1.0 + +Copyright (c) 2026 Reditus. All rights reserved. + +## 1. DEFINITIONS +"Software" refers to the source code, templates, scripts, and documentation contained in this repository. +"Author" refers to the original creator of the Software. + +## 2. SOURCE AVAILABILITY +The source code of the Software is made available for inspection, review, and security auditing purposes only. + +## 3. RESTRICTIONS +a) You may NOT redistribute the Software, in whole or in part, modified or unmodified. +b) You may NOT claim authorship, copyright, or any form of credit for the Software or any derivative work. +c) You may NOT use the Software for commercial purposes without explicit written permission from the Author. +d) You may NOT sublicense, sell, or lease the Software. + +## 4. PERMITTED USE +You are granted a non-exclusive, revocable license to use the Software for personal, non-commercial purposes, provided you comply with all restrictions herein. + +## 5. NO WARRANTY +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY. + +## 6. TERMINATION +This license terminates automatically if you fail to comply with any of its terms. Upon termination, you must cease all use and destroy all copies of the Software. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0c520b1 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +# Dune Awakening Dashboard + +A comprehensive web-based management dashboard for Dune: Awakening private servers. Provides real-time monitoring, player management, chat logging, file browsing, and server administration tools. + +## Features + +- **Real-time Overview**: Server metrics, player counts, pod status, and resource usage. +- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. +- **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. +- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures. + +## License + +This project is **Source Available** under the [Dune Dashboard Source License (DDSL)](LICENSE). +- Source code is available for inspection and security auditing. +- **No redistribution** (modified or unmodified). +- **No claiming of credit** or authorship. +- Personal, non-commercial use only. + +## Requirements + +- Python 3.8+ +- OpenSSH client +- `kubectl` access to the Dune: Awakening Kubernetes cluster +- SSH access to the game server VM + +## Setup + +### Windows + +1. **Run Setup** + ```powershell + .\setup.ps1 + ``` + This will install dependencies, configure your SSH key, and generate `settings.yaml`. + +2. **Start Dashboard** + ```powershell + .\start.ps1 + ``` + This starts the SSH tunnel, database port-forward, and launches the dashboard. + +### Linux / macOS + +1. **Run Setup** + ```bash + chmod +x setup.sh start.sh + ./setup.sh + ``` + +2. **Start Dashboard** + ```bash + ./start.sh + ``` + +## Configuration + +All settings are stored in `settings.yaml`. The setup script generates this automatically. Key settings include: + +- `server.host`: Game server VM IP +- `server.ssh_key`: Path to your SSH private key +- `kubernetes.namespace`: Auto-detected K8s namespace +- `database.port`: Local port for database tunnel +- `auth.username` / `auth.password`: Dashboard login credentials + +## Project Structure + +``` +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 +├── setup.ps1 / setup.sh # One-time setup scripts +├── start.ps1 / start.sh # Dashboard launchers +└── settings.yaml # Configuration (gitignored) +``` + +## 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. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..ccc870e --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Dune Awakening Server Dashboard - Application Package""" diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..a2efe68 --- /dev/null +++ b/app/config.py @@ -0,0 +1,109 @@ +"""Settings loader - reads settings.yaml with env var overrides""" + +import os +import yaml +import logging + +logger = logging.getLogger(__name__) + +DEFAULTS = { + 'server': { + 'host': '127.0.0.1', + 'user': 'dune', + 'ssh_key': None, + }, + 'dashboard': { + 'host': '127.0.0.1', + 'port': 5050, + 'debug': False, + 'secret_key': 'change-me-to-random-string', + }, + 'database': { + 'host': '127.0.0.1', + 'port': 15433, + 'user': 'postgres', + 'password': 'postgres', + 'name': 'dune', + 'schema': 'dune', + 'min_connections': 2, + 'max_connections': 10, + }, + 'kubernetes': { + 'namespace': '', + 'battlegroup_script': '/home/dune/.dune/bin/battlegroup', + }, + 'director': { + 'port': 32479, + }, + 'filebrowser': { + 'port': 18888, + }, + 'cache': { + 'chat_pod_ttl': 60, + 'chat_messages_ttl': 10, + 'static_data_ttl': 300, + }, + 'auth': { + 'enabled': True, + 'username': 'admin', + 'password': 'changeme', + }, + 'logging': { + 'level': 'INFO', + 'file': 'logs/dashboard.log', + 'max_bytes': 10485760, + 'backup_count': 5, + }, +} + + +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 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 = DEFAULTS.copy() + + 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 env_overrides: + settings = deep_merge(settings, env_overrides) + logger.info("Environment variable overrides applied") + + return settings diff --git a/app/factory.py b/app/factory.py new file mode 100644 index 0000000..0207e01 --- /dev/null +++ b/app/factory.py @@ -0,0 +1,154 @@ +"""Application factory - creates and configures the Flask app""" + +import os +import sys +import logging +import logging.handlers +from flask import Flask, request +from flask_socketio import SocketIO +from flask_talisman import Talisman + +from app.config import load_settings +from app.services.database import DatabaseService +from app.services.ssh import SSHService +from app.services.k8s import K8sService +from app.services.player import PlayerService +from app.services.vehicle import VehicleService +from app.services.chat import ChatService +from app.services.admin import AdminService +from app.utils.cache import MultiCache +from app.routes.main import register_routes +from app.routes.api import register_api_routes +from app.routes.auth import init_auth +from app.websocket.shell import register_websocket_handlers + + +def create_app(settings_path=None): + settings = load_settings(settings_path) + + base_dir = os.path.dirname(os.path.dirname(__file__)) + + app = Flask( + __name__, + template_folder=os.path.join(base_dir, 'templates'), + static_folder=os.path.join(base_dir, 'static'), + static_url_path='/static' + ) + app.config['SECRET_KEY'] = settings['dashboard']['secret_key'] + app.config['SESSION_COOKIE_HTTPONLY'] = True + app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' + + if not settings['dashboard']['debug']: + Talisman(app, content_security_policy=None, force_https=False) + + _setup_logging(settings) + + 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'] + ) + 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'] + ) + + static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl']) + + player_svc = PlayerService(db_service) + vehicle_svc = VehicleService(db_service) + chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache) + admin_svc = AdminService(db_service, ssh_service) + + services = { + 'db': db_service, + 'ssh': ssh_service, + 'k8s': k8s_service, + 'player': player_svc, + 'vehicle': vehicle_svc, + 'chat': chat_svc, + 'admin': admin_svc, + 'static_cache': static_cache, + } + + socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading') + + if settings['auth']['enabled']: + init_auth(app, settings) + + register_routes(app, services, settings) + register_api_routes(app, services, settings) + register_websocket_handlers(socketio, settings) + + @app.teardown_appcontext + def cleanup_db(exc): + pass + + 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(f"Could not auto-detect K8s namespace: {e}") + + app.dune_settings = settings + app.dune_services = services + + return app, socketio + + +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_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(logging.Formatter( + '%(asctime)s - %(levelname)s - %(message)s' + )) + console_handler.setLevel(log_level) + + root_logger = logging.getLogger() + root_logger.setLevel(log_level) + root_logger.addHandler(handler) + root_logger.addHandler(console_handler) + + audit_logger = logging.getLogger('audit') + audit_handler = logging.handlers.RotatingFileHandler( + 'logs/audit.log', + maxBytes=settings['logging']['max_bytes'], + backupCount=settings['logging']['backup_count'] + ) + audit_handler.setFormatter(logging.Formatter( + '%(asctime)s - %(message)s' + )) + audit_logger.addHandler(audit_handler) + audit_logger.setLevel(logging.INFO) diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 0000000..1a52617 --- /dev/null +++ b/app/routes/__init__.py @@ -0,0 +1 @@ +"""Routes package""" diff --git a/app/routes/api.py b/app/routes/api.py new file mode 100644 index 0000000..1d31ac7 --- /dev/null +++ b/app/routes/api.py @@ -0,0 +1,700 @@ +"""API routes - server actions, player management, debug endpoints""" + +import json +import logging +from flask import Blueprint, request, jsonify +from app.utils.constants import NAV_PAGES + +logger = logging.getLogger(__name__) + + +def register_api_routes(app, services, settings): + db = services['db'] + ssh = services['ssh'] + k8s = services['k8s'] + chat_svc = services['chat'] + admin_svc = services['admin'] + vehicle_svc = services['vehicle'] + + # Server actions + @app.route('/server/action', methods=['POST']) + def server_action(): + deployment = request.form.get('deployment', '') + action = request.form.get('action', '') + if not deployment or not action: + return jsonify({'success': False, 'output': 'Missing deployment or action'}) + + 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({'success': False, 'output': f'Unknown action: {action}'}) + + out, err, rc = k8s.run(cmd) + return jsonify({'success': rc == 0, 'output': out + '\n' + err}) + + @app.route('/server/pods') + def server_pods(): + out, err, rc = k8s.run('get pods -o wide') + if rc != 0: + return jsonify({'success': False, 'output': err}) + return jsonify({'success': True, 'output': out}) + + @app.route('/server/metrics') + def server_metrics(): + metrics = k8s.get_node_metrics() + if metrics: + return jsonify(metrics) + return jsonify({'cpu': 'N/A', 'memory': 'N/A'}) + + # Battlegroup + @app.route('/server/battlegroup/status') + def battlegroup_status(): + bg_script = settings['kubernetes']['battlegroup_script'] + out, err, rc = ssh.run(f'{bg_script} status', timeout=30) + return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + + @app.route('/server/battlegroup/action', methods=['POST']) + def battlegroup_action(): + action = request.form.get('action', '') + if action not in ('start', 'stop', 'restart'): + return jsonify({'success': False, 'output': f'Unknown action: {action}'}) + bg_script = settings['kubernetes']['battlegroup_script'] + out, err, rc = ssh.run(f'{bg_script} {action}', timeout=120) + return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + + @app.route('/server/battlegroup/update', methods=['POST']) + def battlegroup_update(): + bg_script = settings['kubernetes']['battlegroup_script'] + out, err, rc = ssh.run(f'{bg_script} update', timeout=600) + return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + + # Chat API + @app.route('/api/chat_logs') + def api_chat_logs(): + try: + chat_svc.ensure_history_table() + + db_messages = chat_svc.get_history(1) + if not db_messages or len(db_messages) < 10: + chat_svc.catch_up(settings['kubernetes']['namespace']) + + db_messages = chat_svc.get_history(200) + messages = [] + for row in db_messages: + ts = row.get('timestamp') + messages.append({ + 'channel': row.get('channel', ''), + 'sender': row.get('sender', ''), + 'message': row.get('message', ''), + 'timestamp': ts.isoformat() if ts else '', + 'location': {'X': row.get('location_x', 0), 'Y': row.get('location_y', 0), 'Z': row.get('location_z', 0)}, + 'target': row.get('target', ''), + 'is_admin': row.get('is_admin', False), + }) + + return jsonify({'success': True, 'messages': messages, 'count': len(messages)}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # Player IP management + @app.route('/api/set_player_ip', methods=['POST']) + def api_set_player_ip(): + try: + player_id = request.form.get('player_id', type=int) + ip_address = request.form.get('ip_address', '').strip() + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + if not ip_address: + return jsonify({'success': False, 'error': 'Missing ip_address'}) + + if admin_svc.set_player_ip(player_id, ip_address): + return jsonify({'success': True, 'message': f'IP {ip_address} set for player {player_id}'}) + return jsonify({'success': False, 'error': 'Failed to set IP'}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/detect_player_ips', methods=['POST']) + def api_detect_player_ips(): + try: + success, message = admin_svc.detect_player_ips(settings['kubernetes']['namespace']) + return jsonify({'success': success, 'message': message}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # Ban management + @app.route('/api/ban_player', methods=['POST']) + def api_ban_player(): + try: + player_id = request.form.get('player_id', type=int) + duration = request.form.get('duration', '0') + reason = request.form.get('reason', '') + note = request.form.get('note', '') + + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + + success, message = admin_svc.ban_player(player_id, duration, reason, note) + return jsonify({'success': success, 'message': message}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/get_player_ban', methods=['POST']) + def api_get_player_ban(): + try: + player_id = request.form.get('player_id', type=int) + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + + ban = admin_svc.get_player_ban(player_id) + if ban: + return jsonify({ + 'success': True, 'banned': True, + 'reason': ban.get('reason', ''), + 'note': ban.get('note', ''), + 'duration': ban.get('duration', 0), + 'banned_at': ban.get('banned_at').isoformat() if ban.get('banned_at') else '', + 'expires_at': ban.get('expires_at').isoformat() if ban.get('expires_at') else 'Permanent' + }) + return jsonify({'success': True, 'banned': False}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/get_player_history', methods=['POST']) + def api_get_player_history(): + try: + player_id = request.form.get('player_id', type=int) + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + + actions = admin_svc.get_player_history(player_id) + history = [] + for a in actions: + history.append({ + 'action': a.get('action_type', ''), + 'reason': a.get('reason', ''), + 'note': a.get('note', ''), + 'duration': a.get('duration_minutes', 0), + 'ip': a.get('ip_address', ''), + 'created_at': a.get('created_at').isoformat() if a.get('created_at') else '' + }) + return jsonify({'success': True, 'history': history}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/unban_player', methods=['POST']) + def api_unban_player(): + try: + player_id = request.form.get('player_id', type=int) + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + + success, message = admin_svc.unban_player(player_id) + return jsonify({'success': success, 'message': message}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/emergency_unban', methods=['POST']) + def api_emergency_unban(): + try: + ip = request.form.get('ip', '').strip() + if not ip: + return jsonify({'success': False, 'error': 'Missing IP'}) + success, message = admin_svc.emergency_unban(ip) + return jsonify({'success': success, 'message': message}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/kick_player', methods=['POST']) + def api_kick_player(): + try: + player_id = request.form.get('player_id', type=int) + if not player_id: + return jsonify({'success': False, 'error': 'Missing player_id'}) + + success, message = admin_svc.kick_player(player_id) + return jsonify({'success': success, 'message': message}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # Vitals editing + @app.route('/api/edit_vitals', methods=['POST']) + def api_edit_vitals(): + try: + pawn_id = request.form.get('pawn_id', type=int) + current_health = request.form.get('current_health', type=float) + max_health = request.form.get('max_health', type=float) + current_hydration = request.form.get('current_hydration', type=float) + current_spice = request.form.get('current_spice', type=float) + + success, result = admin_svc.edit_vitals(pawn_id, current_health, max_health, current_hydration, current_spice) + if success: + return jsonify({'success': True, **result}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # Maintenance + @app.route('/api/maintenance/create_indexes', methods=['POST']) + def api_create_indexes(): + try: + success, created, error = admin_svc.create_indexes() + if success: + return jsonify({'success': True, 'created': created, 'count': len(created)}) + return jsonify({'success': False, 'error': error}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + # Delete vehicle + @app.route('/api/vehicles/', methods=['DELETE']) + def delete_vehicle(vehicle_id): + success, message = vehicle_svc.delete_vehicle(vehicle_id) + if success: + return jsonify({'success': True, 'message': message}) + return jsonify({'success': False, 'error': message}), 404 if 'not found' in message.lower() else 500 + + # Delete building + @app.route('/api/buildings/', methods=['DELETE']) + def delete_building(building_id): + conn = db.get_connection() + if not conn: + return jsonify({'success': False, 'error': 'Database connection failed'}), 500 + cur = None + try: + cur = conn.cursor() + cur.execute("SET session_replication_role = replica") + cur.execute("DELETE FROM dune.building_instances WHERE building_id = %s", [building_id]) + cur.execute("DELETE FROM dune.buildings WHERE id = %s RETURNING id", [building_id]) + deleted = cur.fetchone() + if deleted: + cur.execute("DELETE FROM dune.actors WHERE id = %s RETURNING id", [building_id]) + conn.commit() + cur.execute("SET session_replication_role = default") + return jsonify({'success': True, 'message': f'Building {building_id} deleted'}) + else: + conn.rollback() + cur.execute("SET session_replication_role = default") + return jsonify({'success': False, 'error': 'Building not found'}), 404 + except Exception as e: + logger.error(f"Failed to delete building {building_id}: {e}") + try: + cur.execute("SET session_replication_role = default") + except Exception: + pass + return jsonify({'success': False, 'error': str(e)}), 500 + finally: + if cur: + cur.close() + db.return_connection(conn) + + # Debug endpoints (should be restricted in production) + @app.route('/api/debug/vehicle_properties/') + def debug_vehicle_properties(vehicle_id): + try: + vehicle = db.query(""" + 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], one=True) + if not vehicle: + return jsonify({'error': 'Vehicle not found'}), 404 + + props = vehicle.get('properties', {}) + keys = list(props.keys()) if props else [] + damageable = props.get('DamageableActorComponent', {}) + damageable_keys = list(damageable.keys()) if damageable else [] + weapon_comp = props.get('WeaponActorComponent', {}) + weapon_keys = list(weapon_comp.keys()) if weapon_comp else [] + + class_key = [k for k in keys if k.startswith('BP_')][0] if [k for k in keys if k.startswith('BP_')] else None + vehicle_bp = props.get(class_key, {}) if class_key else {} + + def extract_all_keys(d, prefix='', max_depth=3, depth=0): + if depth >= max_depth: + return [] + result = [] + if isinstance(d, dict): + for k, v in d.items(): + result.append(prefix + k) + if isinstance(v, dict): + result.extend(extract_all_keys(v, prefix + k + '.', max_depth, depth + 1)) + elif isinstance(v, list) and v and isinstance(v[0], dict): + result.append(prefix + k + '[]') + result.extend(extract_all_keys(v[0], prefix + k + '[0].', max_depth, depth + 1)) + return result + + all_keys = extract_all_keys(props)[:100] + relevant = [k for k in all_keys if any(x in k.lower() for x in ['health', 'damage', 'part', 'module', 'component', 'hit', 'armor', 'slot'])] + + return jsonify({ + 'id': vehicle_id, 'class': vehicle['class'], + 'all_keys_sample': all_keys[:50], 'relevant_keys': relevant[:30] + }) + except Exception as e: + logger.exception("Error fetching vehicle properties") + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vehicle_children//') + def debug_vehicle_children(vehicle_id): + try: + children = db.query(""" + SELECT a.id, a.class, a.map, a.properties + FROM dune.actors a + WHERE a.properties::text LIKE %s LIMIT 50 + """, [f'!!act#{vehicle_id}']) or [] + + results = [] + for c in children: + props = c.get('properties', {}) + results.append({ + 'id': c['id'], 'class': c['class'], 'map': c['map'], + 'keys': list(props.keys())[:15] if props else [] + }) + return jsonify({'vehicle_id': vehicle_id, 'found_children': len(results), 'children': results}) + except Exception as e: + logger.exception("Error fetching vehicle children") + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vehicle_parts/') + def debug_vehicle_parts(vehicle_id): + try: + parts = db.query(""" + SELECT a.id, a.class, a.properties FROM dune.actors + WHERE a.properties::text LIKE %s LIMIT 100 + """, [f'%!!act#{vehicle_id}%']) or [] + + results = [] + for p in parts: + props = p.get('properties', {}) + current_health = props.get('DamageableActorComponent', {}).get('m_CurrentMaxHealth') + max_health = props.get('DamageableActorComponent', {}).get('m_TotalMaxHealth') + results.append({ + 'id': p['id'], + 'class': p['class'][:100] if p.get('class') else '', + 'current_health': current_health, 'max_health': max_health + }) + + vehicle = db.query(""" + 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], one=True) + + return jsonify({ + 'vehicle_id': vehicle_id, + 'vehicle_class': vehicle.get('class', '') if vehicle else '', + 'keys': list(vehicle.get('properties', {}).keys()) if vehicle else [], + 'bp_keys': list(vehicle.get('properties', {}).get('BP_MediumOrnithopter_CHOAM_C', {}).keys()) if vehicle else [] + }) + except Exception as e: + logger.exception("Error fetching vehicle parts") + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/list_tables') + def list_tables(): + try: + tables = db.query(""" + SELECT table_name FROM information_schema.tables + WHERE table_schema = 'dune' ORDER BY table_name + """) or [] + return jsonify({'tables': [t.get('table_name', '') for t in tables]}) + except Exception as e: + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vehicle_modules/') + def debug_vehicle_modules(vehicle_id): + try: + vehicle_modules = db.query("SELECT * FROM dune.vehicle_modules WHERE vehicle_id = %s LIMIT 50", [vehicle_id]) or [] + return jsonify({'vehicle_id': vehicle_id, 'found': len(vehicle_modules), 'modules': vehicle_modules}) + except Exception as e: + logger.exception("Error fetching vehicle modules") + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vmi/') + def debug_vmi(vehicle_id): + try: + invs = db.query("SELECT * FROM dune.vehicle_module_inventories WHERE vehicle_id = %s LIMIT 10", [vehicle_id]) + return jsonify({'data': invs}) + except Exception as e: + return jsonify({'error': str(e)[:100]}) + + @app.route('/api/debug/vm_schema') + def debug_vm_schema(): + try: + cols = db.query(""" + SELECT column_name, data_type FROM information_schema.columns + WHERE table_name = 'vehicle_modules' AND table_schema = 'dune' + ORDER BY ordinal_position + """) or [] + return jsonify({'columns': cols}) + except Exception as e: + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vm_stats/') + def debug_vm_stats(vehicle_id): + try: + modules = db.query("SELECT id, template_id, stats FROM dune.vehicle_modules WHERE vehicle_id = %s", [vehicle_id]) or [] + results = [] + for m in modules: + stats = m.get('stats', {}) + durability = stats.get('FVehicleModuleDurabilityStats', [{}])[1] if stats.get('FVehicleModuleDurabilityStats') else {} + results.append({ + 'id': m['id'], 'template': m['template_id'], + 'durability_keys': list(durability.keys()) if durability else [], + 'durability': durability + }) + return jsonify({'vehicle_id': vehicle_id, 'modules': results}) + except Exception as e: + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/vehicle_row/') + def debug_vehicle_row(vehicle_id): + try: + v = db.query("SELECT * FROM dune.vehicles WHERE id = %s", [vehicle_id], one=True) + return jsonify({'vehicle': v}) + except Exception as e: + return jsonify({'error': str(e)}), 500 + + @app.route('/api/debug/module_tables') + def debug_module_tables(): + try: + tables = db.query(""" + SELECT table_name FROM information_schema.tables + WHERE table_schema = 'dune' AND (table_name LIKE '%module%' OR table_name LIKE '%vehicle%') + ORDER BY table_name + """) or [] + return jsonify({'tables': [t.get('table_name', '') for t in tables]}) + except Exception as e: + return jsonify({'error': str(e)}), 500 + + # File browser + def _get_fb_pod(): + """Get the FileBrowser pod name dynamically.""" + pod = k8s.find_pod_by_pattern('fb-deploy') + return pod + + def _fb_exec(command, timeout=10): + """Execute kubectl exec in the FileBrowser pod with correct namespace placement.""" + pod = _get_fb_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) + + @app.route('/api/files/list', methods=['POST']) + def api_files_list(): + path = request.form.get('path', '/srv') + out, err, rc = _fb_exec(f'ls -la "{path}"', timeout=10) + if rc != 0: + return jsonify({'success': False, 'error': err or 'Failed to list directory'}) + + files = [] + for line in out.strip().split('\n')[1:]: + parts = line.split(None, 8) + if len(parts) >= 9: + perms = parts[0] + size = parts[4] + date = ' '.join(parts[5:8]) + name = parts[8] + if name in ('.', '..'): + continue + files.append({ + 'name': name, + 'is_dir': perms.startswith('d'), + 'size': size if not perms.startswith('d') else '', + 'perms': perms, + 'date': date, + }) + return jsonify({'success': True, 'files': files}) + + @app.route('/api/files/view') + def api_files_view(): + path = request.args.get('path', '') + if not path: + return jsonify({'success': False, 'error': 'Missing path'}) + out, err, rc = _fb_exec(f'head -c 100000 "{path}"', timeout=10) + if rc != 0: + return jsonify({'success': False, 'error': err or 'Failed to read file'}) + return jsonify({'success': True, 'content': out, 'path': path}) + + @app.route('/api/files/save', methods=['POST']) + def api_files_save(): + path = request.form.get('path', '') + content = request.form.get('content', '') + if not path: + return jsonify({'success': False, 'error': 'Missing path'}) + import base64 + content_b64 = base64.b64encode(content.encode()).decode() + out, err, rc = _fb_exec(f'sh -c \'echo {content_b64} | base64 -d > "{path}"\'', timeout=15) + if rc != 0: + return jsonify({'success': False, 'error': err or 'Failed to save file'}) + return jsonify({'success': True}) + + director_port = settings.get('director', {}).get('port', 32479) + director_base = f"http://{settings['server']['host']}:{director_port}" + k8s_ns = settings['kubernetes']['namespace'] + cm_name = f"{k8s_ns}-bgd-conf-cm" + + def _patch_configmap(new_ini_content): + """Patch the BGD ConfigMap with new director.ini content via base64 pipe.""" + import base64 + cm_out, cm_err, cm_rc = k8s.run(f'get configmap {cm_name} -o json') + if cm_rc != 0 or not cm_out: + logger.warning(f"Could not get ConfigMap: {cm_err}") + return False + cm = json.loads(cm_out) + cm['data']['director.ini'] = new_ini_content + cm_json = json.dumps(cm) + cm_b64 = base64.b64encode(cm_json.encode()).decode() + patch_cmd = f'echo {cm_b64} | base64 -d | sudo kubectl apply -f - -n {k8s_ns}' + out, err, rc = ssh.run(patch_cmd, timeout=15) + if rc != 0: + logger.warning(f"ConfigMap patch failed: {err}") + return False + return True + + def _update_ini_section(map_name, key_values, remove_section=False): + """Read ConfigMap INI, modify section, write back.""" + import configparser + import io + cm_out, _, cm_rc = k8s.run(f'get configmap {cm_name} -o json') + if cm_rc != 0 or not cm_out: + return False + cm = json.loads(cm_out) + ini_content = cm['data'].get('director.ini', '') + cfg = configparser.ConfigParser() + cfg.read_string(ini_content) + if remove_section: + if cfg.has_section(map_name): + cfg.remove_section(map_name) + else: + if not cfg.has_section(map_name): + cfg.add_section(map_name) + for key, value in key_values.items(): + if value is not None: + cfg.set(map_name, key, str(value)) + buf = io.StringIO() + cfg.write(buf) + return _patch_configmap(buf.getvalue()) + + # Director API proxy + @app.route('/api/director/battlegroup') + def director_battlegroup(): + try: + import urllib.request + req = urllib.request.Request(f"{director_base}/v0/battlegroup") + with urllib.request.urlopen(req, timeout=15) as resp: + data = resp.read().decode() + return data, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 + + @app.route('/api/director/update_config', methods=['POST']) + def director_update_config(): + try: + import urllib.request + config = request.get_json() + map_name = config.get('MapName', '') + req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateServerGroupConfig", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(req, timeout=30) as resp: + result = resp.read().decode() + + if map_name: + kv = {} + if 'DimensionServerGroupConfig' in config: + dcfg = config['DimensionServerGroupConfig'] + if dcfg.get('playerHardCap') is not None: + kv['PlayerHardCap'] = dcfg['playerHardCap'] + if dcfg.get('minServers') is not None: + kv['MinServers'] = dcfg['minServers'] + if dcfg.get('numExtraServers') is not None: + kv['NumExtraServers'] = dcfg['numExtraServers'] + if 'enableAutomaticInstanceScaling' in dcfg: + kv['EnableAutomaticInstanceScaling'] = str(dcfg['enableAutomaticInstanceScaling']) + if dcfg.get('instanceScalingThrottlingSeconds') is not None: + kv['InstanceScalingThrottlingSeconds'] = dcfg['instanceScalingThrottlingSeconds'] + elif 'ClassicalInstancingGroupConfig' in config: + icfg = config['ClassicalInstancingGroupConfig'] + if icfg.get('playerHardCap') is not None: + kv['PlayerHardCap'] = icfg['playerHardCap'] + if icfg.get('minServers') is not None: + kv['MinServers'] = icfg['minServers'] + if icfg.get('numExtraServers') is not None: + kv['NumExtraServers'] = icfg['numExtraServers'] + if 'enableAutomaticInstanceScaling' in icfg: + kv['EnableAutomaticInstanceScaling'] = str(icfg['enableAutomaticInstanceScaling']) + if icfg.get('instanceScalingThrottlingSeconds') is not None: + kv['InstanceScalingThrottlingSeconds'] = icfg['instanceScalingThrottlingSeconds'] + elif 'SingleServerConfig' in config: + scfg = config['SingleServerConfig'] + if scfg.get('playerHardCap') is not None: + kv['PlayerHardCap'] = scfg['playerHardCap'] + if kv: + _update_ini_section(map_name, kv) + + return result, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 + + @app.route('/api/director/clear_config', methods=['POST']) + def director_clear_config(): + try: + import urllib.request + map_name = request.get_data(as_text=True).strip() + req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearMapConfigOverrides", data=map_name.encode(), headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(req, timeout=30) as resp: + result = resp.read().decode() + if map_name: + _update_ini_section(map_name, {}, remove_section=True) + return result, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 + + @app.route('/api/director/character_transfer', methods=['GET']) + def director_character_transfer_get(): + try: + import urllib.request + req = urllib.request.Request(f"{director_base}/v0/BattlegroupFetchCharacterTransferRules") + with urllib.request.urlopen(req, timeout=15) as resp: + data = resp.read().decode() + return data, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 + + @app.route('/api/director/character_transfer', methods=['POST']) + def director_character_transfer_update(): + try: + import urllib.request + config = request.get_json() + req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateCharacterTransferSettings", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(req, timeout=30) as resp: + result = resp.read().decode() + + kv = {} + if 'ForceIsWorldClosed' in config: + kv['ForceIsWorldClosed'] = str(config['ForceIsWorldClosed']) + if 'ForceIsWorldClosingSoon' in config: + kv['ForceIsWorldClosingSoon'] = str(config['ForceIsWorldClosingSoon']) + if kv: + _update_ini_section('CharacterTransfers', kv) + + return result, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 + + @app.route('/api/director/character_transfer_clear', methods=['POST']) + def director_character_transfer_clear(): + try: + import urllib.request + req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearCharacterTransferOverrides", method='POST') + with urllib.request.urlopen(req, timeout=30) as resp: + result = resp.read().decode() + + _update_ini_section('CharacterTransfers', {}, remove_section=True) + + return result, 200, {'Content-Type': 'application/json'} + except Exception as e: + return jsonify({'success': False, 'error': str(e)}), 500 diff --git a/app/routes/auth.py b/app/routes/auth.py new file mode 100644 index 0000000..97acb4c --- /dev/null +++ b/app/routes/auth.py @@ -0,0 +1,50 @@ +"""Authentication routes - login, logout""" + +from flask import Blueprint, render_template, request, redirect, url_for, flash +from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user + +login_manager = LoginManager() +login_manager.login_view = 'auth.login' +login_manager.login_message = 'Please log in to access the dashboard.' + + +class AdminUser(UserMixin): + def __init__(self, username): + self.id = username + + +def init_auth(app, settings): + login_manager.init_app(app) + + @login_manager.user_loader + def load_user(user_id): + auth_settings = settings.get('auth', {}) + if auth_settings.get('username') == user_id: + return AdminUser(user_id) + return None + + @app.route('/login', methods=['GET', 'POST']) + def login(): + if current_user.is_authenticated: + return redirect(url_for('overview')) + + if request.method == 'POST': + username = request.form.get('username', '') + password = request.form.get('password', '') + auth_settings = settings.get('auth', {}) + + if username == auth_settings.get('username') and password == auth_settings.get('password'): + user = AdminUser(username) + login_user(user) + next_page = request.args.get('next') + return redirect(next_page or url_for('overview')) + else: + flash('Invalid username or password', 'error') + + return render_template('login.html') + + @app.route('/logout') + @login_required + def logout(): + logout_user() + return redirect(url_for('login')) diff --git a/app/routes/main.py b/app/routes/main.py new file mode 100644 index 0000000..4946551 --- /dev/null +++ b/app/routes/main.py @@ -0,0 +1,438 @@ +"""Main route blueprints""" + +import json +import logging +from flask import Blueprint, render_template, request, jsonify +from flask_login import login_required, current_user +from app.utils.constants import NAV_PAGES, GUILD_ROLES + +logger = logging.getLogger(__name__) + + +def register_routes(app, services, settings): + db = services['db'] + ssh = services['ssh'] + k8s = services['k8s'] + player_svc = services['player'] + vehicle_svc = services['vehicle'] + chat_svc = services['chat'] + admin_svc = services['admin'] + static_cache = services['static_cache'] + + def fmt_role(role_id): + return GUILD_ROLES.get(role_id, f'Role {role_id}') + + def get_static_data(): + current_time = __import__('datetime').datetime.now().timestamp() + cached = static_cache.get('static_data') + if cached and (current_time - cached['timestamp']) < settings['cache']['static_data_ttl']: + return cached + + data = { + 'factions': db.query("SELECT id, name FROM dune.factions ORDER BY id") or [], + 'guilds': db.query("SELECT guild_id, guild_name FROM dune.guilds ORDER BY guild_name") or [], + 'maps': db.query("SELECT DISTINCT map FROM dune.actors WHERE class LIKE %s AND map IS NOT NULL ORDER BY map", ['%DunePlayerCharacter_C']) or [], + 'keystones': db.query("SELECT id, name FROM dune.specialization_keystones_map ORDER BY id") or [], + 'timestamp': current_time, + } + static_cache.set('static_data', data) + logger.info("Static data cache refreshed") + return data + + @app.context_processor + def inject_globals(): + conn_ok = db.check_health() + return dict( + nav_pages=NAV_PAGES, + current_path=request.path if request else '/', + fmt_role=fmt_role, + conn_ok=conn_ok, + current_user=current_user, + ) + + @app.template_filter('inv_label') + def inv_label_filter(inv_type): + from app.utils.constants import INVENTORY_TYPE_LABELS + if inv_type is None: + return 'Unknown' + return INVENTORY_TYPE_LABELS.get(inv_type, f'Type {inv_type}') + + @app.template_filter('currency_label') + def currency_label_filter(currency_id): + from app.utils.constants import CURRENCY_ID_LABELS + return CURRENCY_ID_LABELS.get(currency_id, f'Currency {currency_id}') + + @app.template_filter('class_name') + def class_name_filter(s): + if not s: + return '' + short = s.split('/')[-1] if '/' in s else s + if short.endswith('_C'): + short = short[:-2] + if '.' in short: + short = short.split('.')[-1] + return short + + @app.template_filter('truncate') + def truncate_filter(s, length=100): + if s and len(s) > length: + return s[:length] + '...' + return s or '' + + @app.template_filter('json_format') + def json_format_filter(val): + if val is None: + return '' + if isinstance(val, dict): + return json.dumps(val, indent=2, ensure_ascii=False) + return str(val) + + @app.template_filter('format_number') + def format_number_filter(val): + if val is None: + return '0' + try: + n = int(val) + return f'{n:,}' + except (ValueError, TypeError): + return str(val) + + # Health check + @app.route('/health') + def health_check(): + health = {'status': 'healthy', 'checks': {}} + port_ok = __import__('socket').socket(__import__('socket').AF_INET, __import__('socket').SOCK_STREAM).connect_ex(('127.0.0.1', settings['database']['port'])) == 0 + health['checks']['ssh_tunnel'] = 'ok' if port_ok else 'down' + if not port_ok: + health['status'] = 'degraded' + health['checks']['database'] = 'unknown' + return jsonify(health), 503 + + if db.check_health(): + health['checks']['database'] = 'ok' + else: + health['status'] = 'unhealthy' + health['checks']['database'] = 'connection failed' + return jsonify(health), 503 + return jsonify(health) + + # Overview + @app.route('/') + def overview(): + try: + counts = player_svc.get_overview_counts() + data = { + 'faction_dist': player_svc.get_faction_distribution(), + 'per_map': player_svc.get_players_per_map(), + 'players_online': player_svc.get_players_online(), + } + data.update(counts or {}) + return render_template('overview.html', **data) + except Exception as e: + logger.exception("Error in overview route") + return render_template('overview.html', db_error=f"{type(e).__name__}: {e}") + + # Players list + @app.route('/players') + def players(): + try: + search = request.args.get('search', '') + faction_id = request.args.get('faction', '') + guild_id = request.args.get('guild', '') + map_filter = request.args.get('map', '') + online_filter = request.args.get('online', '') + + players_list = player_svc.get_players_list( + search=search, faction_id=faction_id, guild_id=guild_id, + map_filter=map_filter, online_filter=online_filter + ) + + static_data = get_static_data() + return render_template('players.html', + players=players_list, factions=static_data['factions'], + guilds=static_data['guilds'], maps=static_data['maps'], + search=search, sel_faction=faction_id, sel_guild=guild_id, + sel_map=map_filter, sel_online=online_filter) + except Exception as e: + logger.exception("Error in players route") + return render_template('players.html', db_error=f"{type(e).__name__}: {e}") + + # Player detail + @app.route('/players/') + def player_detail(player_id): + try: + player = player_svc.get_player_detail(player_id) + if not player: + return render_template('player_detail.html', not_found=True) + + player_controller_id = player.get('player_controller_id') + + vitals = player_svc.get_player_vitals(player.get('state_pawn_id')) + guild = player_svc.get_player_guild(player_controller_id) + player_vehicles = player_svc.get_player_vehicles(player_controller_id) + buildings_result = player_svc.get_player_buildings(player_id) + currency = player_svc.get_player_currency(player_controller_id) + inventories = player_svc.get_player_inventories(player_id) + landclaims = player_svc.get_player_landclaims(player.get('owner_account_id')) + specialization = player_svc.get_player_specialization(player_controller_id) + tech_knowledge = player_svc.get_player_tech_knowledge(player_id) + purchased_keystones = player_svc.get_player_keystones(player_controller_id) + faction_reputation = player_svc.get_player_faction_reputation(player_controller_id) + landsraad_info = player_svc.get_player_landsraad(player_controller_id) + + is_online = player_svc.is_online(player_controller_id) if player_controller_id else False + + static_data = get_static_data() + + return render_template('player_detail.html', + player=player, guild=guild, vehicles=player_vehicles, + buildings=buildings_result, currency=currency, + inventories=inventories, landclaims=landclaims, + specialization=specialization, tech_knowledge=tech_knowledge, + purchased_keystones=purchased_keystones, all_keystones=static_data['keystones'], + faction_reputation=faction_reputation, landsraad_info=landsraad_info, + vitals=vitals, is_online=is_online) + except Exception as e: + logger.exception("Error in player_detail route") + return render_template('player_detail.html', db_error=f"{type(e).__name__}: {e}") + + # Vehicles + @app.route('/vehicles') + def vehicles(): + try: + vehicles_list = vehicle_svc.get_all_vehicles() + return render_template('vehicles.html', vehicles=vehicles_list) + except Exception as e: + logger.exception("Error in vehicles route") + return render_template('vehicles.html', db_error=f"{type(e).__name__}: {e}") + + # Vehicle detail + @app.route('/vehicles/') + def vehicle_detail(vehicle_id): + try: + vehicle = vehicle_svc.get_vehicle(vehicle_id) + if not vehicle: + return render_template('vehicle_detail.html', not_found=True) + + modules = vehicle_svc.get_vehicle_modules(vehicle_id) + from app.services.vehicle import parse_vehicle_modules + parsed_modules = parse_vehicle_modules(modules, vehicle.get('class', '')) + + return render_template('vehicle_detail.html', vehicle=vehicle, modules=parsed_modules) + except Exception as e: + logger.exception("Error in vehicle_detail route") + return render_template('vehicle_detail.html', db_error=f"{type(e).__name__}: {e}") + + # Guilds + @app.route('/guilds') + def guilds(): + try: + guilds_list = db.query(""" + SELECT g.*, f.name as faction_name, + (SELECT COUNT(*)::int FROM dune.guild_members gm WHERE gm.guild_id = g.guild_id) as member_count, + (SELECT COUNT(*)::int FROM dune.guild_members gm + JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id + WHERE gm.guild_id = g.guild_id AND ps.online_status::text = 'Online') as online_count + FROM dune.guilds g + LEFT JOIN dune.factions f ON g.guild_faction = f.id + ORDER BY g.guild_name + """) or [] + return render_template('guilds.html', guilds=guilds_list) + except Exception as e: + logger.exception("Error in guilds route") + return render_template('guilds.html', db_error=f"{type(e).__name__}: {e}") + + # Guild detail + @app.route('/guilds/') + def guild_detail(guild_id): + try: + guild = db.query(""" + SELECT g.*, f.name as faction_name + FROM dune.guilds g + LEFT JOIN dune.factions f ON g.guild_faction = f.id + WHERE g.guild_id = %s + """, [guild_id], one=True) + if not guild: + return render_template('guild_detail.html', not_found=True) + + members = db.query(""" + SELECT ps.player_pawn_id as actor_id, ea.user as account_email, gm.role_id, + COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || ps.player_pawn_id::text) as player_name, + ps.online_status::text as online_status, + ps.player_controller_id, + pawn_a.map as player_map, + CASE WHEN pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving' = 'True' THEN TRUE ELSE FALSE END as is_driving, + vehicle_a.class as driving_vehicle_class + FROM dune.guild_members gm + JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id + JOIN dune.encrypted_accounts ea ON ps.account_id = ea.id + LEFT JOIN dune.accounts acc ON ea.id = acc.id + LEFT JOIN dune.actors pawn_a ON ps.player_pawn_id = pawn_a.id + LEFT JOIN dune.actors vehicle_a ON pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_CurrentVehicleId' = CONCAT('!!act#', vehicle_a.id::text) + AND (pawn_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving')::boolean = TRUE + WHERE gm.guild_id = %s + ORDER BY gm.role_id DESC, player_name + """, [guild_id]) or [] + + return render_template('guild_detail.html', guild=guild, members=members) + except Exception as e: + logger.exception("Error in guild_detail route") + return render_template('guild_detail.html', db_error=f"{type(e).__name__}: {e}") + + # Buildings + @app.route('/buildings') + def buildings(): + try: + buildings_list = db.query(""" + SELECT a.id, a.class, a.map, a.transform::text as transform_text, + COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'ID:' || b.owner_id::text) as owner_name, + (SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count, + a.properties->>'m_bIsPowered' as is_powered, + a.properties->>'m_PowerLevel' as power_level, + a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id + FROM dune.buildings b + JOIN dune.actors a ON b.id = a.id + LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id + LEFT JOIN dune.encrypted_accounts ea ON ea.id = ( + SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1 + ) + ORDER BY owner_name + LIMIT 200 + """) or [] + return render_template('buildings.html', buildings=buildings_list) + except Exception as e: + logger.exception("Error in buildings route") + return render_template('buildings.html', db_error=f"{type(e).__name__}: {e}") + + # Events + @app.route('/events') + def events_page(): + game_events = [] + event_logs = [] + try: + game_events = db.query("SELECT id, event_type, actor_id, actor_name, map, universe_time, x, y, z FROM dune.game_events ORDER BY universe_time DESC LIMIT 50") or [] + except Exception as e: + logger.error(f"Error fetching game_events: {e}") + try: + event_logs = db.query("SELECT id, event_type, category, function_name, message, event_time, meta FROM dune.event_log ORDER BY event_time DESC LIMIT 100") or [] + except Exception as e: + logger.error(f"Error fetching event_logs: {e}") + return render_template('events.html', game_events=game_events, event_logs=event_logs) + + # Chat + @app.route('/chat') + def chat_logs(): + return render_template('chat.html', max_lines=200) + + # Shell + @app.route('/shell') + def shell_page(): + pods = [] + ssh_command = '' + namespace = settings['kubernetes']['namespace'] + try: + out, err, rc = ssh.run(f'sudo kubectl get pods -n {namespace} -o custom-columns=NAME:.metadata.name,ROLE:.metadata.labels.role,STATUS:.status.phase') + if out: + for line in out.strip().split('\n')[1:]: + parts = line.split() + if len(parts) >= 3: + pods.append({'name': parts[0], 'role': parts[1] if parts[1] != '' else '', 'status': parts[2]}) + + ssh_key = settings['server'].get('ssh_key') + if ssh_key: + ssh_command = f'ssh -i "{ssh_key}" {settings["server"]["user"]}@{settings["server"]["host"]}' + except Exception: + pass + + return render_template('shell.html', pods=pods, ssh_command=ssh_command, namespace=namespace) + + # Files (stub) + @app.route('/files') + def files_page(): + return render_template('files.html') + + @app.route('/files/view') + def files_view(): + path = request.args.get('path', '') + return render_template('file_view.html', path=path) + + # Director + @app.route('/director') + def director_page(): + director_port = settings.get('director', {}).get('port', 32479) + return render_template('director.html', director_port=director_port) + + # Admin + @app.route('/admin') + def admin_page(): + try: + bans = admin_svc.get_bans() + except Exception: + bans = [] + return render_template('admin.html', bans=bans) + + # Server status + @app.route('/server') + def server_status(): + try: + active_servers = db.query(""" + SELECT a.server_id, w.map + FROM dune.active_server_ids a + LEFT JOIN dune.world_partition w ON a.server_id = w.server_id + ORDER BY w.map, a.server_id + """) or [] + per_map = player_svc.get_players_per_map() + online_players = db.query( + "SELECT ps.character_name, a.map, ps.online_status::text as online_status, " + "ps.life_state::text as life_state, ps.last_login_time, ps.last_avatar_activity " + "FROM dune.player_state ps " + "JOIN dune.actors a ON ps.player_pawn_id = a.id " + "WHERE ps.online_status::text = 'Online' " + "ORDER BY ps.character_name" + ) or [] + partitions = db.query("SELECT * FROM dune.world_partition ORDER BY map, partition_id LIMIT 50") or [] + overmap_count = db.query("SELECT COUNT(*) c FROM dune.overmap_players", one=True) + online_count = db.query("SELECT COUNT(*) c FROM dune.player_state WHERE online_status::text = 'Online'", one=True) + + deployments = k8s.get_deployments() + node_metrics = k8s.get_node_metrics() + + for p in partitions: + sid = (p.get('server_id') or '').lower().replace('_', '-') + p['deployment'] = '' + mp = (p.get('map') or '').lower().replace('_', '-') + + for d in deployments: + short = d.replace('deployment.apps/', '') + if sid and sid in short.lower(): + p['deployment'] = d + break + if mp and mp in short.lower(): + p['deployment'] = d + break + + if not p['deployment']: + mid = '-sg-' + sid + for d in deployments: + short = d.replace('deployment.apps/', '') + if mid in short.lower(): + p['deployment'] = d + break + + if not p['deployment'] and mp: + for d in deployments: + short = d.replace('deployment.apps/', '') + if mp in short.lower() and 'pod' in short.lower(): + p['deployment'] = d + break + + return render_template('server.html', + active_servers=active_servers, per_map=per_map, + online_players=online_players, partitions=partitions, + overmap_count=overmap_count.get('c') if overmap_count else 0, + online_count=online_count.get('c') if online_count else 0, + deployments=deployments, deploys_ok=True, ssh_error='', + node_metrics=node_metrics) + except Exception as e: + logger.exception("Error in server_status route") + return render_template('server.html', db_error=f"{type(e).__name__}: {e}") diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..e372604 --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1 @@ +"""Services package""" diff --git a/app/services/admin.py b/app/services/admin.py new file mode 100644 index 0000000..cc5a207 --- /dev/null +++ b/app/services/admin.py @@ -0,0 +1,393 @@ +"""Admin service - ban, kick, unban, vitals, IP detection""" + +import re +import time +import threading +import logging + +logger = logging.getLogger(__name__) + + +class AdminService: + def __init__(self, db_service, ssh_service): + self.db = db_service + self.ssh = ssh_service + + def ban_player(self, player_id, duration=0, reason='', note=''): + try: + duration_int = int(duration) if duration else 0 + except (ValueError, TypeError): + duration_int = 0 + + player_row = self.db.query( + "SELECT ps.account_id, ps.character_name FROM dune.player_state ps WHERE ps.player_controller_id = %s", + [player_id], one=True + ) + + account_id = player_row.get('account_id') if player_row else None + player_name = player_row.get('character_name', 'Unknown') if player_row else 'Unknown' + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + + if account_id: + if duration_int == 0: + cur.execute(""" + INSERT INTO dune.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) + VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE) + ON CONFLICT (player_id) DO UPDATE SET + account_id = EXCLUDED.account_id, reason = EXCLUDED.reason, + note = EXCLUDED.note, duration = EXCLUDED.duration, + banned_at = NOW(), expires_at = NULL, active = TRUE + """, [player_id, account_id, reason, note, duration_int]) + else: + cur.execute(""" + INSERT INTO dune.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active) + VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE) + ON CONFLICT (player_id) DO UPDATE SET + account_id = EXCLUDED.account_id, reason = EXCLUDED.reason, + note = EXCLUDED.note, duration = EXCLUDED.duration, + banned_at = NOW(), expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE + """, [player_id, account_id, reason, note, duration_int, duration_int, duration_int]) + else: + if duration_int == 0: + cur.execute(""" + INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active) + VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE) + ON CONFLICT (player_id) DO UPDATE SET + reason = EXCLUDED.reason, note = EXCLUDED.note, + duration = EXCLUDED.duration, banned_at = NOW(), + expires_at = NULL, active = TRUE + """, [player_id, reason, note, duration_int]) + else: + cur.execute(""" + INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active) + VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE) + ON CONFLICT (player_id) DO UPDATE SET + reason = EXCLUDED.reason, note = EXCLUDED.note, + duration = EXCLUDED.duration, banned_at = NOW(), + expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE + """, [player_id, reason, note, duration_int, duration_int, duration_int]) + + conn.commit() + return True, f"Player {player_name} banned for {duration_int} minutes" + except Exception as e: + logger.error(f"Failed to ban player {player_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def unban_player(self, player_id): + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("DELETE FROM dune.bans WHERE player_id = %s", [player_id]) + conn.commit() + + cur.execute("SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s", [player_id]) + account_row = cur.fetchone() + account_id = account_row[0] if account_row else None + + ips_to_unblock = [] + if account_id: + all_ips = self.db.query(""" + SELECT ip_address FROM dune.player_ips + WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s) + """, [account_id]) or [] + ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')] + else: + ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True) + if ip_row and ip_row.get('ip_address'): + ips_to_unblock.append(ip_row.get('ip_address')) + + cur.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id]) + conn.commit() + + for ip in ips_to_unblock: + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') + + return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)." + except Exception as e: + logger.error(f"Failed to unban player {player_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def kick_player(self, player_id): + player = self.db.query(""" + SELECT ps.character_name, a.map FROM dune.player_state ps + JOIN dune.actors a ON ps.player_pawn_id = a.id + WHERE ps.player_controller_id = %s + """, [player_id], one=True) + + if not player: + return False, "Player not found" + + player_name = player.get('character_name', 'Unknown') + ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True) + player_ip = ip_row.get('ip_address') if ip_row else None + + if not player_ip: + return False, "Player IP not known. Detect IPs first." + + def temporary_block(ip): + self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') + time.sleep(60) + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP') + + thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True) + thread.start() + + self.db.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip]) + + return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)" + + def edit_vitals(self, pawn_id, current_health=None, max_health=None, current_hydration=None, current_spice=None): + if pawn_id is None or current_hydration is None or current_spice is None: + return False, "Missing parameters" + + controller_row = self.db.query( + "SELECT player_controller_id FROM dune.player_state WHERE player_pawn_id = %s LIMIT 1", + [pawn_id], one=True + ) + if controller_row: + from app.services.player import PlayerService + ps = PlayerService(self.db) + if ps.is_online(controller_row['player_controller_id']): + return False, "Player must be offline to edit vitals. Log out first." + + health = max(0.0, float(current_health)) if current_health is not None else None + max_h = max(0.0, float(max_health)) if max_health is not None else None + hydration = max(0.0, float(current_hydration)) + spice = max(0.0, float(current_spice)) + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + if health is not None: + cur.execute( + "UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)) WHERE id = %s", + [health, pawn_id] + ) + if max_h is not None: + cur.execute( + "UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)) WHERE id = %s", + [max_h, pawn_id] + ) + cur.execute( + "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] + ) + conn.commit() + return True, {"health": health, "max_health": max_h, "hydration": hydration, "spice": spice} + except Exception as e: + logger.error(f"Failed to edit vitals for pawn {pawn_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def detect_player_ips(self, namespace): + out, err, rc = self.ssh.run(f'sudo kubectl get pods -n {namespace} -o name 2>/dev/null') + if rc != 0 or not out: + return False, "Failed to list pods" + + game_pods = [] + for line in out.strip().split('\n'): + pod = line.replace('pod/', '').strip() + if '-sg-' in pod and '-pod-' in pod: + map_name = pod.split('-sg-')[-1].split('-pod-')[0] if '-sg-' in pod else 'Unknown' + game_pods.append((pod, map_name)) + + if not game_pods: + return False, "No game server pods found" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + updated = 0 + try: + cur = conn.cursor() + + for pod_name, map_name in game_pods: + cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- find /home/dune -name "*.log" -path "*/Logs/*" 2>/dev/null | head -5' + out_logs, err_logs, rc_logs = self.ssh.run(cmd) + if not out_logs: + continue + + log_files = [l.strip() for l in out_logs.strip().split('\n') if l.strip()] + for log_file in log_files: + cat_cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- cat "{log_file}" 2>/dev/null' + out, err, rc = self.ssh.run(cat_cmd) + if not out: + continue + + ip_to_player = {} + current_ip = None + + for line in out.split('\n'): + ip_match = re.search(r'RemoteAddr:\s*([0-9.]+):(\d+)', line) + if ip_match: + current_ip = ip_match.group(1) + continue + + if 'Login request:' in line and current_ip: + name_match = re.search(r'Name=([^?#]+)', line) + if name_match: + current_player = name_match.group(1).split('#')[0] + if current_player and current_ip and current_ip != '65.21.198.100': + ip_to_player[current_ip] = current_player + current_ip = None + + if ip_to_player: + for ip, name in ip_to_player.items(): + cur.execute(""" + SELECT ps.player_controller_id, ps.account_id + FROM dune.player_state ps + JOIN dune.accounts a ON ps.account_id = a.id + WHERE a.funcom_id = %s OR ps.character_name = %s + LIMIT 1 + """, [name, name]) + row = cur.fetchone() + if row: + pid = row[0] + account_id = row[1] + cur.execute(""" + INSERT INTO dune.player_ips (player_id, ip_address, updated_at) + VALUES (%s, %s, NOW()) + ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW() + """, [pid, ip]) + updated += 1 + + ban_check = self.db.query(""" + SELECT player_id FROM dune.bans + WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL) + LIMIT 1 + """, [pid, account_id], one=True) + + if ban_check: + self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') + + conn.commit() + return True, f"Updated {updated} player IPs from game logs" + except Exception as e: + logger.error(f"Failed to detect player IPs: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def set_player_ip(self, player_id, ip_address): + return self.db.execute(""" + INSERT INTO dune.player_ips (player_id, ip_address, updated_at) + VALUES (%s, %s, NOW()) + ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW() + """, [player_id, ip_address]) + + def emergency_unban(self, ip): + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') + return True, f"Unblocked {ip}" + + def get_bans(self, limit=50): + return self.db.query(""" + SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name + FROM dune.bans b + LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id + ORDER BY b.banned_at DESC + LIMIT %s + """, [limit]) or [] + + def get_player_ban(self, player_id): + return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dune.bans WHERE player_id = %s", [player_id], one=True) + + def get_player_history(self, player_id, limit=20): + return self.db.query(""" + SELECT action_type, reason, note, duration_minutes, created_at, ip_address + FROM dune.player_actions + WHERE player_id = %s + ORDER BY created_at DESC + LIMIT %s + """, [player_id, limit]) or [] + + def create_indexes(self): + indexes = [ + ("idx_actors_class", "CREATE INDEX IF NOT EXISTS idx_actors_class ON dune.actors (class)"), + ("idx_actors_map", "CREATE INDEX IF NOT EXISTS idx_actors_map ON dune.actors (map)"), + ("idx_actors_owner_account", "CREATE INDEX IF NOT EXISTS idx_actors_owner_account ON dune.actors (owner_account_id)"), + ("idx_player_state_controller", "CREATE INDEX IF NOT EXISTS idx_player_state_controller ON dune.player_state (player_controller_id)"), + ("idx_player_state_pawn", "CREATE INDEX IF NOT EXISTS idx_player_state_pawn ON dune.player_state (player_pawn_id)"), + ("idx_player_state_account", "CREATE INDEX IF NOT EXISTS idx_player_state_account ON dune.player_state (account_id)"), + ("idx_player_state_online", "CREATE INDEX IF NOT EXISTS idx_player_state_online ON dune.player_state (online_status)"), + ("idx_guild_members_player", "CREATE INDEX IF NOT EXISTS idx_guild_members_player ON dune.guild_members (player_id)"), + ("idx_guild_members_guild", "CREATE INDEX IF NOT EXISTS idx_guild_members_guild ON dune.guild_members (guild_id)"), + ("idx_player_faction_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_actor ON dune.player_faction (actor_id)"), + ("idx_permission_actor_rank_player", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_player ON dune.permission_actor_rank (player_id)"), + ("idx_permission_actor_rank_actor", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_actor ON dune.permission_actor_rank (permission_actor_id)"), + ("idx_buildings_owner", "CREATE INDEX IF NOT EXISTS idx_buildings_owner ON dune.buildings (owner_id)"), + ("idx_inventories_actor", "CREATE INDEX IF NOT EXISTS idx_inventories_actor ON dune.inventories (actor_id)"), + ("idx_items_inventory", "CREATE INDEX IF NOT EXISTS idx_items_inventory ON dune.items (inventory_id)"), + ("idx_specialization_tracks_player", "CREATE INDEX IF NOT EXISTS idx_specialization_tracks_player ON dune.specialization_tracks (player_id)"), + ("idx_player_faction_reputation_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_reputation_actor ON dune.player_faction_reputation (actor_id)"), + ("idx_player_virtual_currency_controller", "CREATE INDEX IF NOT EXISTS idx_player_virtual_currency_controller ON dune.player_virtual_currency_balances (player_controller_id)"), + ] + + created = [] + conn = self.db.get_connection() + if not conn: + return False, [], "Database connection failed" + cur = None + try: + cur = conn.cursor() + for name, sql in indexes: + try: + cur.execute(sql) + created.append(name) + except Exception as e: + logger.warning(f"Index {name} failed: {e}") + conn.commit() + return True, created, None + except Exception as e: + logger.error(f"Failed to create indexes: {e}") + if conn: + conn.rollback() + return False, [], str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) diff --git a/app/services/chat.py b/app/services/chat.py new file mode 100644 index 0000000..77d56c4 --- /dev/null +++ b/app/services/chat.py @@ -0,0 +1,156 @@ +"""Chat service - chat history and log parsing""" + +import json +import datetime +import logging + +logger = logging.getLogger(__name__) + + +class ChatService: + def __init__(self, db_service, k8s_service, ssh_service, cache): + self.db = db_service + self.k8s = k8s_service + self.ssh = ssh_service + self.cache = cache + self.ensured_table = False + + def ensure_history_table(self): + if self.ensured_table: + return True + try: + self.db.execute(""" + CREATE TABLE IF NOT EXISTS dune.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("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dune.chat_history (timestamp DESC)") + self.ensured_table = True + logger.info("Chat history table ready") + return True + except Exception as e: + logger.error(f"Failed to create chat history table: {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(""" + INSERT INTO dune.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 save_messages_batch(self, messages): + if not messages: + return 0 + conn = self.db.get_connection() + if not conn: + return 0 + cur = None + try: + cur = conn.cursor() + for msg in messages: + cur.execute(""" + INSERT INTO dune.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + """, [ + msg['channel'], msg['sender'], msg['message'], + msg.get('target', ''), + msg.get('location', {}).get('X', 0), + msg.get('location', {}).get('Y', 0), + msg.get('location', {}).get('Z', 0), + msg.get('is_admin', False) + ]) + conn.commit() + return len(messages) + except Exception as e: + logger.error(f"Failed to save chat messages batch: {e}") + if conn: + conn.rollback() + return 0 + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def get_history(self, limit=200): + return self.db.query(""" + SELECT id, timestamp, channel, sender, message, target, + location_x, location_y, location_z, is_admin + FROM dune.chat_history + ORDER BY timestamp DESC + LIMIT %s + """, [limit]) + + def catch_up(self, namespace): + db_messages = self.get_history(1) + has_history = db_messages and len(db_messages) >= 10 + if has_history: + 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 + + out, err, rc = self.ssh.run( + f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null | " + "grep 'CLOG.*TextChat' | grep -v 'Starting filtering' | grep -v 'Skipping filtering' | grep -v 'Redirected message'", + timeout=30 + ) + + messages = [] + seen = set() + for line in (out or '').strip().split('\n'): + 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_messages_batch(messages) + logger.info(f"Caught up {saved} chat messages from pod logs") + return saved + return 0 diff --git a/app/services/database.py b/app/services/database.py new file mode 100644 index 0000000..969c119 --- /dev/null +++ b/app/services/database.py @@ -0,0 +1,174 @@ +"""Database service - connection pool and query helpers""" + +import logging +import psycopg2 +import psycopg2.extras +import psycopg2.pool + +logger = logging.getLogger(__name__) + + +class DatabaseService: + def __init__(self, db_config, min_conn=2, max_conn=10): + self.db_config = db_config + self.min_conn = min_conn + self.max_conn = max_conn + self.pool = None + + def init_pool(self): + if self.pool is None: + try: + self.pool = psycopg2.pool.ThreadedConnectionPool( + minconn=self.min_conn, + maxconn=self.max_conn, + **self.db_config + ) + logger.info("Database connection pool initialized") + except Exception as e: + logger.error(f"Failed to initialize database pool: {e}") + self.pool = None + return self.pool + + def get_connection(self): + try: + pool = self.init_pool() + if pool: + return pool.getconn() + return psycopg2.connect(**self.db_config) + except Exception as e: + logger.error(f"Failed to get database connection: {e}") + return None + + def return_connection(self, conn): + if conn and self.pool and hasattr(conn, 'poll'): + try: + self.pool.putconn(conn) + except Exception: + try: + conn.close() + except Exception: + pass + + def close_all(self): + if self.pool: + try: + self.pool.closeall() + except Exception as e: + logger.error(f"Error closing pool: {e}") + self.pool = None + + def query(self, sql, params=None, one=False): + conn = self.get_connection() + if not conn: + return {} if one else [] + cur = None + try: + cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) + cur.execute(sql, params) + rows = cur.fetchall() + if one and rows: + return rows[0] + if one: + return {} + return rows + except Exception as e: + logger.error(f"Database query error: {e}") + raise + finally: + if cur: + cur.close() + self.return_connection(conn) + + def execute(self, sql, params=None, commit=True): + conn = self.get_connection() + if not conn: + return False + cur = None + try: + cur = conn.cursor() + cur.execute(sql, params) + if commit: + conn.commit() + return True + except Exception as e: + logger.error(f"Database execute error: {e}") + if conn: + conn.rollback() + return False + finally: + if cur: + cur.close() + self.return_connection(conn) + + def execute_with_conn(self, conn, sql, params=None): + cur = conn.cursor() + try: + cur.execute(sql, params) + return cur + except Exception: + conn.rollback() + raise + + def check_health(self): + try: + conn = self.get_connection() + if not conn: + return False + cur = conn.cursor() + cur.execute('SELECT 1') + cur.fetchone() + cur.close() + self.return_connection(conn) + return True + except Exception: + return False + + def ensure_tables(self): + conn = self.get_connection() + if not conn: + return + cur = None + try: + cur = conn.cursor() + cur.execute(""" + CREATE TABLE IF NOT EXISTS dune.player_ips ( + player_id BIGINT PRIMARY KEY, + ip_address INET NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT NOW() + ) + """) + cur.execute(""" + CREATE TABLE IF NOT EXISTS dune.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 + ) + """) + cur.execute(""" + CREATE TABLE IF NOT EXISTS dune.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() + ) + """) + conn.commit() + logger.info("Dashboard tables ensured (player_ips, bans, player_actions)") + except Exception as e: + logger.warning(f"Failed to ensure dashboard tables: {e}") + if conn: + conn.rollback() + finally: + if cur: + cur.close() + self.return_connection(conn) diff --git a/app/services/k8s.py b/app/services/k8s.py new file mode 100644 index 0000000..d982297 --- /dev/null +++ b/app/services/k8s.py @@ -0,0 +1,77 @@ +"""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}' + return self.ssh.run(full_cmd, timeout=timeout) + + def get_pods(self): + out, err, rc = self.run('get pods -o name') + if rc != 0: + logger.error(f"Failed to get pods: {err}") + return [] + return [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()] + + 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 + pod = self.find_pod_by_pattern('router') + return pod + + def get_rabbitmq_pod(self): + pod = self.find_pod_by_pattern('mq-admin') + if pod: + return pod + pod = self.find_pod_by_pattern('mq-game') + return pod + + def get_deployments(self): + out, err, rc = self.run('get deployments -o name') + if rc != 0: + return [] + return [d.strip() for d in (out or '').strip().split('\n') if d.strip()] + + 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 {} + + 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(f"Auto-detected K8s namespace: {ns}") + self.namespace = ns + return ns + return None diff --git a/app/services/player.py b/app/services/player.py new file mode 100644 index 0000000..5f1d041 --- /dev/null +++ b/app/services/player.py @@ -0,0 +1,339 @@ +"""Player service - player queries and operations""" + +import logging + +logger = logging.getLogger(__name__) + +LIKE_PC = '%DunePlayerCharacter_C' + + +class PlayerService: + def __init__(self, db_service): + self.db = db_service + + def is_online(self, player_controller_id): + result = self.db.query( + "SELECT 1 FROM dune.player_state WHERE player_controller_id = %s AND online_status::text = 'Online' LIMIT 1", + [player_controller_id], + one=True + ) + return bool(result) + + def get_overview_counts(self): + return self.db.query(""" + SELECT + (SELECT COUNT(*) FROM dune.accounts) as account_count, + (SELECT COUNT(*) FROM dune.player_state) as player_count, + (SELECT COUNT(*) FROM dune.vehicles) as vehicle_count, + (SELECT COUNT(*) FROM dune.buildings) as building_count, + (SELECT COUNT(*) FROM dune.guilds) as guild_count, + (SELECT COUNT(*) FROM dune.actors) as actor_count, + (SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') as online_count + """, one=True) + + def get_faction_distribution(self): + return self.db.query(""" + SELECT f.name, COUNT(pf.actor_id)::int count + FROM dune.player_faction pf + JOIN dune.factions f ON pf.faction_id = f.id + GROUP BY f.name + ORDER BY count DESC + """) + + def get_players_per_map(self): + return self.db.query(""" + SELECT a.map, COUNT(*)::int as count + FROM dune.player_state ps + JOIN dune.actors a ON ps.player_pawn_id = a.id + WHERE a.class LIKE %s AND a.map IS NOT NULL + GROUP BY a.map + ORDER BY count DESC + """, [LIKE_PC]) + + def get_players_online(self): + return self.db.query(""" + SELECT ps.character_name, ps.player_pawn_id as pawn_id, a.map, + ps.online_status::text as online_status + FROM dune.player_state ps + JOIN dune.actors a ON ps.player_pawn_id = a.id + WHERE ps.online_status::text = 'Online' + ORDER BY ps.character_name + """) + + def get_players_list(self, search='', faction_id='', guild_id='', map_filter='', online_filter='', limit=200): + where = ["a.class LIKE %s"] + params = [LIKE_PC] + + if search: + where.append("""( + ps.character_name ILIKE %s + OR acc.funcom_id ILIKE %s + OR ea.user ILIKE %s + OR a.properties::text ILIKE %s + )""") + params.extend([f'%{search}%'] * 4) + if faction_id: + where.append("pf.faction_id = %s") + params.append(faction_id) + if guild_id: + where.append("gm.guild_id = %s") + params.append(guild_id) + if map_filter: + where.append("a.map = %s") + params.append(map_filter) + if online_filter == 'online': + where.append("ps.online_status::text = 'Online'") + elif online_filter == 'offline': + where.append("ps.online_status::text = 'Offline'") + + where_clause = ' AND '.join(where) + players = self.db.query(f""" + SELECT a.id, a.class, a.map, a.transform::text as transform_text, + COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name, + ps.online_status::text as online_status, + ps.life_state::text as life_state, + ps.last_login_time, + ps.last_avatar_activity, + ea.id as account_id, ea.user as account_email, + acc.funcom_id, + ps.player_controller_id, + f.name as faction_name, g.guild_name, + pi.ip_address + FROM dune.actors a + JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id + LEFT JOIN dune.accounts acc ON ea.id = acc.id + LEFT JOIN dune.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id + LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_id + LEFT JOIN dune.factions f ON pf.faction_id = f.id + LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id + LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id + LEFT JOIN dune.player_ips pi ON ps.player_controller_id = pi.player_id + WHERE {where_clause} + ORDER BY player_name + LIMIT %s + """, params + [limit]) + + if not players: + return [] + + player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')] + actor_ids = [p.get('id') for p in players if p.get('id')] + + vehicle_counts = {} + if player_ids: + vc = self.db.query(""" + SELECT par.player_id, COUNT(DISTINCT par.permission_actor_id)::int as cnt + FROM dune.permission_actor_rank par + JOIN dune.vehicles v ON par.permission_actor_id = v.id + WHERE par.rank = 1 AND par.player_id = ANY(%s) + GROUP BY par.player_id + """, [player_ids]) + vehicle_counts = {r['player_id']: r['cnt'] for r in (vc or []) if r.get('player_id')} + + building_counts = {} + if actor_ids: + bc = self.db.query(""" + SELECT owner_id, COUNT(*)::int as cnt + FROM dune.buildings + WHERE owner_id = ANY(%s) + GROUP BY owner_id + """, [actor_ids]) + building_counts = {r['owner_id']: r['cnt'] for r in (bc or []) if r.get('owner_id')} + + for p in players: + pid = p.get('player_controller_id') or p.get('id') + p['vehicle_count'] = vehicle_counts.get(pid, 0) + p['building_count'] = building_counts.get(p.get('id'), 0) + + return players + + def get_player_detail(self, player_id): + player = self.db.query(""" + SELECT a.*, a.transform::text as transform_text, + ea.id as account_id, ea.user as account_email, ea.platform_id, + acc.funcom_id, + COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name, + ps.online_status::text as online_status, + ps.life_state::text as life_state, + ps.last_login_time, + ps.last_avatar_activity, + ps.player_controller_id, + ps.player_pawn_id as state_pawn_id, + f.name as faction_name, pf.faction_id, pf.utc_time_faction_change + FROM dune.actors a + JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id + LEFT JOIN dune.accounts acc ON ea.id = acc.id + LEFT JOIN dune.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id + LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_id + LEFT JOIN dune.factions f ON pf.faction_id = f.id + WHERE a.id = %s AND a.class LIKE %s + """, [player_id, LIKE_PC], one=True) + return player + + def get_player_vitals(self, state_pawn_id): + if not state_pawn_id: + return {} + try: + return self.db.query(""" + SELECT + (properties->'DamageableActorComponent'->>'m_CurrentMaxHealth')::float as current_health, + (properties->'DamageableActorComponent'->>'m_TotalMaxHealth')::float as max_health, + (gas_attributes->'DuneHydrationAttributeSet'->'CurrentHydration'->>'CurrentValue')::float as current_hydration, + (gas_attributes->'DuneHydrationAttributeSet'->'DehydrationPenalty'->>'CurrentValue')::float as dehydration_penalty, + (gas_attributes->'DuneSpiceAddictionAttributeSet'->'CurrentSpice'->>'CurrentValue')::float as current_spice, + (gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceAddictionLevel'->'CurrentValue'->>'Value')::float as spice_addiction_level, + (gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceTolerance'->'CurrentValue'->>'Value')::float as spice_tolerance + FROM dune.actors WHERE id = %s + """, [state_pawn_id], one=True) or {} + except Exception as e: + logger.warning(f"Failed to get vitals: {e}") + return {} + + def get_player_guild(self, player_controller_id): + return self.db.query(""" + SELECT g.guild_id, g.guild_name, g.guild_description, f.name as faction_name, gm.role_id + FROM dune.guild_members gm + JOIN dune.guilds g ON gm.guild_id = g.guild_id + LEFT JOIN dune.factions f ON g.guild_faction = f.id + WHERE gm.player_id = %s + """, [player_controller_id], one=True) + + def get_player_vehicles(self, player_controller_id): + if not player_controller_id: + return [] + return self.db.query(""" + SELECT v_a.id, v_a.class, v_a.map, v_a.transform::text as transform_text, + pa.actor_name, + par.rank as ownership_rank + FROM dune.permission_actor_rank par + JOIN dune.vehicles v ON par.permission_actor_id = v.id + JOIN dune.actors v_a ON v.id = v_a.id + LEFT JOIN dune.permission_actor pa ON v.id = pa.actor_id AND pa.is_child = FALSE + WHERE par.player_id = %s + ORDER BY v_a.class + """, [player_controller_id]) or [] + + def get_player_buildings(self, player_id): + try: + return self.db.query(""" + SELECT a.id, a.class, a.map, a.transform::text as transform_text, + (SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count + FROM dune.buildings b + JOIN dune.actors a ON b.id = a.id + WHERE b.owner_id = %s + ORDER BY a.map + """, [player_id]) or [] + except Exception: + return [] + + def get_player_currency(self, player_controller_id): + if not player_controller_id: + return [] + try: + return self.db.query( + "SELECT pvcb.currency_id, pvcb.balance FROM dune.player_virtual_currency_balances pvcb WHERE pvcb.player_controller_id = %s", + [player_controller_id] + ) or [] + except Exception: + return [] + + def get_player_inventories(self, player_id): + try: + inventories = self.db.query(""" + SELECT i.id, i.actor_id, i.inventory_type, + COALESCE(json_agg( + json_build_object( + 'id', items.id, + 'template_id', items.template_id, + 'stack_size', items.stack_size, + 'quality_level', items.quality_level, + 'is_new', items.is_new, + 'stats_text', items.stats::text + ) ORDER BY items.position_index + ) FILTER (WHERE items.id IS NOT NULL), '[]') as item_list + FROM dune.inventories i + LEFT JOIN dune.items ON i.id = items.inventory_id + WHERE i.actor_id = %s + GROUP BY i.id, i.actor_id, i.inventory_type + ORDER BY i.inventory_type + """, [player_id]) or [] + for inv in inventories: + inv['item_list'] = inv.get('item_list', []) or [] + return inventories + except Exception as e: + logger.warning(f"Failed to get inventories: {e}") + inventories = self.db.query( + "SELECT i.* FROM dune.inventories i WHERE i.actor_id = %s ORDER BY i.inventory_type", + [player_id] + ) or [] + for inv in inventories: + inv['item_list'] = [] + return inventories + + def get_player_landclaims(self, owner_account_id): + try: + return self.db.query(""" + SELECT DISTINCT a.id, a.class, a.map, a.transform::text as transform_text + FROM dune.landclaim_segments lcs + JOIN dune.actors a ON lcs.totem_id = a.id + WHERE a.owner_account_id = %s + """, [owner_account_id]) or [] + except Exception: + return [] + + def get_player_specialization(self, player_controller_id): + if not player_controller_id: + return [] + try: + return self.db.query( + "SELECT track_type, xp_amount, level FROM dune.specialization_tracks WHERE player_id = %s", + [player_controller_id] + ) or [] + except Exception: + return [] + + def get_player_tech_knowledge(self, player_id): + try: + tech_row = self.db.query( + "SELECT (properties->'TechKnowledgePlayerComponent'->>'m_TechKnowledgePoints')::int as xp_points FROM dune.actors WHERE id = %s", + [player_id], one=True + ) + return tech_row['xp_points'] if tech_row else None + except Exception: + return None + + def get_player_keystones(self, player_controller_id): + if not player_controller_id: + return [] + try: + return self.db.query( + "SELECT ks.id, ks.name FROM dune.purchased_specialization_keystones psk JOIN dune.specialization_keystones_map ks ON psk.keystone_id = ks.id WHERE psk.player_id = %s ORDER BY ks.id", + [player_controller_id] + ) or [] + except Exception: + return [] + + def get_player_faction_reputation(self, player_controller_id): + if not player_controller_id: + return [] + try: + return self.db.query( + "SELECT pfr.faction_id, f.name as faction_name, pfr.reputation_amount FROM dune.player_faction_reputation pfr JOIN dune.factions f ON pfr.faction_id = f.id WHERE pfr.actor_id = %s ORDER BY pfr.faction_id", + [player_controller_id] + ) or [] + except Exception: + return [] + + def get_player_landsraad(self, player_controller_id): + if not player_controller_id: + return {} + try: + return self.db.query( + "SELECT (properties->'LandsraadCharacterComponent'->>'m_DailyRewardCharges')::int as daily_reward_charges, " + "(properties->'LandsraadCharacterComponent'->>'m_LastViewedLandsraadTermId')::int as last_viewed_term_id, " + "(properties->'LandsraadCharacterComponent'->>'m_DailyRewardLastProcessedTimestamp')::bigint as daily_reward_last_processed " + "FROM dune.actors WHERE id = %s", + [player_controller_id], one=True + ) or {} + except Exception: + return {} diff --git a/app/services/ssh.py b/app/services/ssh.py new file mode 100644 index 0000000..e618191 --- /dev/null +++ b/app/services/ssh.py @@ -0,0 +1,43 @@ +"""SSH service - remote command execution""" + +import subprocess +import logging +import os + +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 + + def run(self, command, timeout=30): + args = [ + 'ssh', + '-i', self.ssh_key, + '-o', 'StrictHostKeyChecking=accept-new', + '-o', 'ConnectTimeout=10', + '-o', 'BatchMode=yes', + f'{self.user}@{self.host}', + command + ] + try: + result = subprocess.run( + args, + capture_output=True, + text=True, + timeout=timeout + ) + return result.stdout, result.stderr, result.returncode + except FileNotFoundError: + return '', 'ssh command not found', -1 + except subprocess.TimeoutExpired: + return '', 'SSH command timed out', -1 + except Exception as ex: + return '', str(ex), -1 + + def check_connection(self): + out, err, rc = self.run('echo ok', timeout=5) + return rc == 0 and 'ok' in out diff --git a/app/services/vehicle.py b/app/services/vehicle.py new file mode 100644 index 0000000..7c50eb2 --- /dev/null +++ b/app/services/vehicle.py @@ -0,0 +1,158 @@ +"""Vehicle service - vehicle queries and operations""" + +import logging + +logger = logging.getLogger(__name__) + +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', +} + +TYPE_CONFIGS = { + 'Ornithopter': { + 'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000, 'Boost': 2000, 'Launcher': 2000}, + 'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Cockpit', 'HullBack': 'Tail', 'Locomotion': 'Wing', 'Boost': 'Boost', 'Launcher': 'Launcher'} + }, + 'Transport': { + 'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000}, + 'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Main Hull', 'HullBack': 'Tail Hull', 'Locomotion': 'Wing'} + }, + 'Buggy': { + 'base': {'Chassis': 3500, 'Engine': 1750, 'Generator': 1750, 'Hull': 2625, 'HullFront': 2625, 'HullBack': 2625, 'Locomotion': 1750}, + 'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'PSU', 'Hull': 'Hull', 'HullFront': 'Front', 'HullBack': 'Rear', 'Locomotion': 'Tread'} + }, + 'Sandcrawler': { + 'base': {'Chassis': 4250, 'Hull': 3187, 'Locomotion': 2500, 'SpiceHeader': 2500, 'Generator': 2500, 'Engine': 2500, 'SpiceContainer': 3200}, + 'names': {'Chassis': 'Chassis', 'Hull': 'Hull', 'Locomotion': 'Tread', 'SpiceHeader': 'Spice Header', 'Generator': 'PSU', 'Engine': 'Engine', 'SpiceContainer': 'Spice Container'} + }, + 'Sandbike': { + 'base': {'Chassis': 1500, 'Engine': 1200, 'Generator': 1200, 'Hull': 1000, 'Locomotion': 1200}, + 'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'Locomotion': 'Wheel'} + } +} + + +def vehicle_type_name(cls): + if '/' in cls: + short = cls.split('/')[-1].replace('_C', '') + for key, name in VEHICLE_TYPE_MAP.items(): + if key in short: + return name + return short.replace('BP_', '').replace('_CHOAM', '').replace('_Choam', '').replace('_', ' ') + return cls + + +def get_vehicle_type_config(vehicle_class): + type_order = ['Sandcrawler', 'Sandbike', 'Buggy', 'Transport', 'Ornithopter', 'Light', 'Medium'] + for t in type_order: + if t in vehicle_class: + return TYPE_CONFIGS.get(t, TYPE_CONFIGS['Buggy']) + return TYPE_CONFIGS['Buggy'] + + +def parse_vehicle_modules(modules, vehicle_class): + config = get_vehicle_type_config(vehicle_class) + parsed = [] + for m in modules: + stats = m.get('stats', {}) + durability = stats.get('FVehicleModuleDurabilityStats', [{}])[1] if stats.get('FVehicleModuleDurabilityStats') else {} + current = durability.get('CurrentDurability', 0) + max_durability = durability.get('MaxDurability') or durability.get('DecayedMaxDurability') or current + + template = m.get('template_id', '') + mod_clean = template.replace('Ornithopter', '').replace('Buggy', '').replace('Sandcrawler', '').replace('Sandbike', '').replace('_6', '').replace('_0', '') + mod_type = mod_clean.replace('Medium', '').replace('Transport', '').replace('Light', '').replace('Heavy', '').replace('Front', '').replace('Back', '').replace('Left', '').replace('Right', '').replace('Center', '').replace('1', '').replace('2', '') + name = config['names'].get(mod_type, mod_clean) + + parsed.append({ + 'id': m['id'], + 'name': name, + 'template': template, + 'current': round(current, 1), + 'max': round(max_durability, 1), + 'damage_cause': durability.get('LastDeteriorationCause', '') + }) + return parsed + + +class VehicleService: + def __init__(self, db_service): + self.db = db_service + + def get_all_vehicles(self, limit=200): + return self.db.query(""" + SELECT a.id, a.class, a.map, a.transform::text as transform_text, + pa.actor_name, + pilot_ps.character_name as pilot_name, + pilot_a.id as pilot_pawn_id, + ps_owner.character_name as owner_name, + ps_owner.player_pawn_id as owner_pawn_id, + par.rank as owner_rank + FROM dune.actors a + JOIN dune.vehicles v ON a.id = v.id + LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE + LEFT JOIN dune.actors pilot_a ON pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_CurrentVehicleId' = CONCAT('!!act#', a.id::text) + AND (pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving')::boolean = TRUE + LEFT JOIN dune.player_state pilot_ps ON pilot_a.owner_account_id = pilot_ps.account_id AND pilot_a.id = pilot_ps.player_pawn_id + LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1 + LEFT JOIN dune.player_state ps_owner ON par.player_id = ps_owner.player_controller_id + ORDER BY a.class + LIMIT %s + """, [limit]) or [] + + def get_vehicle(self, vehicle_id): + return self.db.query(""" + SELECT a.id, a.class, a.map, a.transform::text as transform_text, + pa.actor_name, + ps.character_name as owner_name, + ps.player_pawn_id as owner_pawn_id + FROM dune.actors a + JOIN dune.vehicles v ON a.id = v.id + LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE + LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1 + LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id + WHERE a.id = %s + """, [vehicle_id], one=True) + + def get_vehicle_modules(self, vehicle_id): + return self.db.query(""" + SELECT id, template_id, stats + FROM dune.vehicle_modules + WHERE vehicle_id = %s + ORDER BY id + """, [vehicle_id]) or [] + + def delete_vehicle(self, vehicle_id): + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SET session_replication_role = replica") + cur.execute("DELETE FROM dune.vehicles WHERE id = %s RETURNING id", [vehicle_id]) + deleted = cur.fetchone() + if deleted: + cur.execute("DELETE FROM dune.actors WHERE id = %s RETURNING id", [vehicle_id]) + conn.commit() + cur.execute("SET session_replication_role = default") + return True, f"Vehicle {vehicle_id} deleted" + else: + conn.rollback() + cur.execute("SET session_replication_role = default") + return False, "Vehicle not found" + except Exception as e: + logger.error(f"Failed to delete vehicle {vehicle_id}: {e}") + try: + cur.execute("SET session_replication_role = default") + except Exception: + pass + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000..5ee152c --- /dev/null +++ b/app/utils/__init__.py @@ -0,0 +1 @@ +"""Utils package""" diff --git a/app/utils/cache.py b/app/utils/cache.py new file mode 100644 index 0000000..3a0e218 --- /dev/null +++ b/app/utils/cache.py @@ -0,0 +1,51 @@ +"""Simple TTL-based cache""" + +import datetime +import logging + +logger = logging.getLogger(__name__) + + +class TTLCache: + def __init__(self, ttl_seconds=60): + self._data = None + self._timestamp = 0 + self._ttl = ttl_seconds + + def get(self): + current_time = datetime.datetime.now().timestamp() + if self._data and (current_time - self._timestamp) < self._ttl: + return self._data + return None + + def set(self, data): + self._data = data + self._timestamp = datetime.datetime.now().timestamp() + + def invalidate(self): + self._data = None + self._timestamp = 0 + + +class MultiCache: + def __init__(self, ttl_seconds=60): + self._cache = {} + self._ttl = ttl_seconds + + def get(self, key): + entry = self._cache.get(key) + if not entry: + return None + current_time = datetime.datetime.now().timestamp() + if (current_time - entry['timestamp']) < self._ttl: + return entry['data'] + return None + + def set(self, key, data): + self._cache[key] = {'data': data, 'timestamp': datetime.datetime.now().timestamp()} + + def invalidate(self, key=None): + if key: + self._cache.pop(key, None) + else: + self._cache = {} diff --git a/app/utils/constants.py b/app/utils/constants.py new file mode 100644 index 0000000..d0dadd4 --- /dev/null +++ b/app/utils/constants.py @@ -0,0 +1,41 @@ +"""Shared data 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', +} + +CURRENCY_ID_LABELS = { + 0: 'Solari Credits', + 1: 'House Script', + 2: 'Spice', +} + +GUILD_ROLES = {100: 'Leader', 90: 'Officer', 80: 'Officer', 50: 'Member', 1: 'Member'} + +NAV_PAGES = [ + ('/', 'Overview'), + ('/server', 'Server'), + ('/director', 'Director'), + ('/shell', 'Shell'), + ('/files', 'Files'), + ('/events', 'Events'), + ('/chat', 'Chat'), + ('/players', 'Players'), + ('/vehicles', 'Vehicles'), + ('/guilds', 'Guilds'), + ('/buildings', 'Buildings'), + ('/admin', 'Admin'), +] diff --git a/app/websocket/__init__.py b/app/websocket/__init__.py new file mode 100644 index 0000000..d8eacc9 --- /dev/null +++ b/app/websocket/__init__.py @@ -0,0 +1 @@ +"""WebSocket handlers package""" diff --git a/app/websocket/shell.py b/app/websocket/shell.py new file mode 100644 index 0000000..162a91f --- /dev/null +++ b/app/websocket/shell.py @@ -0,0 +1,124 @@ +"""WebSocket shell handler - interactive terminal via SSH""" + +import os +import sys +import time +import threading +import logging + +try: + import paramiko + HAS_PARAMIKO = True +except ImportError: + HAS_PARAMIKO = False + +logger = logging.getLogger(__name__) + +shell_processes = {} + + +def register_websocket_handlers(socketio, settings): + if not HAS_PARAMIKO: + logger.warning("Paramiko not installed. WebSocket shell disabled.") + return + + @socketio.on('shell_create') + def handle_shell_create(data): + 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', '') + 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) + chan.exec_command(f'sudo kubectl exec -it {pod} -n {namespace} -- /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: + 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: + 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: + pass + + @socketio.on('shell_disconnect') + def handle_shell_disconnect(): + 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: + pass + del shell_processes[shell_id] + + +def _find_ssh_key(settings): + key = settings['server'].get('ssh_key') + if key and os.path.exists(key): + return key + + base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + temp_dir = os.environ.get('TEMP') or os.environ.get('TMPDIR') or ('/tmp' if os.name != 'nt' else 'C:\\Temp') + potential_paths = [ + os.path.join(temp_dir, 'dune-tunnel-key'), + os.path.join(temp_dir, 'dune-awakening-server-sshKey'), + os.path.join(base_dir, 'internal-scripts', 'ssh', 'sshKey'), + os.path.join(os.path.dirname(base_dir), 'internal-scripts', 'ssh', 'sshKey'), + ] + for p in potential_paths: + if os.path.exists(p): + return p + return None + + +# Import flask globals inside functions to avoid circular imports +from flask import request +from flask_socketio import emit diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f0dd083 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +Flask==3.1.2 +Flask-SocketIO==5.4.1 +python-socketio==5.12.1 +psycopg2-binary==2.9.12 +paramiko==3.4.0 +PyYAML==6.0.2 +Flask-Login==0.6.3 +Flask-WTF==1.2.2 +Flask-Talisman==1.1.0 diff --git a/run.py b/run.py new file mode 100644 index 0000000..1e7ec1c --- /dev/null +++ b/run.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Dune Awakening Dashboard - Entry Point""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(__file__)) + +from app.factory import create_app + +app, socketio = create_app() + +if __name__ == '__main__': + settings = app.dune_settings + host = settings['dashboard']['host'] + port = settings['dashboard']['port'] + debug = settings['dashboard']['debug'] + + print(f"\n Dune Awakening Dashboard") + print(f" http://{host}:{port}") + print(f" Debug: {debug}\n") + + socketio.run(app, host=host, port=port, debug=debug) diff --git a/settings.yaml.example b/settings.yaml.example new file mode 100644 index 0000000..542717a --- /dev/null +++ b/settings.yaml.example @@ -0,0 +1,54 @@ +# Dune Awakening Dashboard - Settings +# ========================================== +# All configuration in one file. +# Copy this to settings.yaml and edit for your server. +# Run 'python setup.py' for guided setup. +# ========================================== + +# Server connection +server: + host: "65.21.198.100" # VM IP address + user: "dune" # SSH username + ssh_key: null # Path to SSH key (null = auto-detect) + +# Dashboard +dashboard: + host: "127.0.0.1" # Bind address (use 127.0.0.1 for security) + port: 5050 # Port number + debug: false # Set true for development only + secret_key: "change-me-to-random-string" # For session security + +# Database (accessed via SSH tunnel) +database: + host: "127.0.0.1" # Local tunnel endpoint + port: 15433 # Local tunnel port + user: "postgres" + password: "postgres" + name: "dune" + schema: "dune" + min_connections: 2 + max_connections: 10 + +# Kubernetes +kubernetes: + namespace: "" # Leave empty to auto-detect on first run + battlegroup_script: "/home/dune/.dune/bin/battlegroup" + +# Cache (seconds) +cache: + chat_pod_ttl: 60 + chat_messages_ttl: 10 + static_data_ttl: 300 + +# Authentication +auth: + enabled: true # Set false to disable login (localhost only) + username: "admin" + password: "changeme" # Change this! + +# Logging +logging: + level: "INFO" # DEBUG, INFO, WARNING, ERROR + file: "logs/dashboard.log" + max_bytes: 10485760 # 10MB + backup_count: 5 diff --git a/setup.ps1 b/setup.ps1 new file mode 100644 index 0000000..fbb19bb --- /dev/null +++ b/setup.ps1 @@ -0,0 +1,324 @@ +# Dune Awakening Dashboard - Setup +# Run this ONCE per server. After that, use start.ps1 + +$ErrorActionPreference = "Stop" + +$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location -LiteralPath $ProjectRoot + +Write-Host "" +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host " Dune Awakening Dashboard - Setup" -ForegroundColor Cyan +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host "" + +# Check if this is a re-run (existing settings or logs) +$IsReRun = (Test-Path (Join-Path $ProjectRoot "settings.yaml")) -or (Test-Path (Join-Path $ProjectRoot "logs")) -or (Test-Path (Join-Path $ProjectRoot "instance")) + +if ($IsReRun) { + Write-Host " [WARNING] Existing dashboard data detected!" -ForegroundColor Red + Write-Host "" + Write-Host " This will WIPE the following and start fresh:" -ForegroundColor Yellow + Write-Host " - settings.yaml (configuration)" -ForegroundColor Yellow + Write-Host " - logs/ (all log files)" -ForegroundColor Yellow + Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow + Write-Host " - __pycache__/ (Python cache)" -ForegroundColor Yellow + Write-Host "" + Write-Host " Are you sure you want to continue? (Y/N)" -ForegroundColor Red + + $confirmation = Read-Host " Type Y to confirm" + if ($confirmation -ne "Y" -and $confirmation -ne "y") { + Write-Host "" + Write-Host " Setup cancelled. No changes made." -ForegroundColor Yellow + exit 0 + } + + Write-Host "" + Write-Host " Cleaning existing data..." -ForegroundColor Yellow + + if (Test-Path (Join-Path $ProjectRoot "settings.yaml")) { + Remove-Item (Join-Path $ProjectRoot "settings.yaml") -Force + Write-Host " Removed settings.yaml" -ForegroundColor Green + } + if (Test-Path (Join-Path $ProjectRoot "logs")) { + Remove-Item (Join-Path $ProjectRoot "logs") -Recurse -Force + Write-Host " Removed logs/" -ForegroundColor Green + } + if (Test-Path (Join-Path $ProjectRoot "instance")) { + Remove-Item (Join-Path $ProjectRoot "instance") -Recurse -Force + Write-Host " Removed instance/" -ForegroundColor Green + } + if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { + Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force + Write-Host " Removed __pycache__/" -ForegroundColor Green + } + + # Clean app/__pycache__ and routes/__pycache__ etc. + $cacheDirs = Get-ChildItem -Path (Join-Path $ProjectRoot "app") -Recurse -Directory -Filter "__pycache__" -ErrorAction SilentlyContinue + foreach ($dir in $cacheDirs) { + Remove-Item $dir.FullName -Recurse -Force + } + if ($cacheDirs.Count -gt 0) { + Write-Host " Removed $($cacheDirs.Count) Python cache folders" -ForegroundColor Green + } + + Write-Host " Clean complete!" -ForegroundColor Green + Write-Host "" +} + +# Check Python +Write-Host "[1/6] Checking Python..." -ForegroundColor Yellow +try { + $pythonVersion = python --version 2>&1 + Write-Host " Found: $pythonVersion" -ForegroundColor Green +} catch { + Write-Host " [ERROR] Python not found. Install Python 3.8+ first." -ForegroundColor Red + exit 1 +} + +# Install dependencies +Write-Host "" +Write-Host "[2/6] Installing dependencies..." -ForegroundColor Yellow +pip install -r (Join-Path $ProjectRoot "requirements.txt") --quiet +if ($LASTEXITCODE -eq 0) { + Write-Host " Dependencies installed" -ForegroundColor Green +} else { + Write-Host " [WARN] Some packages may have failed. Continuing..." -ForegroundColor Yellow +} + +# Configure SSH key +Write-Host "" +Write-Host "[3/6] Configuring SSH key..." -ForegroundColor Yellow +$TargetKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey" +$SshKeyPaths = @( + "$env:TEMP\dune-tunnel-key", + "$env:TEMP\dune-awakening-server-sshKey", + $TargetKey, + (Join-Path (Split-Path $ProjectRoot) "internal-scripts\ssh\sshKey") +) +$FoundKey = $null +foreach ($path in $SshKeyPaths) { + if (Test-Path $path) { + $FoundKey = $path + break + } +} + +function Fix-SshKeyPermissions($keyPath) { + if (-not (Test-Path $keyPath)) { return } + $acl = Get-Acl $keyPath + $acl.SetAccessRuleProtection($true, $false) + $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow") + $acl.SetAccessRule($rule) + $adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators", "FullControl", "Allow") + $acl.SetAccessRule($adminRule) + Set-Acl -Path $keyPath -AclObject $acl +} + +if (-not $FoundKey) { + Write-Host " [INFO] No SSH key found in standard locations." -ForegroundColor Yellow + $userKey = Read-Host " Enter path to your SSH key file (or press Enter to skip)" + if ($userKey -and (Test-Path $userKey)) { + $targetDir = Join-Path $ProjectRoot "internal-scripts\ssh" + if (-not (Test-Path $targetDir)) { + New-Item -ItemType Directory -Path $targetDir -Force | Out-Null + } + Copy-Item $userKey $TargetKey -Force + Fix-SshKeyPermissions $TargetKey + $FoundKey = $TargetKey + Write-Host " Key copied to internal-scripts\ssh\sshKey" -ForegroundColor Green + } else { + Write-Host " Skipping SSH key configuration." -ForegroundColor Yellow + $FoundKey = $null + } +} else { + # If found in temp, copy to project for portability + if ($FoundKey -notlike "*internal-scripts*") { + $targetDir = Join-Path $ProjectRoot "internal-scripts\ssh" + if (-not (Test-Path $targetDir)) { + New-Item -ItemType Directory -Path $targetDir -Force | Out-Null + } + Copy-Item $FoundKey $TargetKey -Force + Fix-SshKeyPermissions $TargetKey + $FoundKey = $TargetKey + Write-Host " Key copied to internal-scripts\ssh\sshKey for portability" -ForegroundColor Green + } else { + Write-Host " Found: $FoundKey" -ForegroundColor Green + } +} + +# Auto-detect server settings +Write-Host "" +Write-Host "[4/6] Detecting server settings..." -ForegroundColor Yellow + +$ServerHost = "65.21.198.100" +$ServerUser = "dune" +$K8sNamespace = "" +$DashboardPort = "5050" +$DbPort = "15433" +$DirectorPort = "32479" +$FileBrowserPort = "18888" +$AuthUser = "admin" +$AuthPass = "changeme" + +if ($FoundKey) { + # Test SSH + $testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$ServerHost" "echo ok" 2>$null + if ($testOut -eq "ok") { + Write-Host " SSH connection OK" -ForegroundColor Green + + # Auto-detect namespace + $nsOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$ServerHost" "sudo kubectl get namespaces -o name" 2>$null + if ($nsOut) { + foreach ($line in $nsOut -split "`n") { + $ns = $line -replace 'namespace/', '' + if ($ns -match '^funcom-seabass-') { + $K8sNamespace = $ns + Write-Host " Namespace: $K8sNamespace" -ForegroundColor Green + break + } + } + } + } else { + Write-Host " [WARN] SSH failed. Using defaults." -ForegroundColor Yellow + } +} + +# Interactive review/edit +Write-Host "" +Write-Host " Review settings (press Enter to accept, or type new value):" -ForegroundColor Cyan +Write-Host "" + +$val = Read-Host " Server Host [$ServerHost]" +if ($val) { $ServerHost = $val } + +$val = Read-Host " Server User [$ServerUser]" +if ($val) { $ServerUser = $val } + +$val = Read-Host " SSH Key Path [$FoundKey]" +if ($val) { $FoundKey = $val } + +$val = Read-Host " K8s Namespace [$K8sNamespace]" +if ($val) { $K8sNamespace = $val } + +$val = Read-Host " Dashboard Port [$DashboardPort]" +if ($val) { $DashboardPort = $val } + +$val = Read-Host " DB Local Port [$DbPort]" +if ($val) { $DbPort = $val } + +$val = Read-Host " Director Port [$DirectorPort]" +if ($val) { $DirectorPort = $val } + +$val = Read-Host " FileBrowser Port [$FileBrowserPort]" +if ($val) { $FileBrowserPort = $val } + +$val = Read-Host " Auth Username [$AuthUser]" +if ($val) { $AuthUser = $val } + +$val = Read-Host " Auth Password [$AuthPass]" +if ($val) { $AuthPass = $val } + +Write-Host "" +Write-Host "[5/6] Saving settings..." -ForegroundColor Yellow + +# Generate secret key +$secret = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_}) + +# Write settings.yaml (UTF-8 without BOM) +$sshKeyPath = if ($FoundKey) { $FoundKey -replace '\\', '\\' } else { "null" } +$settingsContent = @" +server: + host: '$ServerHost' + user: $ServerUser + ssh_key: '$sshKeyPath' + +dashboard: + host: 127.0.0.1 + port: $DashboardPort + debug: false + secret_key: $secret + +database: + host: 127.0.0.1 + port: $DbPort + user: postgres + password: postgres + name: dune + schema: dune + min_connections: 2 + max_connections: 10 + +kubernetes: + namespace: '$K8sNamespace' + battlegroup_script: /home/dune/.dune/bin/battlegroup + +director: + port: $DirectorPort + +filebrowser: + port: $FileBrowserPort + +cache: + chat_pod_ttl: 60 + chat_messages_ttl: 10 + static_data_ttl: 300 + +auth: + enabled: true + username: $AuthUser + password: $AuthPass + +logging: + level: INFO + file: logs/dashboard.log + max_bytes: 10485760 + backup_count: 5 +"@ + +[System.IO.File]::WriteAllText((Join-Path $ProjectRoot "settings.yaml"), $settingsContent, [System.Text.UTF8Encoding]::new($false)) +Write-Host " Settings saved to settings.yaml" -ForegroundColor Green + +# Create logs directory +New-Item -ItemType Directory -Path (Join-Path $ProjectRoot "logs") -Force | Out-Null + +Write-Host "" +Write-Host "[6/6] Verifying setup..." -ForegroundColor Yellow +$verifyResult = python -W ignore -c "from app.factory import create_app; app, sio = create_app(); print('OK -', len(app.url_map._rules), 'routes')" 2>$null +if ($verifyResult -match "OK") { + Write-Host " $verifyResult" -ForegroundColor Green +} else { + Write-Host " [WARN] Verification failed: $verifyResult" -ForegroundColor Yellow +} + +Write-Host "" +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host " Setup Complete!" -ForegroundColor Cyan +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host "" + +# Check if SSH key is valid for the server +$SshValid = $false +if ($FoundKey -and (Test-Path $FoundKey)) { + $testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${ServerHost}" "echo ok" 2>$null + $SshValid = ($testOut -eq "ok") +} + +if (-not $SshValid) { + Write-Host " SSH key is not configured or failed to connect." -ForegroundColor Yellow + Write-Host " Run setup-ssh-key.ps1 first to configure SSH access:" -ForegroundColor Yellow + Write-Host "" + Write-Host " .\setup-ssh-key.ps1" -ForegroundColor Cyan + Write-Host "" + Write-Host " Then start the dashboard with:" -ForegroundColor Yellow + Write-Host "" + Write-Host " .\start.ps1" -ForegroundColor Cyan +} else { + Write-Host " SSH connection verified." -ForegroundColor Green + Write-Host "" + Write-Host " Start the dashboard with:" -ForegroundColor Yellow + Write-Host "" + Write-Host " .\start.ps1" -ForegroundColor Cyan +} + +Write-Host "" diff --git a/setup.sh b/setup.sh new file mode 100644 index 0000000..7c00a4e --- /dev/null +++ b/setup.sh @@ -0,0 +1,266 @@ +#!/bin/bash +# Dune Awakening Dashboard - Setup (Linux/macOS) +# Run this ONCE per server. After that, use start.sh + +set -e + +PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)" +cd "$PROJECT_ROOT" + +echo "" +echo "============================================================" +echo " Dune Awakening Dashboard - Setup" +echo "============================================================" +echo "" + +# Check if this is a re-run +IS_RERUN=false +if [ -f "$PROJECT_ROOT/settings.yaml" ] || [ -d "$PROJECT_ROOT/logs" ] || [ -d "$PROJECT_ROOT/instance" ]; then + IS_RERUN=true +fi + +if [ "$IS_RERUN" = true ]; then + echo " [WARNING] Existing dashboard data detected!" + echo "" + echo " This will WIPE the following and start fresh:" + echo " - settings.yaml (configuration)" + echo " - logs/ (all log files)" + echo " - instance/ (SQLite database)" + echo "" + echo " Are you sure you want to continue? (y/N)" + read -r CONFIRMATION + if [ "$CONFIRMATION" != "y" ] && [ "$CONFIRMATION" != "Y" ]; then + echo "" + echo " Setup cancelled. No changes made." + exit 0 + fi + + echo "" + echo " Cleaning existing data..." + [ -f "$PROJECT_ROOT/settings.yaml" ] && rm -f "$PROJECT_ROOT/settings.yaml" && echo " Removed settings.yaml" + [ -d "$PROJECT_ROOT/logs" ] && rm -rf "$PROJECT_ROOT/logs" && echo " Removed logs/" + [ -d "$PROJECT_ROOT/instance" ] && rm -rf "$PROJECT_ROOT/instance" && echo " Removed instance/" + find "$PROJECT_ROOT" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null && echo " Removed __pycache__/" + echo " Clean complete!" + echo "" +fi + +# Determine Python command +PYTHON="" +if command -v python3 &>/dev/null; then + PYTHON="python3" +elif command -v python &>/dev/null; then + PYTHON="python" +else + echo "[ERROR] Python not found. Install Python 3.8+ first." + exit 1 +fi + +echo "[1/6] Checking Python..." +echo " Found: $($PYTHON --version)" + +# Install dependencies +echo "" +echo "[2/6] Installing dependencies..." +$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null && echo " Dependencies installed" || echo " [WARN] Some packages may have failed. Continuing..." + +# Configure SSH key +echo "" +echo "[3/6] Configuring SSH key..." +TARGET_KEY="$PROJECT_ROOT/internal-scripts/ssh/sshKey" +SSH_KEY_PATHS=( + "/tmp/dune-tunnel-key" + "/tmp/dune-awakening-server-sshKey" + "$TARGET_KEY" + "$(dirname "$PROJECT_ROOT")/internal-scripts/ssh/sshKey" +) +FOUND_KEY="" +for path in "${SSH_KEY_PATHS[@]}"; do + if [ -f "$path" ]; then + FOUND_KEY="$path" + break + fi +done + +fix_ssh_perms() { + if [ -f "$1" ]; then + chmod 600 "$1" + if command -v chown &>/dev/null; then + chown "$(whoami)" "$1" 2>/dev/null || true + fi + fi +} + +if [ -z "$FOUND_KEY" ]; then + echo " [INFO] No SSH key found in standard locations." + read -rp " Enter path to your SSH key file (or press Enter to skip): " USER_KEY + if [ -n "$USER_KEY" ] && [ -f "$USER_KEY" ]; then + mkdir -p "$(dirname "$TARGET_KEY")" + cp "$USER_KEY" "$TARGET_KEY" + fix_ssh_perms "$TARGET_KEY" + FOUND_KEY="$TARGET_KEY" + echo " Key copied to internal-scripts/ssh/sshKey" + else + echo " Skipping SSH key configuration." + fi +else + if [[ "$FOUND_KEY" != *internal-scripts* ]]; then + mkdir -p "$(dirname "$TARGET_KEY")" + cp "$FOUND_KEY" "$TARGET_KEY" + fix_ssh_perms "$TARGET_KEY" + FOUND_KEY="$TARGET_KEY" + echo " Key copied to internal-scripts/ssh/sshKey for portability" + else + fix_ssh_perms "$FOUND_KEY" + echo " Found: $FOUND_KEY" + fi +fi + +# Auto-detect server settings +echo "" +echo "[4/6] Detecting server settings..." + +SERVER_HOST="65.21.198.100" +SERVER_USER="dune" +K8S_NAMESPACE="" +DASHBOARD_PORT="5050" +DB_PORT="15433" +DIRECTOR_PORT="32479" +FILEBROWSER_PORT="18888" +AUTH_USER="admin" +AUTH_PASS="changeme" + +if [ -n "$FOUND_KEY" ]; then + if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$SERVER_HOST" "echo ok" &>/dev/null; then + echo " SSH connection OK" + NS=$(ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$SERVER_HOST" "sudo kubectl get namespaces -o name" 2>/dev/null | grep 'funcom-seabass-' | head -1 | sed 's|namespace/||') + if [ -n "$NS" ]; then + K8S_NAMESPACE="$NS" + echo " Namespace: $K8S_NAMESPACE" + fi + else + echo " [WARN] SSH failed. Using defaults." + fi +fi + +# Interactive review/edit +echo "" +echo " Review settings (press Enter to accept, or type new value):" +echo "" + +read -rp " Server Host [$SERVER_HOST]: " VAL; [ -n "$VAL" ] && SERVER_HOST="$VAL" +read -rp " Server User [$SERVER_USER]: " VAL; [ -n "$VAL" ] && SERVER_USER="$VAL" +read -rp " SSH Key Path [$FOUND_KEY]: " VAL; [ -n "$VAL" ] && FOUND_KEY="$VAL" +read -rp " K8s Namespace [$K8S_NAMESPACE]: " VAL; [ -n "$VAL" ] && K8S_NAMESPACE="$VAL" +read -rp " Dashboard Port [$DASHBOARD_PORT]: " VAL; [ -n "$VAL" ] && DASHBOARD_PORT="$VAL" +read -rp " DB Local Port [$DB_PORT]: " VAL; [ -n "$VAL" ] && DB_PORT="$VAL" +read -rp " Director Port [$DIRECTOR_PORT]: " VAL; [ -n "$VAL" ] && DIRECTOR_PORT="$VAL" +read -rp " FileBrowser Port [$FILEBROWSER_PORT]: " VAL; [ -n "$VAL" ] && FILEBROWSER_PORT="$VAL" +read -rp " Auth Username [$AUTH_USER]: " VAL; [ -n "$VAL" ] && AUTH_USER="$VAL" +read -rp " Auth Password [$AUTH_PASS]: " VAL; [ -n "$VAL" ] && AUTH_PASS="$VAL" + +echo "" +echo "[5/6] Saving settings..." + +# Generate secret key +SECRET=$($PYTHON -c "import secrets; print(secrets.token_hex(32))") + +# Escape SSH key path for YAML +SSH_KEY_YAML="null" +if [ -n "$FOUND_KEY" ]; then + SSH_KEY_YAML="'$FOUND_KEY'" +fi + +cat > "$PROJECT_ROOT/settings.yaml" << EOF +server: + host: '$SERVER_HOST' + user: $SERVER_USER + ssh_key: $SSH_KEY_YAML + +dashboard: + host: 127.0.0.1 + port: $DASHBOARD_PORT + debug: false + secret_key: $SECRET + +database: + host: 127.0.0.1 + port: $DB_PORT + user: postgres + password: postgres + name: dune + schema: dune + min_connections: 2 + max_connections: 10 + +kubernetes: + namespace: '$K8S_NAMESPACE' + battlegroup_script: /home/dune/.dune/bin/battlegroup + +director: + port: $DIRECTOR_PORT + +filebrowser: + port: $FILEBROWSER_PORT + +cache: + chat_pod_ttl: 60 + chat_messages_ttl: 10 + static_data_ttl: 300 + +auth: + enabled: true + username: $AUTH_USER + password: $AUTH_PASS + +logging: + level: INFO + file: logs/dashboard.log + max_bytes: 10485760 + backup_count: 5 +EOF + +echo " Settings saved to settings.yaml" + +# Create logs directory +mkdir -p "$PROJECT_ROOT/logs" + +echo "" +echo "[6/6] Verifying setup..." +VERIFY=$($PYTHON -W ignore -c "from app.factory import create_app; app, sio = create_app(); print('OK -', len(app.url_map._rules), 'routes')" 2>/dev/null) +if [[ "$VERIFY" == OK* ]]; then + echo " $VERIFY" +else + echo " [WARN] Verification failed: $VERIFY" +fi + +echo "" +echo "============================================================" +echo " Setup Complete!" +echo "============================================================" +echo "" + +# Check SSH validity +SSH_VALID=false +if [ -n "$FOUND_KEY" ] && [ -f "$FOUND_KEY" ]; then + if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${SERVER_USER}@${SERVER_HOST}" "echo ok" &>/dev/null; then + SSH_VALID=true + fi +fi + +if [ "$SSH_VALID" = false ]; then + echo " SSH key is not configured or failed to connect." + echo " Edit settings.yaml and set ssh_key to your key path." + echo "" + echo " Then start the dashboard with:" + echo "" + echo " ./start.sh" +else + echo " SSH connection verified." + echo "" + echo " Start the dashboard with:" + echo "" + echo " ./start.sh" +fi + +echo "" diff --git a/start.ps1 b/start.ps1 new file mode 100644 index 0000000..60ded86 --- /dev/null +++ b/start.ps1 @@ -0,0 +1,191 @@ +# Dune Awakening Dashboard Launcher +# Starts SSH tunnel, DB port-forward, then runs the dashboard + +$ErrorActionPreference = "Stop" + +$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$SettingsFile = Join-Path $ProjectRoot "settings.yaml" + +# Check if settings exist +if (-not (Test-Path $SettingsFile)) { + Write-Host "[WARN] settings.yaml not found. Running setup..." -ForegroundColor Yellow + & (Join-Path $ProjectRoot "setup.ps1") + if (-not (Test-Path $SettingsFile)) { + Write-Host "[ERROR] Setup failed." -ForegroundColor Red + exit 1 + } +} + +# Read settings via Python script (avoids YAML parsing issues in PowerShell) +$readSettingsScript = @" +import yaml, json, sys, os +path = sys.argv[1] +if not os.path.exists(path): + print(json.dumps({})) + sys.exit(0) +with open(path, 'r', encoding='utf-8-sig') as f: + s = yaml.safe_load(f) or {} +print(json.dumps(s)) +"@ +$readSettingsScript | Out-File -FilePath "$env:TEMP\read_settings.py" -Encoding utf8 -Force +$settingsJson = python "$env:TEMP\read_settings.py" $SettingsFile 2>$null +if (-not $settingsJson) { + Write-Host "[ERROR] Failed to read settings.yaml" -ForegroundColor Red + exit 1 +} +$settings = $settingsJson | ConvertFrom-Json + +$SSHHost = $settings.server.host +$SSHUser = $settings.server.user +$LocalPort = [int]$settings.database.port +$Namespace = $settings.kubernetes.namespace +$DashboardPort = [int]$settings.dashboard.port + +# Find SSH key (prefer project-local for portability) +$SSHKeySrc = $settings.server.ssh_key +$LocalKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey" +if (Test-Path $LocalKey) { + $SSHKeySrc = $LocalKey +} elseif (-not $SSHKeySrc -or $SSHKeySrc -eq 'null' -or [string]::IsNullOrEmpty($SSHKeySrc)) { + $keyPaths = @( + $LocalKey, + (Join-Path (Split-Path $ProjectRoot) "internal-scripts\ssh\sshKey"), + "$env:TEMP\dune-tunnel-key", + "$env:TEMP\dune-awakening-server-sshKey" + ) + foreach ($kp in $keyPaths) { + if (Test-Path $kp) { + $SSHKeySrc = $kp + break + } + } +} + +if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc)) { + Write-Host "[ERROR] SSH key not found. Set ssh_key in settings.yaml or place key in:" -ForegroundColor Red + Write-Host " - $ProjectRoot\internal-scripts\ssh\sshKey" -ForegroundColor Yellow + Write-Host " - (parent)\internal-scripts\ssh\sshKey" -ForegroundColor Yellow + Write-Host " - %TEMP%\dune-tunnel-key" -ForegroundColor Yellow + exit 1 +} + +# Copy key to temp with proper permissions +$SSHKey = "$env:TEMP\dune-tunnel-key" +$ResolvedSrc = [System.IO.Path]::GetFullPath($SSHKeySrc) +$ResolvedDest = [System.IO.Path]::GetFullPath($SSHKey) +if ($ResolvedSrc -ne $ResolvedDest) { + Copy-Item $SSHKeySrc $SSHKey -Force +} +try { + $acl = Get-Acl $SSHKey -ErrorAction SilentlyContinue + if ($acl) { + $acl.SetAccessRuleProtection($true, $false) + $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow") + $acl.SetAccessRule($rule) + Set-Acl -Path $SSHKey -AclObject $acl -ErrorAction SilentlyContinue + } +} catch {} + +Write-Host "" +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host " Dune Awakening Dashboard" -ForegroundColor Cyan +Write-Host "============================================================" -ForegroundColor Cyan +Write-Host "" + +# Kill any existing SSH tunnels on the target port +Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object { + Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue +} +Start-Sleep 1 + +Write-Host "[1/4] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow +$sshArgs = @( + "-i", $SSHKey, + "-o", "StrictHostKeyChecking=accept-new", + "-o", "ServerAliveInterval=30", + "-o", "ServerAliveCountMax=3", + "-L", "${LocalPort}:localhost:${LocalPort}", + "-N", "${SSHUser}@${SSHHost}" +) +$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden + +$connected = $false +for ($i = 0; $i -lt 30; $i++) { + Start-Sleep -Seconds 1 + if ($sshTunnel.HasExited) { + Write-Host "[ERROR] SSH tunnel exited (code: $($sshTunnel.ExitCode))" -ForegroundColor Red + exit 1 + } + try { + $tcp = New-Object System.Net.Sockets.TcpClient + $tcp.Connect("127.0.0.1", $LocalPort) + $tcp.Close() + $connected = $true + break + } catch {} +} +if (-not $connected) { + Write-Host "[ERROR] SSH tunnel did not connect within 30s" -ForegroundColor Red + Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue + exit 1 +} +Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green + +# Start DB port-forward on VM +Write-Host "[2/4] Starting DB port-forward on VM..." -ForegroundColor Yellow +$DBService = "${Namespace}-db-dbdepl-svc" + +# Try to find the actual DB service name if the default fails +$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${SSHHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null +if ($pfCheck) { + $dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1 + if ($dbSvc) { + $DBService = $dbSvc -replace 'service/', '' + Write-Host " Found DB service: $DBService" -ForegroundColor Green + } +} + +$RemotePort = 15432 +$pfCmd = "ssh -i `"$SSHKey`" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 ${SSHUser}@${SSHHost} `"nohup sudo kubectl port-forward -n ${Namespace} svc/${DBService} ${LocalPort}:${RemotePort} > /tmp/pf.log 2>&1 &`"" +cmd /c $pfCmd +Start-Sleep -Seconds 5 + +# Check DB +Write-Host "[3/4] Checking database..." -ForegroundColor Yellow +$dbTest = $false +for ($i = 0; $i -lt 15; $i++) { + try { + $result = python -W ignore -c "import psycopg2; c = psycopg2.connect(host='localhost', port=$LocalPort, user='postgres', password='postgres', dbname='dune', connect_timeout=3); c.close(); print('ok')" 2>$null + if ($result -match 'ok') { $dbTest = $true; break } + } catch {} + Start-Sleep -Seconds 1 +} +if (-not $dbTest) { + Write-Host "[ERROR] Database connection failed." -ForegroundColor Red + Write-Host "Checking port-forward log on VM..." -ForegroundColor Yellow + $pfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${SSHHost} "cat /tmp/pf.log" 2>$null + if ($pfLog) { Write-Host $pfLog -ForegroundColor Red } + else { Write-Host "Log empty or unreadable." -ForegroundColor Yellow } + Write-Host "" + Write-Host "Verify DB service exists:" -ForegroundColor Yellow + Write-Host " ssh -i $SSHKey ${SSHUser}@${SSHHost} 'sudo kubectl get svc -n $Namespace'" -ForegroundColor Cyan + exit 1 +} +Write-Host "[OK] Database connected" -ForegroundColor Green + +# Check dependencies +Write-Host "[4/4] Starting dashboard..." -ForegroundColor Yellow +$pipCheck = python -c "import flask_socketio, yaml, flask_login" 2>$null +if ($LASTEXITCODE -ne 0) { + Write-Host " Installing dependencies..." -ForegroundColor Yellow + pip install -r (Join-Path $ProjectRoot "requirements.txt") --quiet +} + +Set-Location -LiteralPath $ProjectRoot +python run.py + +# Cleanup +Write-Host "Stopping tunnels..." -ForegroundColor Cyan +Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue +$pkillCmd = "ssh -i `"$SSHKey`" -o StrictHostKeyChecking=accept-new ${SSHUser}@${SSHHost} `"pkill -f kubectl-port-forward`"" +cmd /c $pkillCmd 2>$null diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..aa5a67b --- /dev/null +++ b/start.sh @@ -0,0 +1,144 @@ +#!/bin/bash +# Dune Awakening Dashboard Launcher (Linux/macOS) +# Starts SSH tunnel, DB port-forward, then runs the dashboard + +set -e + +PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)" +SETTINGS_FILE="$PROJECT_ROOT/settings.yaml" + +# Determine Python command +PYTHON="" +if command -v python3 &>/dev/null; then + PYTHON="python3" +elif command -v python &>/dev/null; then + PYTHON="python" +else + echo "[ERROR] Python not found. Install Python 3.8+ first." + exit 1 +fi + +# Check if settings exist +if [ ! -f "$SETTINGS_FILE" ]; then + echo "[WARN] settings.yaml not found. Running setup..." + bash "$PROJECT_ROOT/setup.sh" + if [ ! -f "$SETTINGS_FILE" ]; then + echo "[ERROR] Setup failed." + exit 1 + fi +fi + +# Read settings safely via Python +eval "$($PYTHON -c " +import yaml, json, os, sys +with open('$SETTINGS_FILE') as f: + s = yaml.safe_load(f) or {} +ssh_key = s.get('server', {}).get('ssh_key') or '' +print(f'SSH_HOST=\"{s.get(\"server\", {}).get(\"host\", \"\")}\"') +print(f'SSH_USER=\"{s.get(\"server\", {}).get(\"user\", \"dune\")}\"') +print(f'SSH_KEY=\"{ssh_key}\"') +print(f'LOCAL_PORT={s.get(\"database\", {}).get(\"port\", 15433)}') +print(f'DASHBOARD_PORT={s.get(\"dashboard\", {}).get(\"port\", 5050)}') +print(f'NAMESPACE=\"{s.get(\"kubernetes\", {}).get(\"namespace\", \"\")}\"') +")" + +# Fallback SSH key resolution +LOCAL_KEY="$PROJECT_ROOT/internal-scripts/ssh/sshKey" +if [ -z "$SSH_KEY" ] || [ ! -f "$SSH_KEY" ]; then + if [ -f "$LOCAL_KEY" ]; then + SSH_KEY="$LOCAL_KEY" + else + echo "[ERROR] SSH key not found. Set ssh_key in settings.yaml or place key at:" + echo " - $LOCAL_KEY" + echo " - /tmp/dune-tunnel-key" + exit 1 + fi +fi + +chmod 600 "$SSH_KEY" 2>/dev/null || true + +# Track SSH tunnel PID for cleanup +SSH_PID="" + +cleanup() { + echo "Stopping tunnels..." + if [ -n "$SSH_PID" ] && kill -0 "$SSH_PID" 2>/dev/null; then + kill "$SSH_PID" 2>/dev/null || true + fi + ssh -i "$SSH_KEY" -o ConnectTimeout=5 "${SSH_USER}@${SSH_HOST}" "pkill -f 'kubectl port-forward' 2>/dev/null" || true + exit 0 +} +trap cleanup EXIT INT TERM + +echo "" +echo "============================================================" +echo " Dune Awakening Dashboard" +echo "============================================================" +echo "" + +echo "[1/4] Starting SSH tunnel (localhost:$LOCAL_PORT -> VM)..." +ssh -i "$SSH_KEY" \ + -o StrictHostKeyChecking=accept-new \ + -o ServerAliveInterval=30 \ + -o ServerAliveCountMax=3 \ + -L "${LOCAL_PORT}:localhost:${LOCAL_PORT}" \ + -N -f "${SSH_USER}@${SSH_HOST}" + +# Get the PID of the background SSH process +if command -v pgrep &>/dev/null; then + SSH_PID=$(pgrep -f "ssh.*${SSH_HOST}.*${LOCAL_PORT}.*-N" | head -1) +else + SSH_PID=$(ps aux | grep "ssh.*${SSH_HOST}.*${LOCAL_PORT}.*-N" | grep -v grep | awk '{print $2}' | head -1) +fi + +sleep 3 +echo "[OK] SSH tunnel up on localhost:$LOCAL_PORT" + +echo "[2/4] Starting DB port-forward on VM..." + +# Auto-detect DB service name +DB_SVC=$(ssh -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${SSH_USER}@${SSH_HOST}" "sudo kubectl get svc -n ${NAMESPACE} -o name 2>/dev/null" | grep -E 'db.*svc|postgres' | head -1 | sed 's|service/||') +if [ -z "$DB_SVC" ]; then + DB_SVC="${NAMESPACE}-db-dbdepl-svc" +fi + +ssh -i "$SSH_KEY" \ + -o StrictHostKeyChecking=accept-new \ + -o ServerAliveInterval=30 \ + "${SSH_USER}@${SSH_HOST}" \ + "nohup sudo kubectl port-forward -n ${NAMESPACE} svc/${DB_SVC} ${LOCAL_PORT}:15432 > /tmp/pf.log 2>&1 &" + +sleep 5 + +echo "[3/4] Checking database connection..." +DB_OK=false +for i in $(seq 1 15); do + if $PYTHON -c "import psycopg2; psycopg2.connect(host='localhost', port=$LOCAL_PORT, user='postgres', password='postgres', dbname='dune', connect_timeout=3).close()" 2>/dev/null; then + DB_OK=true + break + fi + sleep 1 +done + +if [ "$DB_OK" = true ]; then + echo "[OK] Database connected" +else + echo "[ERROR] Database connection failed." + echo "Checking port-forward log on VM..." + ssh -i "$SSH_KEY" -o ConnectTimeout=10 "${SSH_USER}@${SSH_HOST}" "cat /tmp/pf.log" 2>/dev/null || echo "Log empty or unreadable." + echo "" + echo "Verify DB service exists:" + echo " ssh -i $SSH_KEY ${SSH_USER}@${SSH_HOST} 'sudo kubectl get svc -n $NAMESPACE'" + exit 1 +fi + +echo "[4/4] Starting dashboard..." + +# Check dependencies +if ! $PYTHON -c "import flask_socketio, yaml, flask_login" 2>/dev/null; then + echo " Installing dependencies..." + $PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet +fi + +cd "$PROJECT_ROOT" +$PYTHON run.py diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..15aa30d --- /dev/null +++ b/static/style.css @@ -0,0 +1,631 @@ +:root { + --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); +} + +* { margin: 0; padding: 0; box-sizing: border-box; } + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + background: var(--bg); + color: var(--text); + line-height: 1.5; +} + +/* Top Navigation */ +nav { + background: var(--nav-bg); + padding: 0 24px; + display: flex; + align-items: center; + gap: 4px; + height: 52px; + position: sticky; + top: 0; + z-index: 100; + box-shadow: 0 1px 4px rgba(0,0,0,0.2); +} + +nav .brand { + color: var(--primary); + font-weight: 700; + font-size: 15px; + margin-right: 24px; + letter-spacing: 0.5px; + white-space: nowrap; +} + +nav a { + color: var(--nav-text); + text-decoration: none; + padding: 0 14px; + height: 52px; + display: flex; + align-items: center; + font-size: 13px; + font-weight: 500; + border-bottom: 2px solid transparent; + transition: all 0.15s; +} + +nav a:hover { color: #fff; background: rgba(255,255,255,0.05); } +nav a.active { + color: var(--nav-active); + border-bottom-color: var(--nav-active); +} + +nav .spacer { flex: 1; } + +.conn-dot { + width: 8px; + height: 8px; + border-radius: 50%; + display: inline-block; + margin-right: 6px; +} +.conn-dot.online { background: var(--success); } +.conn-dot.offline { background: var(--danger); } + +/* Container */ +.container { max-width: 1400px; margin: 0 auto; padding: 24px; } + +/* Error Banners */ +.error-banner { + background: #fff3cd; + border: 1px solid #ffc107; + color: #856404; + padding: 16px 24px; + border-radius: 8px; + margin-bottom: 20px; + font-size: 14px; +} + +.error-banner.danger { + background: #f8d7da; + border-color: #f5c6cb; + color: #721c24; +} + +.error-banner code { + background: rgba(0,0,0,0.06); + padding: 2px 6px; + border-radius: 3px; + font-size: 13px; +} + +/* Page Header */ +.page-header { + margin-bottom: 24px; +} +.page-header h1 { + font-size: 24px; + font-weight: 700; + color: var(--text); +} +.page-header p { + color: var(--text-light); + font-size: 14px; + margin-top: 4px; +} + +/* Vitals Bar */ +.vitals-bar { + display: flex; + align-items: center; + background: var(--card-bg); + border: 1px solid var(--border); + border-radius: 8px; + padding: 12px 20px; + margin-bottom: 20px; + gap: 0; +} +.vitals-item { + display: flex; + align-items: center; + gap: 8px; +} +.vitals-label { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 1px; + color: var(--text-muted); + font-weight: 600; +} +.vitals-value { + font-size: 15px; + font-weight: 700; + font-family: 'Courier New', monospace; +} +.vitals-divider { + width: 1px; + height: 28px; + background: var(--border); + margin: 0 24px; +} + +/* Stat Cards */ +.stats-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + gap: 16px; + margin-bottom: 32px; +} + +.stat-card { + background: var(--card-bg); + border-radius: 12px; + padding: 20px; + box-shadow: var(--shadow); + transition: transform 0.1s; +} +.stat-card:hover { transform: translateY(-1px); } + +.stat-card .label { + font-size: 12px; + text-transform: uppercase; + letter-spacing: 1px; + color: var(--text-muted); + font-weight: 600; +} + +.stat-card .value { + font-size: 32px; + font-weight: 700; + color: var(--text); + margin-top: 4px; +} + +.stat-card .value.online { color: var(--success); } + +/* Cards */ +.card { + background: var(--card-bg); + border-radius: 12px; + box-shadow: var(--shadow); + margin-bottom: 20px; + overflow: hidden; +} + +.card-header { + padding: 16px 20px; + border-bottom: 1px solid var(--border); + font-weight: 600; + font-size: 15px; + display: flex; + align-items: center; + justify-content: space-between; +} + +.card-body { padding: 20px; } +.card-body:empty { display: none; } + +/* Tables */ +.table-wrap { overflow-x: auto; } + +table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +thead th { + background: #f8f6f2; + padding: 10px 14px; + text-align: left; + font-weight: 600; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.5px; + color: var(--text-light); + border-bottom: 2px solid var(--border); + white-space: nowrap; + cursor: pointer; + user-select: none; +} + +thead th:hover { color: var(--text); } +thead th.sort-asc::after { content: ' \25B2'; font-size: 10px; } +thead th.sort-desc::after { content: ' \25BC'; font-size: 10px; } + +tbody td { + padding: 10px 14px; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} + +tbody tr:hover { background: var(--hover); } +tbody tr:last-child td { border-bottom: none; } + +td a { + color: var(--accent); + text-decoration: none; + font-weight: 500; +} +td a:hover { text-decoration: underline; } + +/* Filters */ +.filters { + display: flex; + gap: 12px; + align-items: center; + flex-wrap: wrap; + margin-bottom: 16px; +} + +.filters input, .filters select { + padding: 8px 12px; + border: 1px solid var(--border); + border-radius: 6px; + font-size: 13px; + background: var(--card-bg); + color: var(--text); + min-width: 160px; +} + +.filters input:focus, .filters select:focus { + outline: none; + border-color: var(--primary); + box-shadow: 0 0 0 3px rgba(201,162,78,0.15); +} + +.filters button { + padding: 8px 16px; + background: var(--primary); + color: #fff; + border: none; + border-radius: 6px; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background 0.15s; +} + +.filters button:hover { background: var(--primary-dark); } + +/* Faction Badges */ +.badge { + display: inline-block; + padding: 2px 10px; + border-radius: 12px; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.3px; +} + +.badge-atreides { background: #1a5276; color: #fff; } +.badge-harkonnen { background: #7b241c; color: #fff; } +.badge-smuggler { background: #7d6608; color: #fff; } +.badge-none { background: #566573; color: #fff; } +.badge-neutral { background: #566573; color: #fff; } + +.badge-leader { background: #f39c12; color: #fff; } +.badge-officer { background: #3498db; color: #fff; } +.badge-member { background: #95a5a6; color: #fff; } + +.badge-online { background: #27ae60; color: #fff; } +.badge-offline { background: #95a5a6; color: #fff; } +.badge-alive { background: #27ae60; color: #fff; } +.badge-dead { background: #c0392b; color: #fff; } +.badge-solaris { background: #8e44ad; color: #fff; } + +/* Guild Cards Grid */ +.guild-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 16px; +} + +.guild-card { + background: var(--card-bg); + border-radius: 12px; + padding: 20px; + box-shadow: var(--shadow); + cursor: pointer; + transition: transform 0.1s, box-shadow 0.1s; + text-decoration: none; + color: var(--text); + display: block; +} + +.guild-card:hover { + transform: translateY(-2px); + box-shadow: 0 4px 16px rgba(44,24,16,0.12); +} + +.guild-card h3 { + font-size: 16px; + margin-bottom: 4px; +} + +.guild-card .meta { + font-size: 13px; + color: var(--text-light); + margin-top: 8px; +} + +.guild-card .meta span { + margin-right: 16px; +} + +/* Detail sections */ +.detail-section { + margin-bottom: 24px; +} + +.detail-section h2 { + font-size: 16px; + font-weight: 700; + color: var(--text); + margin-bottom: 12px; + padding-bottom: 8px; + border-bottom: 2px solid var(--primary); +} + +.detail-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 12px; +} + +.detail-item .dlabel { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 1px; + color: var(--text-muted); + font-weight: 600; +} + +.detail-item .dvalue { + font-size: 14px; + font-weight: 500; + margin-top: 2px; + word-break: break-word; +} + +/* Inventory */ +.inv-type { + font-weight: 600; + margin: 12px 0 8px; + font-size: 14px; +} + +.inv-type:first-child { margin-top: 0; } + +/* Info box */ +.info-box { + background: #eaf2f8; + border: 1px solid #d4e6f1; + color: #1a5276; + padding: 16px 20px; + border-radius: 8px; + font-size: 14px; + margin-bottom: 20px; +} + +.info-box code { + background: rgba(0,0,0,0.06); + padding: 2px 6px; + border-radius: 3px; +} + +/* Empty state */ +.empty { + text-align: center; + padding: 40px 20px; + color: var(--text-muted); + font-size: 14px; +} + +/* Bar chart */ +.faction-bar { + display: flex; + align-items: center; + gap: 8px; + margin: 4px 0; + font-size: 13px; +} + +.faction-bar .bar-bg { + flex: 1; + height: 24px; + background: #e8e4dc; + border-radius: 4px; + overflow: hidden; + position: relative; +} + +.faction-bar .bar-fill { + height: 100%; + border-radius: 4px; + transition: width 0.3s; + min-width: 2px; +} + +.faction-bar .bar-fill.atreides { background: #1a5276; } +.faction-bar .bar-fill.harkonnen { background: #7b241c; } +.faction-bar .bar-fill.smuggler { background: #7d6608; } +.faction-bar .bar-fill.none { background: #566573; } +.faction-bar .bar-fill.neutral { background: #566573; } + +.faction-bar .bar-label { + min-width: 100px; + white-space: nowrap; +} + +.faction-bar .bar-count { + min-width: 40px; + text-align: right; + font-weight: 600; +} + +/* Responsive */ +@media (max-width: 768px) { + .container { padding: 16px; } + .stats-grid { grid-template-columns: repeat(2, 1fr); } + .guild-grid { grid-template-columns: 1fr; } + nav .brand { font-size: 13px; margin-right: 12px; } + nav a { padding: 0 8px; font-size: 12px; } + .filters { flex-direction: column; align-items: stretch; } + .filters input, .filters select { min-width: auto; } +} + +/* Edit Buttons */ +.btn-edit { + background: var(--primary); + color: #fff; + border: none; + border-radius: 4px; + padding: 4px 10px; + font-size: 12px; + font-weight: 600; + cursor: pointer; + margin-left: 8px; +} +.btn-edit:hover { background: var(--primary-dark); } + +.btn-save { + background: var(--success); + color: #fff; + border: none; + border-radius: 4px; + padding: 8px 16px; + font-size: 13px; + font-weight: 600; + cursor: pointer; +} +.btn-save:hover { background: #219a52; } + +.btn-cancel { + background: var(--text-muted); + color: #fff; + border: none; + border-radius: 4px; + padding: 8px 16px; + font-size: 13px; + font-weight: 600; + cursor: pointer; +} +.btn-cancel:hover { background: #7a6b5b; } + +.btn-danger { + background: var(--danger); + color: #fff; + border: none; + border-radius: 3px; + padding: 2px 6px; + font-size: 11px; + cursor: pointer; +} +.btn-danger:hover { background: #a93226; } + +/* Modal */ +.modal-overlay { + position: fixed; + top: 0; left: 0; right: 0; bottom: 0; + background: rgba(0,0,0,0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 200; +} + +.modal { + background: var(--card-bg); + border-radius: 12px; + padding: 24px; + box-shadow: 0 8px 32px rgba(0,0,0,0.3); + max-width: 400px; + width: 90%; + max-height: 80vh; + overflow-y: auto; +} + +.modal h3 { + margin: 0 0 16px 0; + font-size: 18px; + color: var(--text); +} + +.modal label { + display: block; + margin-bottom: 12px; + font-size: 14px; + color: var(--text); +} + +.modal label input, .modal label select { + display: block; + margin-top: 4px; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 4px; + font-size: 14px; + width: 100%; +} + +.modal-actions { + margin-top: 16px; + display: flex; + gap: 8px; + justify-content: flex-end; +} + +/* Chat Logs */ +.chat-msg { + padding: 8px 12px; + border-bottom: 1px solid var(--border); + display: flex; + align-items: baseline; + gap: 8px; + font-size: 14px; + flex-wrap: wrap; +} +.chat-msg:last-child { + border-bottom: none; +} +.chat-msg:hover { + background: var(--hover); +} +.chat-time { + font-size: 12px; + color: var(--text-muted); + font-family: monospace; + white-space: nowrap; +} +.chat-channel { + font-weight: 600; + font-size: 12px; + white-space: nowrap; +} +.chat-sender { + font-weight: 600; + color: var(--text); + white-space: nowrap; +} +.chat-text { + color: var(--text); + flex: 1; + min-width: 200px; +} +.chat-coords { + font-size: 11px; + color: var(--text-muted); + font-family: monospace; + white-space: nowrap; +} diff --git a/templates/account_detail.html b/templates/account_detail.html new file mode 100644 index 0000000..dde089e --- /dev/null +++ b/templates/account_detail.html @@ -0,0 +1,76 @@ +{% extends "base.html" %} +{% block title %}{{ account.funcom_id if account and account.funcom_id else 'Account' }} - Dune Awakening Dashboard{% endblock %} +{% block content %} + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% elif not_found %} +
Account Not Found
+{% else %} + + + +
+

Account Details

+
+
+
Funcom ID
+
{{ account.funcom_id or 'N/A' }}
+
+
+
User Hash
+
{{ account.user }}
+
+
+
Platform
+
{{ account.platform_name or 'N/A' }}
+
+
+
Platform ID
+
{{ account.platform_id or 'N/A' }}
+
+
+
+ +
+

Characters ({{ characters|length }})

+
+
+ + + + + + + + + + + + + + {% for c in characters %} + + + + + + + + + + {% else %} + + {% endfor %} + +
NameStatusActor IDMapFactionLast LoginPosition
{{ c.player_name or 'Unknown' }}{% if c.online_status %}{{ c.online_status }}{% else %}—{% endif %}{{ c.id }}{{ c.map or 'N/A' }}{% if c.faction_name %}{{ c.faction_name }}{% else %}—{% endif %}{{ c.last_login_time.strftime('%Y-%m-%d %H:%M') if c.last_login_time else 'N/A' }}{{ c.transform_text or '' }}
No characters on this account
+
+
+
+{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/accounts.html b/templates/accounts.html new file mode 100644 index 0000000..24d4d51 --- /dev/null +++ b/templates/accounts.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% block title %}Accounts - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
+ SSH Tunnel Not Detected
+ Start the SSH tunnel first, then refresh. +
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+ + + + + + + + + + + + + {% for a in accounts %} + + + + + + + + + {% else %} + + {% endfor %} + +
Funcom IDCharacterStatusUser HashPlatform IDCharacters
{{ a.funcom_id or a.platform_name or 'Unknown' }}{{ a.character_name or '—'|safe }}{% if a.online_status %}{{ a.online_status }}{% else %}—{% endif %}{{ a.user }}{{ a.platform_id or 'N/A' }}{{ a.player_count }}
No accounts found
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/admin.html b/templates/admin.html new file mode 100644 index 0000000..d407275 --- /dev/null +++ b/templates/admin.html @@ -0,0 +1,46 @@ +{% extends "base.html" %} +{% block title %}Admin - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
+
+ Upcoming Feature: Advanced admin tools (live command execution, player management, server config editor) are currently in development. +
+
+ +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% else %} + +
+
Bans ({{ bans|length }})
+
+ + + + + + {% for b in bans %} + + + + + + + + + {% else %} + + {% endfor %} + +
IDPlayerReasonStatusBanned AtExpires
{{ b.id }}{{ b.character_name or b.player_id or '-' }}{{ b.reason or '-' }}{{ 'Active' if b.active else 'Inactive' }}{{ b.banned_at.strftime('%Y-%m-%d %H:%M') if b.banned_at else '-' }}{{ b.expires_at.strftime('%Y-%m-%d %H:%M') if b.expires_at else 'Never' }}
No bans found
+
+
+ +{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..61bc5a6 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,29 @@ + + + + + + {% block title %}Dune Awakening Server Dashboard{% endblock %} + + + + +
+ {% block content %}{% endblock %} +
+ {% block scripts %}{% endblock %} + + diff --git a/templates/buildings.html b/templates/buildings.html new file mode 100644 index 0000000..a28e44b --- /dev/null +++ b/templates/buildings.html @@ -0,0 +1,93 @@ +{% extends "base.html" %} +{% block title %}Buildings - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+ + + + + + + + + + + + + + + {% for b in buildings %} + + + + + + + + + + + {% else %} + + {% endfor %} + +
IDOwnerBuilding TypeMapPowerInstancesPositionActions
{{ b.id }}{{ b.owner_name or 'Unknown' }}{{ b.class | class_name }}{{ b.map or 'N/A' }}{% if b.is_powered == 'True' %}Powered{% elif b.is_powered == 'False' %}Unpowered{% else %}?{% endif %}{{ b.instance_count }}{{ b.transform_text or '' }}
No buildings found
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/chat.html b/templates/chat.html new file mode 100644 index 0000000..03f69d2 --- /dev/null +++ b/templates/chat.html @@ -0,0 +1,139 @@ +{% extends "base.html" %} +{% block title %}Chat Logs - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+ + + + Showing last 500 log lines +
+ +
+
Loading chat logs...
+ +
+ +{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/director.html b/templates/director.html new file mode 100644 index 0000000..3a99f00 --- /dev/null +++ b/templates/director.html @@ -0,0 +1,691 @@ +{% extends "base.html" %} +{% block title %}Director - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
Loading Director data...
+ + + + + + +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/events.html b/templates/events.html new file mode 100644 index 0000000..6b74c63 --- /dev/null +++ b/templates/events.html @@ -0,0 +1,69 @@ +{% extends "base.html" %} +{% block title %}Events - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+
Game Events ({{ game_events|length }})
+
+ + + + + + {% for e in game_events %} + + + + + + + + + {% else %} + + {% endfor %} + +
TimeActorMapTypePlayerPosition
{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}{{ e.actor_id }}{{ e.map or '' }}{{ e.event_type }}{% if e.actor_name %}{{ e.actor_name }}{% else %}—{% endif %}{% if e.x %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}, {{ e.z|round(0)|int }}{% endif %}
No game events found
+
+
+ +
+
Event Log ({{ event_logs|length }})
+
+ + + + + + {% for e in event_logs %} + + + + + + + + {% else %} + + {% endfor %} + +
TimeCategoryFunctionMessageDetails
{{ e.event_time.strftime('%Y-%m-%d %H:%M') if e.event_time else '' }}{{ e.category or '' }}{{ e.function_name or '' }}{{ e.message or '' }}{% if e.meta %}
{{ e.meta | json_format }}
{% endif %}
No event logs found
+
+
+
+ +{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/file_view.html b/templates/file_view.html new file mode 100644 index 0000000..4eb0946 --- /dev/null +++ b/templates/file_view.html @@ -0,0 +1,146 @@ +{% extends "base.html" %} +{% block title %}View File - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
+
+
+
+ View Mode +
+
+ + + +
+
+
Loading file...
+ + + + +
+
+ + + +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/files.html b/templates/files.html new file mode 100644 index 0000000..9c8b201 --- /dev/null +++ b/templates/files.html @@ -0,0 +1,170 @@ +{% extends "base.html" %} +{% block title %}Files - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
+
+
+
+
+ +
+
+ +
+
+
+ + + +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/guild_detail.html b/templates/guild_detail.html new file mode 100644 index 0000000..ae1e601 --- /dev/null +++ b/templates/guild_detail.html @@ -0,0 +1,91 @@ +{% extends "base.html" %} +{% block title %}{{ guild.guild_name if guild else 'Guild' }} - Dune Awakening Dashboard{% endblock %} +{% block content %} + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% elif not_found %} +
Guild Not Found
+{% else %} + + + +
+

Guild Info

+
+
+
Faction
+
{{ guild.faction_name or 'None' }}
+
+
+
Description
+
{{ guild.guild_description or 'No description' }}
+
+
+
Members
+
{{ members|length }}
+
+
+
+ +
+

Members ({{ members|length }})

+
+
+ + + + + + + + + + + + + {% for m in members %} + + + + + + + + + {% else %} + + {% endfor %} + +
NameAccountRoleStatusMapVehicle
{{ m.player_name }}{{ m.account_email }}{{ fmt_role(m.role_id) }}{% if m.online_status == 'Online' %}Online{% else %}Offline{% endif %}{{ m.player_map or 'N/A' }}{% if m.is_driving %}{{ m.driving_vehicle_class | class_name }}{% else %}N/A{% endif %}
No members found
+
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/guilds.html b/templates/guilds.html new file mode 100644 index 0000000..da5567a --- /dev/null +++ b/templates/guilds.html @@ -0,0 +1,72 @@ +{% extends "base.html" %} +{% block title %}Guilds - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
+ SSH Tunnel Not Detected
+ Start the SSH tunnel first, then refresh. +
ssh -i $env:TEMP\dune-awakening-server-sshKey -L 15433:localhost:15433 -N dune@65.21.198.100 +
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+ + + + + + + + + + + + {% for g in guilds %} + + + + + + + + {% else %} + + {% endfor %} + +
NameFactionMembersOnlineDescription
{{ g.guild_name }}{% if g.faction_name %}{{ g.faction_name }}{% else %}Neutral{% endif %}{{ g.member_count }}{% if g.online_count %}{{ g.online_count }}{% else %}0{% endif %}{% if g.guild_description %}{{ g.guild_description[:80] }}{% if g.guild_description|length > 80 %}...{% endif %}{% else %}—{% endif %}
No guilds found
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..5bd4a77 --- /dev/null +++ b/templates/login.html @@ -0,0 +1,125 @@ + + + + + + Login - Dune Dashboard + + + + + + diff --git a/templates/overview.html b/templates/overview.html new file mode 100644 index 0000000..2d576aa --- /dev/null +++ b/templates/overview.html @@ -0,0 +1,116 @@ +{% extends "base.html" %} +{% block title %}Overview - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
+ SSH Tunnel Not Detected
+ The PostgreSQL database is not reachable. Start the SSH tunnel in a separate terminal: +

+ $key = "$env:TEMP\dune-awakening-server-sshKey"
+ ssh -i $key -L 15433:localhost:15433 -N dune@65.21.198.100 +
+{% elif db_error %} +
+ Database Error
+ {{ db_error }} +
+{% else %} +
+
+
Accounts
+
{{ account_count }}
+
+
+
Player Characters
+
{{ player_count }}
+
+
+
Online Now
+
{{ online_count }}
+
+
+
Vehicles
+
{{ vehicle_count }}
+
+
+
Buildings
+
{{ building_count }}
+
+
+
Guilds
+
{{ guild_count }}
+
+
+
Total Actors
+
{{ actor_count }}
+
+
+ +{% if players_online %} +
+
Online Players
+
+ + + + {% for p in players_online %} + + + + + + {% endfor %} + +
CharacterMapStatus
{{ p.character_name or 'Unknown' }}{{ p.map or 'N/A' }}{{ p.online_status }}
+
+
+{% endif %} + +
+
+
Faction Distribution
+
+ {% if faction_dist %} + {% set total = faction_dist | sum(attribute='count') %} + {% for f in faction_dist %} +
+ {{ 'Neutral' if f.name == 'None' else f.name }} +
+
+
+ {{ f.count }} +
+ {% endfor %} + {% else %} +
No faction data available
+ {% endif %} +
+
+
+
Players Per Map
+
+ {% if per_map %} + {% set pmap_total = per_map | sum(attribute='count') %} + {% for m in per_map %} +
+ {{ m.map }} +
+
+
+ {{ m.count }} +
+ {% endfor %} + {% else %} +
No players found on any map
+ {% endif %} +
+
+
+{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/player_detail.html b/templates/player_detail.html new file mode 100644 index 0000000..6d343d3 --- /dev/null +++ b/templates/player_detail.html @@ -0,0 +1,624 @@ +{% extends "base.html" %} +{% block title %}{{ player.player_name if player else 'Player' }} - Dune Awakening Dashboard{% endblock %} +{% block content %} + +{% if tunnel_down %} +
+ SSH Tunnel Not Detected
+ Start the SSH tunnel first, then refresh. +
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% elif not_found %} +
Player Not Found
The requested player character does not exist.
+{% else %} + + + +{% if vitals and vitals.max_health %} +
+ {% if not is_online %} + + {% endif %} +
+ Health + {{ "%.0f"|format(vitals.current_health or 0) }}/{{ "%.0f"|format(vitals.max_health or 0) }} + {% if is_online %}(base — live value may differ){% else %}(base value){% endif %} +
+
+
+ Hydration + {{ "%.1f"|format(vitals.current_hydration | float if vitals.current_hydration else 0) }} + {% if is_online %}(live){% endif %} +
+
+
+ Spice + {{ "%.0f"|format(vitals.current_spice | float if vitals.current_spice else 0) }} + {% if is_online %}(live){% endif %} +
+ {% if vitals.spice_addiction_level is not none or vitals.spice_tolerance is not none %} +
+
+ Spice Addiction + {{ "%.1f"|format(vitals.spice_addiction_level | float if vitals.spice_addiction_level else 0) }} +
+
+
+ Spice Tolerance + {{ "%.1f"|format(vitals.spice_tolerance | float if vitals.spice_tolerance else 0) }} +
+ {% endif %} + {% if is_online %} +
Player is online — edit vitals only when offline. Health shows base value only.
+ {% endif %} +
+{% endif %} + +
+

Account Info

+
+
+
Character Name
+
{{ player.player_name or 'Unknown' }}
+
+
+
Funcom ID
+
{{ player.funcom_id or 'N/A' }}
+
+
+
Email / User
+
{{ player.account_email }}
+
+
+
Platform ID
+
{{ player.platform_id or 'N/A' }}
+
+
+
Map
+
{{ player.map or 'N/A' }}
+
+
+
Position
+
{{ player.transform_text or 'N/A' }}
+
+
+
+ +{% if player.last_login_time or player.last_avatar_activity %} +
+

Activity

+
+ {% if player.last_login_time %} +
+
Last Login
+
{{ player.last_login_time.strftime('%Y-%m-%d %H:%M UTC') }}
+
+ {% endif %} + {% if player.last_avatar_activity %} +
+
Last Activity
+
{{ player.last_avatar_activity.strftime('%Y-%m-%d %H:%M UTC') }}
+
+ {% endif %} +
+
+{% endif %} + +
+
+
Faction + {% if not is_online %} + + {% endif %} +
+
+ {% if player.faction_name %} + {{ player.faction_name }} + {% if player.utc_time_faction_change %}
Since {{ player.utc_time_faction_change.strftime('%Y-%m-%d') }}{% endif %} + {% else %}
No faction
{% endif %} +
+
+
+
Guild
+
+ {% if guild %} + +
{{ guild.faction_name or 'No faction' }}
+
{{ fmt_role(guild.role_id) }}
+ {% if guild.guild_description %}

{{ guild.guild_description }}

{% endif %} + {% else %}
Not in a guild
{% endif %} +
+
+
+ +
+

Currencies

+
+
+ + + + {% for c in currency %} + + + + + {% else %} + + {% endfor %} + +
CurrencyBalance
{{ c.currency_id | currency_label }}{{ c.balance | format_number }}
No currency data
+
Note: Currency values may be stale due to game server behavior
+
+ {% if is_online %} +
Player is online — editing disabled. Log out first.
+ {% else %} + + {% endif %} +
Read-only. Balances reflect last game save — game server writes deltas on top of DB value.
+
+
+ +{% if specialization or tech_knowledge is not none %} +
+

Specialization & XP + {% if not is_online %} + + {% endif %} +

+
+
+ + + + {% for s in specialization %} + + {% endfor %} + {% if tech_knowledge is not none %} + + {% endif %} + +
TrackXPLevel
{{ s.track_type }}{{ s.xp_amount | format_number }}{{ s.level }}
Tech Knowledge Points{{ tech_knowledge | format_number }}—
+
+
+
+{% endif %} + +{% if faction_reputation %} +
+

Faction Reputation

+
+
+ + + + {% for fr in faction_reputation %} + + + + + {% endfor %} + +
FactionReputation
{{ fr.faction_name }}{{ fr.reputation_amount | format_number }}
+
+
+
+{% endif %} + +{% if landsraad_info and landsraad_info.daily_reward_charges is not none %} +
+

Landsraad

+
+
+ + + + {% if landsraad_info.daily_reward_charges is not none %} + + {% endif %} + {% if landsraad_info.last_viewed_term_id is not none %} + + {% endif %} + +
InfoValue
Daily Reward Charges{{ landsraad_info.daily_reward_charges }}
Last Viewed Term{{ landsraad_info.last_viewed_term_id }}
+
+
+
+{% endif %} + +{% if vehicles %} +
+

Vehicles ({{ vehicles|length }})

+
+
+ + + + {% for v in vehicles %} + + + + + + + + {% endfor %} + +
TypeNameMapAccessPosition
{{ v.class | class_name }}{{ v.actor_name or 'N/A' }}{{ v.map or 'N/A' }}{% if v.ownership_rank == 1 %}Owner{% elif v.ownership_rank %}Rank {{ v.ownership_rank }}{% endif %}{{ v.transform_text or '' }}
+
+
+
+{% endif %} + +{% if buildings %} +
+

Buildings ({{ buildings|length }})

+
+
+ + + + {% for b in buildings %} + + + + + + + + {% endfor %} + +
IDClassMapInstancesPosition
{{ b.id }}{{ b.class | class_name }}{{ b.map or 'N/A' }}{{ b.instance_count }}{{ b.transform_text or '' }}
+
+
+
+{% endif %} + +{% if inventories %} +
+

Inventory

+ {% if is_online %} +
Player is online — editing disabled. Log out first.
+ {% endif %} +
+
+ {% for inv in inventories %} +
{{ inv.inventory_type | inv_label }} (ID: {{ inv.id }}, Slots: {{ inv.max_item_count or '?' }}, Volume: {{ inv.max_item_volume or '?' }}) + {% if not is_online %} + + {% endif %} +
+ {% if inv.item_list %} +
+ + {% if not is_online %}{% endif %} + + {% for item in inv.item_list %} + + + + + + {% if not is_online %}{% endif %} + + {% endfor %} + +
TemplateStackQualityNewActions
{{ item.template_id }}{{ item.stack_size }} {% if not is_online %}{% endif %}{{ item.quality_level or 0 }} {% if not is_online %}{% endif %}{{ item.is_new or False }}
+
+ {% else %} +

(empty)

+ {% endif %} + {% endfor %} +
+
+
+{% endif %} + +{% if landclaims %} +
+

Land Claims ({{ landclaims|length }})

+
+
+ + + + {% for lc in landclaims %} + + + + + + + {% endfor %} + +
IDClassMapPosition
{{ lc.id }}{{ lc.class | class_name }}{{ lc.map or 'N/A' }}{{ lc.transform_text or '' }}
+
+
+
+{% endif %} + + + + + + + + + + + + + + + + +{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/players.html b/templates/players.html new file mode 100644 index 0000000..dc4ebba --- /dev/null +++ b/templates/players.html @@ -0,0 +1,261 @@ +{% extends "base.html" %} +{% block title %}Players - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
+ SSH Tunnel Not Detected
+ Start the SSH tunnel first, then refresh. +
ssh -i $env:TEMP\dune-awakening-server-sshKey -L 15433:localhost:15433 -N dune@65.21.198.100 +
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+ + + + + + + {% if search or sel_faction or sel_guild or sel_map or sel_online %} + Clear filters + {% endif %} +
+ +
+
+ + + + + + + + + + + + + + + + + {% for p in players %} + + + + + + + + + + + + + {% else %} + + {% endfor %} + +
NameStatusFactionGuildMapIP AddressAccountVehiclesBuildingsActions
{{ p.player_name or 'Unknown' }}{% if p.online_status %}{{ p.online_status }}{% else %}Unknown{% endif %}{% if p.faction_name %}{{ p.faction_name }}{% else %}—{% endif %}{% if p.guild_name %}{{ p.guild_name }}{% else %}—{% endif %}{{ p.map or '—'|safe }}{% if p.player_controller_id %}{{ p.ip_address or '—' }}{% else %}—{% endif %}{{ p.funcom_id or p.account_email }}{{ p.vehicle_count }}{{ p.building_count }}{% if p.player_controller_id %} {% endif %}
No players found
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file diff --git a/templates/server.html b/templates/server.html new file mode 100644 index 0000000..18cc0c7 --- /dev/null +++ b/templates/server.html @@ -0,0 +1,367 @@ +{% extends "base.html" %} +{% block title %}Server - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+
Online Players
+
{{ online_count }}
+
+
+
Overmap Players
+
{{ overmap_count }}
+
+
+
Active Servers
+
{{ active_servers|length }}
+
+
+
World Partitions
+
{{ partitions|length }}
+
+ {% if node_metrics.cpu %} +
+
Node CPU
+
{{ node_metrics.cpu }}
+
+
+
Node Memory
+
{{ node_metrics.memory }}
+
+ {% endif %} +
+ +
+
+
Players Per Map
+
+ {% if per_map %} + {% for m in per_map %} +
+ {{ m.map }} +
+
+
+ {{ m.count }} +
+ {% endfor %} + {% else %} +
No data
+ {% endif %} +
+
+ +
+
Online Players
+
+ {% if online_players %} + + {% for p in online_players %} + + + + + + {% endfor %} +
{{ p.character_name or 'Unknown' }}{{ p.map or 'N/A' }}{{ p.online_status }}
+ {% else %} +
No players online
+ {% endif %} +
+
+
+ +
+
Active Server IDs
+
+ {% if active_servers %} +
    + {% for s in active_servers %} +
  • + {{ s.server_id }} + {% if s.map %} — {{ s.map }}{% endif %} +
  • + {% endfor %} +
+ {% else %} +
No active servers
+ {% endif %} +
+
+ + +
+
World Partitions
+
+ + + + + + {% for p in partitions %} + + + + + + + + + + {% else %} + + {% endfor %} + +
Partition IDServer IDMapDimensionBlockedLabelActions
{{ p.partition_id }}{{ p.server_id }}{{ p.map }}{{ p.dimension_index }}{{ 'Yes' if p.blocked else 'No' }}{{ p.label or '' }}{% if p.deployment %}{% else %}—{% endif %}
No partitions found
+
+
+ +
+
+ Kubernetes Deployments + {% if deploys_ok %} + SSH connected + {% else %} + SSH unavailable (key not loaded or VM unreachable) + {% endif %} +
+
+ {% if deploys_ok %} +
+ + + + {% for d in deployments %} + + + + + {% endfor %} + +
DeploymentActions
{{ d.replace('deployment.apps/','') }} + + + + +
+
+ {% else %} +

+ To enable server control, ensure the SSH key is available at + $env:TEMP\dune-awakening-server-sshKey and the VM is reachable. +

+ {% if ssh_error %} +
{{ ssh_error }}
+ {% endif %} + {% endif %} + +
+
+ +
+
+ Battlegroup Control + Click "Refresh Status" to load +
+
+
+ + + + + +
+
+
Click "Refresh Status" to load battlegroup status...
+
+
+
+ +
+
+ Admin Management + Coming Soon +
+
+

+ Server admin assignment and player permission management interface. + Requires integration with game server authentication system. +

+
+
+ +
+
Pod Status
+
+ +
+
Click refresh to load pod status...
+
+
+
+ +{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/templates/shell.html b/templates/shell.html new file mode 100644 index 0000000..07e9303 --- /dev/null +++ b/templates/shell.html @@ -0,0 +1,186 @@ +{% extends "base.html" %} +{% block title %}Shell - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% else %} + +
+
+
+ VM Shell + +
+
+
+ +
+
+ Pod Shell + + +
+
+
+
+ +
+
Pods ({{ pods|length }})
+
+ + + + + + {% for pod in pods %} + + + + + + {% else %} + + {% endfor %} + +
NameRoleStatus
{{ pod.name }}{{ pod.role or 'default' }}{{ pod.status }}
No pods found
+
+
+ +{% endif %} +{% endblock %} + +{% block scripts %} + + + + + +{% endblock %} \ No newline at end of file diff --git a/templates/vehicle_detail.html b/templates/vehicle_detail.html new file mode 100644 index 0000000..81d94ec --- /dev/null +++ b/templates/vehicle_detail.html @@ -0,0 +1,78 @@ +{% extends "base.html" %} +{% block title %}Vehicle {{ vehicle.id }} - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +
+
+ Note: Health percentages are calculated against the durability cap, not the module's base max health. Correct base values are still being determined, so these numbers may not reflect actual vehicle state. Fuel data is also pending implementation. +
+
+ +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif not_found %} +
Vehicle not found
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+
Type
+
{{ vehicle.class | class_name }}
+
+
+
Owner
+
{% if vehicle.owner_name %}{{ vehicle.owner_name }}{% else %}Unknown{% endif %}
+
+
+
Map
+
{{ vehicle.map or 'N/A' }}
+
+
+
Modules
+
{{ modules|length }}
+
+
+
Fuel
+
TBD
+
+
+ +

Modules / Parts

+
+ + + + + + + + + + + + + {% for m in modules %} + + + + + + + + + {% else %} + + {% endfor %} + +
IDModuleCurrentDB Max%Damage Cause
{{ m.id }}{{ m.name }}{{ m.current }}{{ m.max }}{% set pct = (m.current / m.max * 100) if m.max > 0 else 0 %}{% if pct > 66 %}{{ "%.0f"|format(pct) }}%{% elif pct > 33 %}{{ "%.0f"|format(pct) }}%{% else %}{{ "%.0f"|format(pct) }}%{% endif %}{{ m.damage_cause or '-' }}
No modules found
+
+ +{% endif %} +{% endblock %} \ No newline at end of file diff --git a/templates/vehicles.html b/templates/vehicles.html new file mode 100644 index 0000000..cb948fd --- /dev/null +++ b/templates/vehicles.html @@ -0,0 +1,142 @@ +{% extends "base.html" %} +{% block title %}Vehicles - Dune Awakening Dashboard{% endblock %} +{% block content %} + + + +{% if tunnel_down %} +
SSH Tunnel Not Detected
+{% elif db_error %} +
Database Error: {{ db_error }}
+{% else %} + +
+
+
Total Vehicles
+
{{ vehicles|length }}
+
+
+
Currently Piloted
+
{{ vehicles|selectattr('pilot_name')|list|length }}
+
+
+
Owned by Players
+
{{ vehicles|selectattr('owner_name')|list|length }}
+
+
+ +
+ +
+ +
+
+ + + + + + + + + + + + + + + {% for v in vehicles %} + + + + + + + + + + + {% else %} + + {% endfor %} + +
IDTypeNameOwnerPiloted ByMapPositionActions
{{ v.id }}{{ v.class | class_name }}{{ v.actor_name or 'N/A' }}{% if v.owner_name %}{{ v.owner_name }}{% else %}—{% endif %}{% if v.pilot_name %}Active {{ v.pilot_name }}{% else %}—{% endif %}{{ v.map or 'N/A' }}{{ v.transform_text or '' }}
No vehicles found
+
+
+{% endif %} +{% endblock %} + +{% block scripts %} + +{% endblock %} \ No newline at end of file