Initial release - Dune Awakening Dashboard beta

This commit is contained in:
Reditus committed 2026-05-12 01:02:58 +01:00
commit 59cc98133c
51 files changed
+8428

No files matched your search

+64
View File
@@ -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/
+25
View File
@@ -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.
+91
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
"""Dune Awakening Server Dashboard - Application Package"""
+109
View File
@@ -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
+154
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
"""Routes package"""
+700
View File
@@ -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/<int:vehicle_id>', 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/<int:building_id>', 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/<int:vehicle_id>')
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/<int:vehicle_id>/')
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/<int:vehicle_id>')
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/<int:vehicle_id>')
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/<int:vehicle_id>')
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/<int:vehicle_id>')
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/<int:vehicle_id>')
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
+50
View File
@@ -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'))
+438
View File
@@ -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/<int:player_id>')
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/<int:vehicle_id>')
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/<int:guild_id>')
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] != '<none>' 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}")
+1
View File
@@ -0,0 +1 @@
"""Services package"""
+393
View File
@@ -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)
+156
View File
@@ -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
+174
View File
@@ -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)
+77
View File
@@ -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
+339
View File
@@ -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 {}
+43
View File
@@ -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
+158
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
"""Utils package"""
+51
View File
@@ -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 = {}
+41
View File
@@ -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'),
]
+1
View File
@@ -0,0 +1 @@
"""WebSocket handlers package"""
+124
View File
@@ -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
+9
View File
@@ -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
+23
View File
@@ -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)
+54
View File
@@ -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
+324
View File
@@ -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 ""
+266
View File
@@ -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 ""
+191
View File
@@ -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
+144
View File
@@ -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
+631
View File
@@ -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;
}
+76
View File
@@ -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 %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% elif not_found %}
<div class="error-banner danger"><strong>Account Not Found</strong></div>
{% else %}
<div class="page-header">
<h1>{{ account.funcom_id or account.platform_name or 'Unknown Account' }}</h1>
<p>Account ID: {{ account.id }} &middot; {{ account.user }}</p>
</div>
<div class="detail-section">
<h2>Account Details</h2>
<div class="detail-grid">
<div class="detail-item">
<div class="dlabel">Funcom ID</div>
<div class="dvalue">{{ account.funcom_id or 'N/A' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">User Hash</div>
<div class="dvalue" style="font-family:monospace;font-size:12px;">{{ account.user }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Platform</div>
<div class="dvalue">{{ account.platform_name or 'N/A' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Platform ID</div>
<div class="dvalue" style="font-size:12px;">{{ account.platform_id or 'N/A' }}</div>
</div>
</div>
</div>
<div class="detail-section">
<h2>Characters ({{ characters|length }})</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Actor ID</th>
<th>Map</th>
<th>Faction</th>
<th>Last Login</th>
<th>Position</th>
</tr>
</thead>
<tbody>
{% for c in characters %}
<tr>
<td><a href="/players/{{ c.id }}">{{ c.player_name or 'Unknown' }}</a></td>
<td>{% if c.online_status %}<span class="badge badge-{{ c.online_status.lower() }}">{{ c.online_status }}</span>{% else %}&mdash;{% endif %}</td>
<td>{{ c.id }}</td>
<td>{{ c.map or 'N/A' }}</td>
<td>{% if c.faction_name %}<span class="badge badge-{{ c.faction_name.lower() }}">{{ c.faction_name }}</span>{% else %}&mdash;{% endif %}</td>
<td style="font-size:11px;">{{ c.last_login_time.strftime('%Y-%m-%d %H:%M') if c.last_login_time else 'N/A' }}</td>
<td style="font-size:10px;font-family:monospace;max-width:180px;word-break:break-all;">{{ c.transform_text or '' }}</td>
</tr>
{% else %}
<tr><td colspan="7" class="empty">No characters on this account</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %}
+73
View File
@@ -0,0 +1,73 @@
{% extends "base.html" %}
{% block title %}Accounts - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Accounts</h1>
<p>{{ accounts|length }} accounts shown</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger">
<strong>SSH Tunnel Not Detected</strong><br>
Start the SSH tunnel first, then refresh.
</div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div class="card">
<div class="table-wrap">
<table id="accounts-table">
<thead>
<tr>
<th data-col="name">Funcom ID</th>
<th data-col="char">Character</th>
<th data-col="status">Status</th>
<th data-col="user">User Hash</th>
<th data-col="platform">Platform ID</th>
<th data-col="chars">Characters</th>
</tr>
</thead>
<tbody>
{% for a in accounts %}
<tr>
<td><a href="/accounts/{{ a.id }}">{{ a.funcom_id or a.platform_name or 'Unknown' }}</a></td>
<td>{{ a.character_name or '&mdash;'|safe }}</td>
<td>{% if a.online_status %}<span class="badge badge-{{ a.online_status.lower() }}">{{ a.online_status }}</span>{% else %}&mdash;{% endif %}</td>
<td style="font-size:11px;font-family:monospace;">{{ a.user }}</td>
<td style="font-size:11px;">{{ a.platform_id or 'N/A' }}</td>
<td>{{ a.player_count }}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">No accounts found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#accounts-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.querySelector('#accounts-table tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#accounts-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
const na = parseFloat(va), nb = parseFloat(vb);
if (!isNaN(na) && !isNaN(nb)) return isAsc ? na - nb : nb - na;
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
</script>
{% endblock %}
+46
View File
@@ -0,0 +1,46 @@
{% extends "base.html" %}
{% block title %}Admin - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Admin</h1>
<p>Server administration and bans</p>
</div>
<div class="card" style="margin-bottom:16px;">
<div class="card-body" style="padding:12px 16px;background:var(--bg-hover);border-left:3px solid var(--accent);">
<strong>Upcoming Feature:</strong> Advanced admin tools (live command execution, player management, server config editor) are currently in development.
</div>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% else %}
<div class="card">
<div class="card-header">Bans ({{ bans|length }})</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Player</th><th>Reason</th><th>Status</th><th>Banned At</th><th>Expires</th></tr>
</thead>
<tbody>
{% for b in bans %}
<tr>
<td>{{ b.id }}</td>
<td>{{ b.character_name or b.player_id or '-' }}</td>
<td>{{ b.reason or '-' }}</td>
<td><span class="badge badge-{{ 'success' if b.active else 'danger' }}">{{ 'Active' if b.active else 'Inactive' }}</span></td>
<td style="font-size:11px;">{{ b.banned_at.strftime('%Y-%m-%d %H:%M') if b.banned_at else '-' }}</td>
<td style="font-size:11px;">{{ b.expires_at.strftime('%Y-%m-%d %H:%M') if b.expires_at else 'Never' }}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">No bans found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
+29
View File
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Dune Awakening Server Dashboard{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<nav>
<div class="brand">DUNE DASHBOARD</div>
{% for href, label in nav_pages %}
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a>
{% endfor %}
<div class="spacer"></div>
<span style="font-size:12px;color:var(--nav-text);display:flex;align-items:center;">
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
{{ 'Connected' if conn_ok else 'Disconnected' }}
</span>
{% if current_user and current_user.is_authenticated %}
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
{% endif %}
</nav>
<main class="container">
{% block content %}{% endblock %}
</main>
{% block scripts %}{% endblock %}
</body>
</html>
+93
View File
@@ -0,0 +1,93 @@
{% extends "base.html" %}
{% block title %}Buildings - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Buildings / Properties</h1>
<p>{{ buildings|length }} buildings shown</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div class="card">
<div class="table-wrap">
<table id="buildings-table">
<thead>
<tr>
<th data-col="id">ID</th>
<th data-col="owner">Owner</th>
<th data-col="type">Building Type</th>
<th data-col="map">Map</th>
<th data-col="power">Power</th>
<th data-col="instances">Instances</th>
<th data-col="pos">Position</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for b in buildings %}
<tr>
<td>{{ b.id }}</td>
<td>{{ b.owner_name or 'Unknown' }}</td>
<td style="font-size:12px;">{{ b.class | class_name }}</td>
<td>{{ b.map or 'N/A' }}</td>
<td>{% if b.is_powered == 'True' %}<span class="badge badge-online">Powered</span>{% elif b.is_powered == 'False' %}<span class="badge" style="background:#666;color:#fff;">Unpowered</span>{% else %}?{% endif %}</td>
<td>{{ b.instance_count }}</td>
<td style="font-size:11px;font-family:monospace;max-width:200px;word-break:break-all;">{{ b.transform_text or '' }}</td>
<td><button class="btn-delete" data-id="{{ b.id }}" data-type="building" title="Delete">🗑️</button></td>
</tr>
{% else %}
<tr><td colspan="8" class="empty">No buildings found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#buildings-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.querySelector('#buildings-table tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#buildings-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
const na = parseFloat(va), nb = parseFloat(vb);
if (!isNaN(na) && !isNaN(nb)) return isAsc ? na - nb : nb - na;
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
document.querySelectorAll('.btn-delete').forEach(btn => {
btn.addEventListener('click', async function() {
const id = this.dataset.id;
const type = this.dataset.type;
if (!confirm(`Are you sure you want to delete this ${type}?`)) return;
try {
const resp = await fetch(`/api/${type === 'vehicle' ? 'vehicles' : 'buildings'}/${id}`, { method: 'DELETE' });
const data = await resp.json();
if (data.success) {
this.closest('tr').remove();
} else {
alert('Error: ' + (data.error || 'Failed to delete'));
}
} catch (e) {
alert('Error: ' + e.message);
}
});
});
</script>
{% endblock %}
+139
View File
@@ -0,0 +1,139 @@
{% extends "base.html" %}
{% block title %}Chat Logs - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Chat Logs</h1>
<p>Parsed from text router pod logs &middot; <span id="last-updated">Never</span></p>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center;">
<button id="refresh-chat" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh</button>
<label style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--text-light);cursor:pointer;">
<input type="checkbox" id="auto-refresh" style="cursor:pointer;"> Auto-refresh (30s)
</label>
<select id="filter-channel" style="padding:6px 12px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:13px;">
<option value="all">All Channels</option>
<option value="Proximity">Proximity</option>
<option value="Map">Map</option>
<option value="Faction">Faction</option>
<option value="Guild">Guild</option>
<option value="Party">Party</option>
<option value="Whisper">Whisper</option>
<option value="Private">Private</option>
</select>
<span style="font-size:12px;color:var(--text-muted);">Showing last 500 log lines</span>
</div>
<div id="chat-container">
<div id="chat-loading" style="text-align:center;padding:40px;color:var(--text-muted);">Loading chat logs...</div>
<div id="chat-messages" style="display:none;"></div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
const CHANNEL_COLORS = {
'Proximity': '#2ecc71',
'Map': '#3498db',
'Faction': '#e74c3c',
'Guild': '#9b59b6',
'Whisper': '#f39c12',
'Party': '#e67e22',
'Private': '#f1c40f',
};
function formatTimestamp(ts) {
if (!ts) return '';
const parts = ts.replace(/\./g, '-').split('-');
if (parts.length >= 6) {
return `${parts[0]}-${parts[1]}-${parts[2]} ${parts[3]}:${parts[4]}:${parts[5]}`;
}
return ts;
}
function renderMessages(messages) {
const container = document.getElementById('chat-messages');
const filter = document.getElementById('filter-channel').value;
const filtered = filter === 'all' ? messages : messages.filter(m => m.channel === filter);
if (filtered.length === 0) {
container.innerHTML = '<div style="text-align:center;padding:40px;color:var(--text-muted);">No chat messages found</div>';
container.style.display = 'block';
return;
}
let html = '';
for (const msg of filtered) {
const color = CHANNEL_COLORS[msg.channel] || '#95a5a6';
const time = formatTimestamp(msg.timestamp);
const coords = msg.location && msg.location.X !== 0 ? ` (${msg.location.X.toFixed(0)}, ${msg.location.Y.toFixed(0)})` : '';
const target = msg.target && msg.target !== '' ? ` &rarr; ${escapeHtml(msg.target)}` : '';
html += `<div class="chat-msg" data-channel="${msg.channel}">
<span class="chat-time">${time}</span>
<span class="chat-channel" style="color:${color};">[${msg.channel}]</span>
<span class="chat-sender">${escapeHtml(msg.sender)}</span>${target}
<span class="chat-text">${escapeHtml(msg.message)}</span>
${coords ? `<span class="chat-coords">${coords}</span>` : ''}
</div>`;
}
container.innerHTML = html;
container.style.display = 'block';
document.getElementById('chat-loading').style.display = 'none';
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function loadChat() {
const loading = document.getElementById('chat-loading');
const messages = document.getElementById('chat-messages');
loading.style.display = 'block';
messages.style.display = 'none';
try {
const resp = await fetch('/api/chat_logs');
const data = await resp.json();
if (data.success) {
renderMessages(data.messages);
document.getElementById('last-updated').textContent = `Updated ${new Date().toLocaleTimeString()}`;
} else {
loading.textContent = 'Error: ' + (data.error || 'Failed to load chat logs');
}
} catch (e) {
loading.textContent = 'Error: ' + e.message;
}
}
document.getElementById('refresh-chat')?.addEventListener('click', loadChat);
document.getElementById('filter-channel')?.addEventListener('change', () => {
const filter = document.getElementById('filter-channel').value;
document.querySelectorAll('.chat-msg').forEach(el => {
el.style.display = (filter === 'all' || el.dataset.channel === filter) ? '' : 'none';
});
});
let autoInterval = null;
document.getElementById('auto-refresh')?.addEventListener('change', function() {
if (this.checked) {
autoInterval = setInterval(loadChat, 30000);
} else {
clearInterval(autoInterval);
}
});
loadChat();
</script>
{% endblock %}
+691
View File
@@ -0,0 +1,691 @@
{% extends "base.html" %}
{% block title %}Director - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Battlegroup Director</h1>
<p>Live server stats, scaling controls, and persistent settings</p>
</div>
<div id="loading-banner" class="loading-banner">Loading Director data...</div>
<div id="error-banner" class="error-banner danger" style="display:none;"></div>
<div id="director-content" style="display:none;">
<div class="stats-grid" id="bg-stats">
<div class="stat-card">
<div class="label">Active Players</div>
<div class="value" id="stat-players">-</div>
</div>
<div class="stat-card">
<div class="label">Online</div>
<div class="value" id="stat-online" style="color:#4ade80;">-</div>
</div>
<div class="stat-card">
<div class="label">In Transit</div>
<div class="value" id="stat-transit" style="color:#fbbf24;">-</div>
</div>
<div class="stat-card">
<div class="label">In Queue</div>
<div class="value" id="stat-queue">-</div>
</div>
<div class="stat-card">
<div class="label">Login Requests</div>
<div class="value" id="stat-logins">-</div>
</div>
<div class="stat-card">
<div class="label">Travel Requests</div>
<div class="value" id="stat-travel">-</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">World Status</div>
<div class="card-body">
<div style="display:flex;gap:12px;flex-wrap:wrap;">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="force-world-closed"> Force World Closed
</label>
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="force-world-closing"> Force World Closing Soon
</label>
<button id="btn-apply-world" class="btn-action" style="padding:6px 16px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Apply</button>
<button id="btn-clear-world" class="btn-action" style="padding:6px 16px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Clear</button>
</div>
<div id="world-status-msg" style="margin-top:8px;font-size:12px;color:var(--text-muted);"></div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">Character Transfers</div>
<div class="card-body" id="char-transfer-body">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
<div>
<label>Incoming Transfers:</label>
<select id="incoming-transfers" style="width:100%;padding:6px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;margin-top:4px;">
<option value="0">Default (0)</option>
<option value="10">Deny All (10)</option>
<option value="20">From Private Only (20)</option>
<option value="30">From Official Only (30)</option>
<option value="40">Accept All (40)</option>
</select>
</div>
<div>
<label style="display:flex;align-items:center;gap:6px;margin-top:20px;">
<input type="checkbox" id="accept-outgoing"> Accept Outgoing Transfers
</label>
</div>
<div>
<label style="display:flex;align-items:center;gap:6px;">
<input type="checkbox" id="free-transfer-from"> Free Transfer From
</label>
</div>
<div>
<label style="display:flex;align-items:center;gap:6px;">
<input type="checkbox" id="free-transfer-to"> Free Transfer To
</label>
</div>
</div>
<div style="margin-top:12px;display:flex;gap:8px;">
<button id="btn-apply-transfer" class="btn-action" style="padding:6px 16px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Apply</button>
<button id="btn-clear-transfer" class="btn-action" style="padding:6px 16px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;">Clear</button>
</div>
<div id="transfer-status-msg" style="margin-top:8px;font-size:12px;color:var(--text-muted);"></div>
</div>
</div>
<h2 style="margin:24px 0 12px;">Maps &amp; Servers</h2>
<div id="maps-container"></div>
</div>
<style>
.loading-banner { padding: 20px; text-align: center; color: var(--text-muted); font-size: 14px; }
.mb-3 { margin-bottom: 16px; }
.map-card { background: var(--card-bg); border-radius: 12px; box-shadow: var(--shadow); margin-bottom: 12px; overflow: hidden; }
.map-header { padding: 10px 16px; background: var(--bg-hover); display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none; }
.map-header:hover { background: var(--border); }
.map-header h3 { margin: 0; font-size: 14px; }
.map-header .meta { display: flex; gap: 10px; align-items: center; font-size: 12px; }
.map-header .chevron { transition: transform 0.2s; font-size: 12px; }
.map-header .chevron.open { transform: rotate(180deg); }
.map-body { display: none; padding: 16px; }
.map-body.open { display: block; }
.server-row { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); font-size: 13px; align-items: center; }
.server-row:last-child { border-bottom: none; }
.server-row.header { font-weight: 600; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
.server-row.summary { padding: 4px 0; border-bottom: none; font-size: 11px; }
.server-row.summary .partition-label { font-size: 11px; }
.status-badge { padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; text-align: center; }
.status-0 { background: #374151; color: #9ca3af; }
.status-1 { background: #854d0e; color: #fbbf24; }
.status-2 { background: #7c2d12; color: #fb923c; }
.status-3 { background: #166534; color: #4ade80; }
.status-starting { background: #1e3a5f; color: #60a5fa; }
.config-row { display: flex; gap: 12px; padding: 12px 0 0; border-top: 1px solid var(--border); margin-top: 12px; flex-wrap: wrap; align-items: flex-end; }
.config-field { display: flex; flex-direction: column; gap: 4px; }
.config-field label { font-size: 11px; color: var(--text-muted); }
.config-field input, .config-field select { padding: 4px 8px; background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 4px; font-size: 13px; width: 90px; }
.config-field input[type="checkbox"] { width: auto; margin-top: 4px; }
.btn-apply-map { padding: 6px 16px; background: #27ae60; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }
.btn-apply-map:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-apply-map.applying { background: #854d0e; }
.btn-apply-map.applied { background: #166534; }
.btn-clear-map { padding: 6px 16px; background: #e74c3c; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }
.btn-clear-map:disabled { opacity: 0.5; cursor: not-allowed; }
.partition-label { font-weight: 500; }
.partition-label.igwo-green { color: #4ade80; }
.partition-label.igwo-grey { color: #9ca3af; }
.partition-label.igwo-brown { color: #fb923c; }
.map-type-badge { font-size: 10px; padding: 2px 6px; border-radius: 3px; background: var(--primary); color: #fff; text-transform: uppercase; }
.summary-partitions { display: flex; gap: 6px; flex-wrap: wrap; max-width: 500px; }
.summary-part { display: flex; gap: 4px; align-items: center; background: var(--bg); padding: 2px 8px; border-radius: 3px; font-size: 11px; }
.summary-part .name { color: var(--text); font-weight: 500; }
.summary-part .players { color: var(--text-muted); }
</style>
{% endblock %}
{% block scripts %}
<script>
let bgData = null;
let charTransferData = null;
async function loadDirector() {
const banner = document.getElementById('loading-banner');
const error = document.getElementById('error-banner');
const content = document.getElementById('director-content');
try {
const [bgResp, ctResp] = await Promise.all([
fetch('/api/director/battlegroup'),
fetch('/api/director/character_transfer')
]);
if (!bgResp.ok) throw new Error('Failed to load battlegroup data');
bgData = await bgResp.json();
if (ctResp.ok) {
charTransferData = await ctResp.json();
}
if (document.getElementById('maps-container').children.length === 0) {
renderStats();
renderMaps();
renderCharTransfer();
banner.style.display = 'none';
content.style.display = 'block';
} else {
updateStats();
updateMapCards();
}
} catch (e) {
banner.style.display = 'none';
error.textContent = 'Error loading Director: ' + e.message;
error.style.display = 'block';
}
}
function updateStats() {
const t = calcTotals();
document.getElementById('stat-players').textContent = t.total;
document.getElementById('stat-online').textContent = t.online;
document.getElementById('stat-transit').textContent = t.transit;
document.getElementById('stat-queue').textContent = t.queue;
document.getElementById('stat-logins').textContent = bgData.numLoginRequestsTotal || 0;
document.getElementById('stat-travel').textContent = bgData.numTravelRequestsTotal || 0;
}
function updateMapCards() {
const allMaps = [
...Object.entries(bgData.dimensionMaps || {}).map(([n, d]) => [n, d, 'dimension']),
...Object.entries(bgData.instancedMaps || {}).map(([n, d]) => [n, d, 'instanced']),
...Object.entries(bgData.singleServerMaps || {}).map(([n, d]) => [n, d, 'single']),
];
for (const [mapName, mapData, type] of allMaps) {
const card = document.querySelector(`.map-card[data-map="${mapName}"]`);
if (!card) continue;
let servers = [];
if (type === 'dimension') servers = objToArray(mapData.serversByDimension);
else if (type === 'instanced') servers = objToArray(mapData.instances);
else servers = [mapData];
const total = servers.reduce((s, sv) => s + (sv.numPlayersInGame || 0), 0);
const online = servers.reduce((s, sv) => s + (sv.numPlayersOnline || 0), 0);
const queue = servers.reduce((s, sv) => s + (sv.numPlayersInQueue || 0), 0);
const meta = card.querySelector('.map-header .meta');
if (meta) {
const playerSpan = meta.querySelector('.map-players');
const onlineSpan = meta.querySelector('.map-online');
const queueSpan = meta.querySelector('.map-queue');
if (playerSpan) playerSpan.textContent = `Players: ${total}`;
if (onlineSpan) onlineSpan.textContent = `Online: ${online}`;
if (queueSpan) queueSpan.textContent = queue ? `Queue: ${queue}` : '';
}
for (const s of servers) {
const label = s.partition?.label || s.label || '';
const row = card.querySelector(`.server-row[data-label="${label}"]`);
if (!row) continue;
const cells = row.querySelectorAll('span');
if (cells.length >= 6) {
cells[2].textContent = s.numPlayersInGame || 0;
cells[3].textContent = s.numPlayersOnline || 0;
cells[4].textContent = s.numPlayersInQueue ?? 'N/A';
const badge = cells[5];
badge.textContent = getStatusText(s);
badge.className = `status-badge ${getStatusClass(s)}`;
}
}
const summaryParts = card.querySelectorAll('.summary-part');
for (let i = 0; i < servers.length && i < summaryParts.length; i++) {
const s = servers[i];
const playersSpan = summaryParts[i].querySelector('.players');
if (playersSpan) playersSpan.textContent = s.numPlayersInGame || 0;
const nameSpan = summaryParts[i].querySelector('.name');
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
}
}
}
function calcTotals() {
let total = 0, online = 0, transit = 0, queue = 0;
for (const maps of [bgData.dimensionMaps || {}, bgData.instancedMaps || {}, bgData.singleServerMaps || {}]) {
for (const [mapName, mapData] of Object.entries(maps)) {
if (mapData.serversByDimension) {
for (const s of objToArray(mapData.serversByDimension)) {
total += s.numPlayersInGame || 0;
online += s.numPlayersOnline || 0;
transit += s.numPlayersInTransit || 0;
queue += s.numPlayersInQueue || 0;
}
} else if (mapData.instances) {
for (const s of objToArray(mapData.instances)) {
total += s.numPlayersInGame || 0;
online += s.numPlayersOnline || 0;
transit += s.numPlayersInTransit || 0;
queue += s.numPlayersInQueue || 0;
}
} else {
total += mapData.numPlayersInGame || 0;
online += mapData.numPlayersOnline || 0;
transit += mapData.numPlayersInTransit || 0;
queue += mapData.numPlayersInQueue || 0;
}
}
}
return { total, online, transit, queue };
}
function renderStats() {
const t = calcTotals();
document.getElementById('stat-players').textContent = t.total;
document.getElementById('stat-online').textContent = t.online;
document.getElementById('stat-transit').textContent = t.transit;
document.getElementById('stat-queue').textContent = t.queue;
document.getElementById('stat-logins').textContent = bgData.numLoginRequestsTotal || 0;
document.getElementById('stat-travel').textContent = bgData.numTravelRequestsTotal || 0;
}
function renderCharTransfer() {
if (!charTransferData) return;
const cfg = charTransferData.config || {};
document.getElementById('force-world-closed').checked = cfg.forceIsWorldClosed || false;
document.getElementById('force-world-closing').checked = cfg.forceIsWorldClosingSoon || false;
document.getElementById('incoming-transfers').value = cfg.incomingCharacterTransfers || 0;
document.getElementById('accept-outgoing').checked = cfg.acceptOutgoingCharacterTransfers || false;
document.getElementById('free-transfer-from').checked = cfg.freeToTransferCharactersFrom || false;
document.getElementById('free-transfer-to').checked = cfg.freeToTransferCharactersTo || false;
}
function objToArray(obj) {
if (!obj) return [];
if (Array.isArray(obj)) return obj;
return Object.keys(obj).sort((a, b) => parseInt(a) - parseInt(b)).map(k => obj[k]);
}
function renderMaps() {
const container = document.getElementById('maps-container');
container.innerHTML = '';
const mapTypes = [
{ key: 'dimensionMaps', label: 'dimension', maps: bgData.dimensionMaps || {} },
{ key: 'instancedMaps', label: 'instanced', maps: bgData.instancedMaps || {} },
{ key: 'singleServerMaps', label: 'single', maps: bgData.singleServerMaps || {} },
];
for (const mt of mapTypes) {
for (const [mapName, mapData] of Object.entries(mt.maps)) {
const card = document.createElement('div');
card.className = 'map-card';
card.innerHTML = buildMapCard(mapName, mapData, mt.label);
container.appendChild(card);
}
}
}
function buildMapCard(mapName, mapData, type) {
const cfg = mapData.cfg || {};
let serversHtml = '';
let configHtml = '';
let summaryHtml = '';
if (type === 'dimension') {
const servers = objToArray(mapData.serversByDimension);
serversHtml = buildServerRows(servers);
configHtml = buildDimensionConfig(mapName, cfg);
summaryHtml = buildSummaryRow(servers);
mapData.numPlayersInGame = servers.reduce((sum, s) => sum + (s.numPlayersInGame || 0), 0);
mapData.numPlayersOnline = servers.reduce((sum, s) => sum + (s.numPlayersOnline || 0), 0);
mapData.numPlayersInQueue = servers.reduce((sum, s) => sum + (s.numPlayersInQueue || 0), 0);
} else if (type === 'instanced') {
const instances = objToArray(mapData.instances);
serversHtml = buildServerRows(instances);
configHtml = buildInstancedConfig(mapName, cfg);
summaryHtml = buildSummaryRow(instances);
mapData.numPlayersInGame = instances.reduce((sum, s) => sum + (s.numPlayersInGame || 0), 0);
mapData.numPlayersOnline = instances.reduce((sum, s) => sum + (s.numPlayersOnline || 0), 0);
mapData.numPlayersInQueue = instances.reduce((sum, s) => sum + (s.numPlayersInQueue || 0), 0);
} else {
serversHtml = buildServerRows([mapData]);
configHtml = buildSingleConfig(mapName, cfg);
summaryHtml = buildSummaryRow([mapData]);
}
const t = calcTotals();
return `
<div class="map-card" data-map="${mapName}">
<div class="map-header" onclick="toggleMap(this)">
<div style="flex:1;">
<h3>${mapName}</h3>
${summaryHtml}
</div>
<div class="meta">
<span class="map-type-badge">${type}</span>
<span class="map-players">Players: ${t.total}</span>
<span class="map-online" style="color:#4ade80;">Online: ${t.online}</span>
<span class="map-queue" ${t.queue ? '' : 'style="display:none"'}>${t.queue ? `Queue: ${t.queue}` : ''}</span>
<span class="chevron">&#9660;</span>
</div>
</div>
<div class="map-body">
<div class="server-row header">
<span>Partition</span><span>Server ID</span><span>Players</span><span>Online</span><span>Queue</span><span>Status</span>
</div>
${serversHtml}
${configHtml}
</div>
`;
}
function buildSummaryRow(servers) {
if (!servers || servers.length === 0) return '';
const parts = servers.map(s => {
const label = s.partition?.label || s.label || '';
const players = s.numPlayersInGame || 0;
return `<span class="summary-part" data-label="${label}">
<span class="name" title="${label}">${label.length > 18 ? label.substring(0,18)+'...' : label}</span>
<span class="players">${players}</span>
</span>`;
}).join('');
return `<div class="summary-partitions">${parts}</div>`;
}
function toggleMap(header) {
const body = header.nextElementSibling;
const chevron = header.querySelector('.chevron');
body.classList.toggle('open');
chevron.classList.toggle('open');
}
function getStatusText(s) {
const ready = s.lastServerState?.ready;
const starting = s.lastServerState?.isStartingMap;
if (s.status === 0) return 'Not Available';
if (s.status === 1) return 'Allocating';
if (s.status === 2) return starting ? 'Starting' : 'Not Ready';
if (s.status === 3) return ready === false ? 'Running (Not Ready)' : 'Running';
return 'Unknown';
}
function getStatusClass(s) {
if (s.status === 0) return 'status-0';
if (s.status === 1) return 'status-1';
if (s.status === 2) {
const starting = s.lastServerState?.isStartingMap;
return starting ? 'status-starting' : 'status-2';
}
if (s.status === 3) {
const ready = s.lastServerState?.ready;
return ready === false ? 'status-2' : 'status-3';
}
return 'status-0';
}
function buildServerRows(servers) {
if (!servers || servers.length === 0) return '';
return servers.map(s => {
const statusText = getStatusText(s);
const statusClass = getStatusClass(s);
const label = s.partition?.label || s.label || '';
const igwoClass = s.isGreyInIGWO ? 'igwo-grey' : s.isBrownInIGWO ? 'igwo-brown' : 'igwo-green';
return `
<div class="server-row" data-label="${label}">
<span class="partition-label ${igwoClass}">${label}</span>
<span style="font-family:monospace;font-size:11px;">${s.partition?.serverId || '-'}</span>
<span>${s.numPlayersInGame || 0}</span>
<span>${s.numPlayersOnline || 0}</span>
<span>${s.numPlayersInQueue ?? 'N/A'}</span>
<span class="status-badge ${statusClass}">${statusText}</span>
</div>
`;
}).join('');
}
function buildDimensionConfig(mapName, cfg) {
const minSrv = cfg.minServers ?? 0;
const extraSrv = cfg.numExtraServers ?? 0;
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
const phCap = cfg.playerHardCap ?? '';
return `
<div class="config-row">
<div class="config-field">
<label>Player Hard Cap</label>
<input type="number" id="cfg-${mapName}-phcap" value="${phCap}" min="1" max="10000">
</div>
<div class="config-field">
<label>Min Servers</label>
<input type="number" id="cfg-${mapName}-minsrv" value="${minSrv}" min="0" max="100">
</div>
<div class="config-field">
<label>Extra Servers</label>
<input type="number" id="cfg-${mapName}-extrasrv" value="${extraSrv}" min="0" max="100">
</div>
<div class="config-field">
<label>Auto Scale</label>
<input type="checkbox" id="cfg-${mapName}-autoscale" ${autoScale ? 'checked' : ''}>
</div>
<div class="config-field">
<label>Scale Throttle (s)</label>
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
</div>
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
</div>
`;
}
function buildInstancedConfig(mapName, cfg) {
const minSrv = cfg.minServers ?? 0;
const extraSrv = cfg.numExtraServers ?? 0;
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
const phCap = cfg.playerHardCap ?? '';
return `
<div class="config-row">
<div class="config-field">
<label>Player Hard Cap</label>
<input type="number" id="cfg-${mapName}-phcap" value="${phCap}" min="1" max="10000">
</div>
<div class="config-field">
<label>Min Servers</label>
<input type="number" id="cfg-${mapName}-minsrv" value="${minSrv}" min="0" max="100">
</div>
<div class="config-field">
<label>Extra Servers</label>
<input type="number" id="cfg-${mapName}-extrasrv" value="${extraSrv}" min="0" max="100">
</div>
<div class="config-field">
<label>Auto Scale</label>
<input type="checkbox" id="cfg-${mapName}-autoscale" ${autoScale ? 'checked' : ''}>
</div>
<div class="config-field">
<label>Scale Throttle (s)</label>
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
</div>
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
</div>
`;
}
function buildSingleConfig(mapName, cfg) {
const phCap = cfg.playerHardCap ?? '';
return `
<div class="config-row">
<div class="config-field">
<label>Player Hard Cap</label>
<input type="number" id="cfg-${mapName}-phcap" value="${phCap}" min="1" max="10000">
</div>
<button class="btn-apply-map" onclick="applyConfig('${mapName}','single', this)">Apply</button>
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
</div>
`;
}
async function applyConfig(mapName, type, btn) {
btn.disabled = true;
btn.classList.add('applying');
btn.textContent = 'Applying...';
const config = { MapName: mapName };
if (type === 'dimension') {
const phcapVal = document.getElementById(`cfg-${mapName}-phcap`).value;
const minsrvVal = document.getElementById(`cfg-${mapName}-minsrv`).value;
const extrasrvVal = document.getElementById(`cfg-${mapName}-extrasrv`).value;
const throttleVal = document.getElementById(`cfg-${mapName}-throttle`).value;
config.DimensionServerGroupConfig = {
EnforceSameHomeDimensionForAll: false,
PlayerHardCap: phcapVal ? parseInt(phcapVal) : null,
ShouldUpdatePlayerCountOnFls: false,
MinServers: minsrvVal ? parseInt(minsrvVal) : 0,
NumExtraServers: extrasrvVal ? parseInt(extrasrvVal) : 0,
EnableAutomaticInstanceScaling: document.getElementById(`cfg-${mapName}-autoscale`).checked,
InstanceScalingThrottlingSeconds: throttleVal ? parseInt(throttleVal) : 30,
DimensionOverrides: {}
};
} else if (type === 'instanced') {
const phcapVal = document.getElementById(`cfg-${mapName}-phcap`).value;
const minsrvVal = document.getElementById(`cfg-${mapName}-minsrv`).value;
const extrasrvVal = document.getElementById(`cfg-${mapName}-extrasrv`).value;
const throttleVal = document.getElementById(`cfg-${mapName}-throttle`).value;
config.ClassicalInstancingGroupConfig = {
PlayerHardCap: phcapVal ? parseInt(phcapVal) : null,
ShouldUpdatePlayerCountOnFls: false,
MinServers: minsrvVal ? parseInt(minsrvVal) : 0,
NumExtraServers: extrasrvVal ? parseInt(extrasrvVal) : 0,
EnableAutomaticInstanceScaling: document.getElementById(`cfg-${mapName}-autoscale`).checked,
InstanceScalingThrottlingSeconds: throttleVal ? parseInt(throttleVal) : 30
};
} else {
const phcapVal = document.getElementById(`cfg-${mapName}-phcap`).value;
config.SingleServerConfig = {
PlayerHardCap: phcapVal ? parseInt(phcapVal) : null,
ShouldUpdatePlayerCountOnFls: false
};
}
try {
const resp = await fetch('/api/director/update_config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
btn.classList.remove('applying');
btn.classList.add('applied');
btn.textContent = 'Applied!';
setTimeout(() => {
btn.classList.remove('applied');
btn.textContent = 'Apply';
btn.disabled = false;
}, 2000);
} catch (e) {
btn.classList.remove('applying');
btn.textContent = 'Failed';
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
}
}
async function clearConfig(mapName, btn) {
btn.disabled = true;
btn.textContent = 'Clearing...';
try {
const resp = await fetch('/api/director/clear_config', {
method: 'POST',
body: mapName
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
btn.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
} catch (e) {
btn.textContent = 'Failed';
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
}
}
document.getElementById('btn-apply-world')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Applying...';
const config = {
ForceIsWorldClosed: document.getElementById('force-world-closed').checked,
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
};
try {
const resp = await fetch('/api/director/character_transfer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
this.textContent = 'Applied!';
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
} catch (e) {
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
this.textContent = 'Apply'; this.disabled = false;
}
});
document.getElementById('btn-clear-world')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Clearing...';
try {
const resp = await fetch('/api/director/character_transfer_clear', { method: 'POST' });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
this.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
} catch (e) {
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
this.textContent = 'Clear'; this.disabled = false;
}
});
document.getElementById('btn-apply-transfer')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Applying...';
const config = {
IncomingCharacterTransfers: parseInt(document.getElementById('incoming-transfers').value),
AcceptOutgoingCharacterTransfers: document.getElementById('accept-outgoing').checked,
FreeToTransferCharactersFrom: document.getElementById('free-transfer-from').checked,
FreeToTransferCharactersTo: document.getElementById('free-transfer-to').checked
};
try {
const resp = await fetch('/api/director/character_transfer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
this.textContent = 'Applied!';
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
} catch (e) {
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
this.textContent = 'Apply'; this.disabled = false;
}
});
document.getElementById('btn-clear-transfer')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Clearing...';
try {
const resp = await fetch('/api/director/character_transfer_clear', { method: 'POST' });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
this.textContent = 'Cleared!';
setTimeout(() => { loadDirector(); }, 1500);
} catch (e) {
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
this.textContent = 'Clear'; this.disabled = false;
}
});
loadDirector();
setInterval(loadDirector, 5000);
</script>
{% endblock %}
+69
View File
@@ -0,0 +1,69 @@
{% extends "base.html" %}
{% block title %}Events - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Game Events</h1>
<p>Recent activity from the game event log</p>
<p style="font-size:11px;color:var(--text-muted);">Note: Solaris currency events may show incomplete history. Delta values may not sum to current balance.</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
<div class="card">
<div class="card-header">Game Events ({{ game_events|length }})</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Time</th><th>Actor</th><th>Map</th><th>Type</th><th>Player</th><th>Position</th></tr>
</thead>
<tbody>
{% for e in game_events %}
<tr>
<td style="font-size:11px;white-space:nowrap;">{{ e.universe_time.strftime('%Y-%m-%d %H:%M') if e.universe_time else '' }}</td>
<td>{{ e.actor_id }}</td>
<td>{{ e.map or '' }}</td>
<td>{{ e.event_type }}</td>
<td>{% if e.actor_name %}{{ e.actor_name }}{% else %}&mdash;{% endif %}</td>
<td style="font-size:11px;font-family:monospace;">{% if e.x %}{{ e.x|round(0)|int }}, {{ e.y|round(0)|int }}, {{ e.z|round(0)|int }}{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">No game events found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-header">Event Log ({{ event_logs|length }})</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Time</th><th>Category</th><th>Function</th><th>Message</th><th>Details</th></tr>
</thead>
<tbody>
{% for e in event_logs %}
<tr>
<td style="font-size:11px;white-space:nowrap;">{{ e.event_time.strftime('%Y-%m-%d %H:%M') if e.event_time else '' }}</td>
<td><span class="badge badge-{{ e.category.lower() if e.category else 'none' }}">{{ e.category or '' }}</span></td>
<td style="font-size:11px;font-family:monospace;">{{ e.function_name or '' }}</td>
<td style="font-size:12px;">{{ e.message or '' }}</td>
<td style="font-size:10px;max-width:250px;word-break:break-word;">{% if e.meta %}<pre style="margin:0;font-size:10px;white-space:pre-wrap;">{{ e.meta | json_format }}</pre>{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="5" class="empty">No event logs found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %}
+146
View File
@@ -0,0 +1,146 @@
{% extends "base.html" %}
{% block title %}View File - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>File Viewer</h1>
<p id="view-path">{{ path }}</p>
</div>
<div class="card">
<div class="card-body">
<div class="view-toolbar">
<div class="view-info">
<span id="view-mode-badge" class="badge">View Mode</span>
</div>
<div class="view-actions">
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button>
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
</div>
</div>
<div id="view-loading" style="padding:20px;text-align:center;color:var(--text-muted);">Loading file...</div>
<div id="view-error" class="error-banner danger" style="display:none;"></div>
<div id="view-success" class="error-banner success" style="display:none;">File saved successfully!</div>
<pre id="view-content" style="display:none;background:var(--bg);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;max-height:80vh;line-height:1.5;color:var(--text);"></pre>
<textarea id="edit-content" style="display:none;background:var(--bg);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;max-height:80vh;line-height:1.5;color:var(--text);border:1px solid var(--border);width:100%;min-height:60vh;font-family:monospace;resize:vertical;box-sizing:border-box;"></textarea>
</div>
</div>
<style>
.view-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.view-info { display: flex; gap: 8px; align-items: center; }
.view-actions { display: flex; gap: 8px; }
.view-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
.view-btn:hover { background: var(--bg-hover); }
.view-btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); }
.view-btn.primary:hover { background: var(--primary-dark); }
.badge { padding: 3px 10px; border-radius: 12px; font-size: 12px; background: var(--bg-hover); color: var(--text-muted); }
.badge.edit { background: var(--accent); color: #fff; }
.error-banner.success { background: #1a3a2a; border-color: #2d6a4f; color: #95d5b2; }
</style>
{% endblock %}
{% block scripts %}
<script>
const filePath = '{{ path }}';
let originalContent = '';
async function loadFile() {
const loading = document.getElementById('view-loading');
const error = document.getElementById('view-error');
const content = document.getElementById('view-content');
try {
const resp = await fetch(`/api/files/view?path=${encodeURIComponent(filePath)}`);
const data = await resp.json();
loading.style.display = 'none';
if (!data.success) {
error.textContent = 'Error: ' + (data.error || 'Failed to load file');
error.style.display = 'block';
return;
}
originalContent = data.content;
content.textContent = data.content;
content.style.display = 'block';
} catch (e) {
loading.style.display = 'none';
error.textContent = 'Request failed: ' + e.message;
error.style.display = 'block';
}
}
function toggleEdit() {
const content = document.getElementById('view-content');
const editor = document.getElementById('edit-content');
const editBtn = document.getElementById('edit-btn');
const saveBtn = document.getElementById('save-btn');
const cancelBtn = document.getElementById('cancel-btn');
const badge = document.getElementById('view-mode-badge');
editor.value = originalContent;
content.style.display = 'none';
editor.style.display = 'block';
editBtn.style.display = 'none';
saveBtn.style.display = 'inline-block';
cancelBtn.style.display = 'inline-block';
badge.textContent = 'Edit Mode';
badge.classList.add('edit');
editor.focus();
}
function cancelEdit() {
const content = document.getElementById('view-content');
const editor = document.getElementById('edit-content');
const editBtn = document.getElementById('edit-btn');
const saveBtn = document.getElementById('save-btn');
const cancelBtn = document.getElementById('cancel-btn');
const badge = document.getElementById('view-mode-badge');
content.style.display = 'block';
editor.style.display = 'none';
editBtn.style.display = 'inline-block';
saveBtn.style.display = 'none';
cancelBtn.style.display = 'none';
badge.textContent = 'View Mode';
badge.classList.remove('edit');
}
async function saveFile() {
const saveBtn = document.getElementById('save-btn');
const success = document.getElementById('view-success');
const error = document.getElementById('view-error');
const editor = document.getElementById('edit-content');
saveBtn.textContent = 'Saving...';
saveBtn.disabled = true;
success.style.display = 'none';
error.style.display = 'none';
try {
const form = new FormData();
form.append('path', filePath);
form.append('content', editor.value);
const resp = await fetch('/api/files/save', { method: 'POST', body: form });
const data = await resp.json();
if (!data.success) {
error.textContent = 'Error: ' + (data.error || 'Failed to save file');
error.style.display = 'block';
} else {
originalContent = editor.value;
document.getElementById('view-content').textContent = originalContent;
success.style.display = 'block';
setTimeout(() => { success.style.display = 'none'; }, 3000);
}
} catch (e) {
error.textContent = 'Request failed: ' + e.message;
error.style.display = 'block';
}
saveBtn.textContent = 'Save';
saveBtn.disabled = false;
}
loadFile();
</script>
{% endblock %}
+170
View File
@@ -0,0 +1,170 @@
{% extends "base.html" %}
{% block title %}Files - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>File Browser</h1>
<p>Browse server files via SSH</p>
</div>
<div class="card">
<div class="card-body">
<div class="fb-toolbar">
<div class="fb-breadcrumb" id="fb-breadcrumb"></div>
<div class="fb-actions">
<button id="fb-refresh-btn" class="fb-btn">Refresh</button>
</div>
</div>
<div id="fb-error" class="error-banner danger" style="display:none;"></div>
<div id="fb-file-list" class="fb-file-list"></div>
</div>
</div>
<style>
.fb-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 6px; margin-bottom: 12px; }
.fb-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
.fb-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; font-size: 13px; }
.fb-breadcrumb span:hover { text-decoration: underline; }
.fb-breadcrumb .sep { color: var(--text-muted); cursor: default; font-size: 11px; }
.fb-breadcrumb .sep:hover { text-decoration: none; }
.fb-breadcrumb .current { color: var(--text); cursor: default; }
.fb-breadcrumb .current:hover { text-decoration: none; }
.fb-actions { display: flex; gap: 8px; }
.fb-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
.fb-btn:hover { background: var(--bg-hover); }
.fb-file-list { }
.fb-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; }
.fb-item:hover { background: var(--bg-hover); }
.fb-item:last-child { border-bottom: none; }
.fb-icon { width: 24px; text-align: center; margin-right: 8px; font-size: 16px; }
.fb-icon.dir { color: var(--accent); }
.fb-name { flex: 1; font-size: 13px; }
.fb-name.dir { color: var(--accent); font-weight: 500; cursor: pointer; }
.fb-name.file { cursor: pointer; }
.fb-name:hover { text-decoration: underline; }
.fb-size { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 70px; text-align: right; }
.fb-date { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 130px; }
.fb-perms { color: var(--text-muted); font-size: 11px; font-family: monospace; margin-right: 12px; min-width: 80px; }
.fb-empty { padding: 20px; text-align: center; color: var(--text-muted); }
</style>
{% endblock %}
{% block scripts %}
<script>
let currentPath = '/srv';
function formatSize(sizeStr) {
if (!sizeStr || sizeStr === '-') return '';
const bytes = parseInt(sizeStr);
if (isNaN(bytes)) return sizeStr;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let size = bytes;
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
}
function renderBreadcrumb(path) {
const parts = path.split('/').filter(Boolean);
let html = '<span onclick="loadFiles(\'/\')">&#128193; /</span>';
let buildPath = '';
for (let i = 0; i < parts.length; i++) {
buildPath += '/' + parts[i];
const isLast = i === parts.length - 1;
if (isLast) {
html += `<span class="sep">/</span><span class="current">${parts[i]}</span>`;
} else {
html += `<span class="sep">/</span><span onclick="loadFiles('${buildPath.replace(/'/g, "\\'")}')">${parts[i]}</span>`;
}
}
return html;
}
async function loadFiles(path) {
currentPath = path;
const list = document.getElementById('fb-file-list');
const error = document.getElementById('fb-error');
const breadcrumb = document.getElementById('fb-breadcrumb');
error.style.display = 'none';
list.innerHTML = '<div class="fb-empty">Loading...</div>';
breadcrumb.innerHTML = renderBreadcrumb(path);
try {
const form = new FormData();
form.append('path', path);
const resp = await fetch('/api/files/list', { method: 'POST', body: form });
const data = await resp.json();
if (!data.success) {
list.innerHTML = '';
error.textContent = 'Error: ' + (data.error || 'Failed to list directory');
error.style.display = 'block';
return;
}
const files = data.files || [];
if (files.length === 0) {
list.innerHTML = '<div class="fb-empty">Empty directory</div>';
return;
}
const sorted = files.sort((a, b) => {
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
return a.name.localeCompare(b.name);
});
let html = '';
for (const f of sorted) {
const icon = f.is_dir ? '&#128193;' : getFileIcon(f.name);
const iconClass = f.is_dir ? 'dir' : '';
const nameClass = f.is_dir ? 'dir' : 'file';
const fullPath = (path === '/' ? '' : path) + '/' + f.name;
const safePath = fullPath.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const safeName = f.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const clickAction = f.is_dir
? `loadFiles('${safePath}')`
: `viewFile('${safePath}', '${safeName}')`;
html += `<div class="fb-item" onclick="${clickAction}">
<span class="fb-icon ${iconClass}">${icon}</span>
<span class="fb-name ${nameClass}">${f.name}</span>
<span class="fb-perms">${f.perms || ''}</span>
<span class="fb-size">${formatSize(f.size)}</span>
<span class="fb-date">${f.date || ''}</span>
</div>`;
}
list.innerHTML = html;
} catch (e) {
list.innerHTML = '';
error.textContent = 'Request failed: ' + e.message;
error.style.display = 'block';
}
}
function getFileIcon(name) {
const ext = name.split('.').pop().toLowerCase();
const icons = {
log: '&#128221;', txt: '&#128196;', ini: '&#9881;', cfg: '&#9881;',
json: '&#123364;', xml: '&#128196;', yaml: '&#128196;', yml: '&#128196;',
sh: '&#9881;', ps1: '&#9881;', bat: '&#9881;', cmd: '&#9881;',
zip: '&#128230;', gz: '&#128230;', tar: '&#128230;',
sql: '&#128451;', db: '&#128451;', sqlite: '&#128451;',
png: '&#127748;', jpg: '&#127748;', jpeg: '&#127748;', gif: '&#127748;', svg: '&#127748;',
pdf: '&#128214;',
md: '&#128214;', html: '&#127760;', css: '&#127912;', js: '&#128220;',
py: '&#128220;',
};
return icons[ext] || '&#128196;';
}
function viewFile(path, name) {
const ext = name.split('.').pop().toLowerCase();
const textExts = ['log', 'txt', 'ini', 'cfg', 'json', 'xml', 'yaml', 'yml', 'sh', 'ps1', 'bat', 'cmd', 'md', 'html', 'css', 'js', 'py', 'conf', 'env'];
if (textExts.includes(ext)) {
window.open(`/files/view?path=${encodeURIComponent(path)}`, '_blank');
} else {
alert('File preview is only available for text files. Download via SSH to view this file.');
}
}
document.getElementById('fb-refresh-btn')?.addEventListener('click', () => loadFiles(currentPath));
loadFiles('/srv');
</script>
{% endblock %}
+91
View File
@@ -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 %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% elif not_found %}
<div class="error-banner danger"><strong>Guild Not Found</strong></div>
{% else %}
<div class="page-header">
<h1>{{ guild.guild_name }}</h1>
<p>Guild ID: {{ guild.guild_id }}</p>
</div>
<div class="detail-section">
<h2>Guild Info</h2>
<div class="detail-grid">
<div class="detail-item">
<div class="dlabel">Faction</div>
<div class="dvalue"><span class="badge badge-{{ guild.faction_name.lower() if guild.faction_name else 'none' }}">{{ guild.faction_name or 'None' }}</span></div>
</div>
<div class="detail-item">
<div class="dlabel">Description</div>
<div class="dvalue">{{ guild.guild_description or 'No description' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Members</div>
<div class="dvalue">{{ members|length }}</div>
</div>
</div>
</div>
<div class="detail-section">
<h2>Members ({{ members|length }})</h2>
<div class="card">
<div class="table-wrap">
<table id="members-table">
<thead>
<tr>
<th data-col="name">Name</th>
<th data-col="account">Account</th>
<th data-col="role">Role</th>
<th data-col="status">Status</th>
<th data-col="map">Map</th>
<th data-col="vehicle">Vehicle</th>
</tr>
</thead>
<tbody>
{% for m in members %}
<tr>
<td><a href="/players/{{ m.actor_id }}">{{ m.player_name }}</a></td>
<td>{{ m.account_email }}</td>
<td><span class="badge badge-{{ fmt_role(m.role_id).lower() }}">{{ fmt_role(m.role_id) }}</span></td>
<td>{% if m.online_status == 'Online' %}<span class="badge badge-online">Online</span>{% else %}<span class="badge badge-offline">Offline</span>{% endif %}</td>
<td>{{ m.player_map or 'N/A' }}</td>
<td>{% if m.is_driving %}<span class="badge badge-leader">{{ m.driving_vehicle_class | class_name }}</span>{% else %}N/A{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">No members found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#members-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.querySelector('#members-table tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#members-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
</script>
{% endblock %}
+72
View File
@@ -0,0 +1,72 @@
{% extends "base.html" %}
{% block title %}Guilds - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Guilds</h1>
<p>{{ guilds|length }} guilds</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger">
<strong>SSH Tunnel Not Detected</strong><br>
Start the SSH tunnel first, then refresh.
<br><code>ssh -i $env:TEMP\dune-awakening-server-sshKey -L 15433:localhost:15433 -N dune@65.21.198.100</code>
</div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div class="card">
<div class="table-wrap">
<table id="guilds-table">
<thead>
<tr>
<th data-col="name">Name</th>
<th data-col="faction">Faction</th>
<th data-col="members">Members</th>
<th data-col="online">Online</th>
<th data-col="description">Description</th>
</tr>
</thead>
<tbody>
{% for g in guilds %}
<tr>
<td><a href="/guilds/{{ g.guild_id }}">{{ g.guild_name }}</a></td>
<td>{% if g.faction_name %}<span class="badge badge-{{ g.faction_name.lower() }}">{{ g.faction_name }}</span>{% else %}<span class="badge badge-neutral">Neutral</span>{% endif %}</td>
<td>{{ g.member_count }}</td>
<td>{% if g.online_count %}{{ g.online_count }}{% else %}0{% endif %}</td>
<td style="font-size:12px;color:var(--text-light);">{% if g.guild_description %}{{ g.guild_description[:80] }}{% if g.guild_description|length > 80 %}...{% endif %}{% else %}&mdash;{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="5" style="text-align:center;padding:20px;color:var(--text-light);">No guilds found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#guilds-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.querySelector('#guilds-table tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#guilds-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
const na = parseFloat(va), nb = parseFloat(vb);
if (!isNaN(na) && !isNaN(nb)) return isAsc ? na - nb : nb - na;
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
</script>
{% endblock %}
+125
View File
@@ -0,0 +1,125 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Dune Dashboard</title>
<style>
:root {
--bg: #0a0a0f;
--bg-card: #12121a;
--border: #2a2a3a;
--text: #e0e0e0;
--text-muted: #888;
--accent: #d4a853;
--accent-hover: #e8bc6a;
--danger: #e74c3c;
}
* { 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);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-container {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 2rem;
width: 100%;
max-width: 400px;
}
.login-header {
text-align: center;
margin-bottom: 2rem;
}
.login-header h1 {
color: var(--accent);
font-size: 1.5rem;
margin-bottom: 0.5rem;
}
.login-header p {
color: var(--text-muted);
font-size: 0.9rem;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-size: 0.9rem;
color: var(--text-muted);
}
.form-group input {
width: 100%;
padding: 0.75rem;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 4px;
color: var(--text);
font-size: 1rem;
}
.form-group input:focus {
outline: none;
border-color: var(--accent);
}
.btn-login {
width: 100%;
padding: 0.75rem;
background: var(--accent);
color: #000;
border: none;
border-radius: 4px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
margin-top: 1rem;
}
.btn-login:hover {
background: var(--accent-hover);
}
.flash-error {
background: rgba(231, 76, 60, 0.1);
border: 1px solid var(--danger);
color: var(--danger);
padding: 0.75rem;
border-radius: 4px;
margin-bottom: 1rem;
font-size: 0.9rem;
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-header">
<h1>DUNE DASHBOARD</h1>
<p>Server Administration Panel</p>
</div>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash-error">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn-login">Sign In</button>
</form>
</div>
</body>
</html>
+116
View File
@@ -0,0 +1,116 @@
{% extends "base.html" %}
{% block title %}Overview - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Server Overview</h1>
<p>Real-time statistics from the Dune Awakening game database</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger">
<strong>SSH Tunnel Not Detected</strong><br>
The PostgreSQL database is not reachable. Start the SSH tunnel in a separate terminal:
<br><br>
<code>$key = "$env:TEMP\dune-awakening-server-sshKey"</code><br>
<code>ssh -i $key -L 15433:localhost:15433 -N dune@65.21.198.100</code>
</div>
{% elif db_error %}
<div class="error-banner danger">
<strong>Database Error</strong><br>
{{ db_error }}
</div>
{% else %}
<div class="stats-grid">
<div class="stat-card">
<div class="label">Accounts</div>
<div class="value">{{ account_count }}</div>
</div>
<div class="stat-card">
<div class="label">Player Characters</div>
<div class="value">{{ player_count }}</div>
</div>
<div class="stat-card">
<div class="label">Online Now</div>
<div class="value online">{{ online_count }}</div>
</div>
<div class="stat-card">
<div class="label">Vehicles</div>
<div class="value">{{ vehicle_count }}</div>
</div>
<div class="stat-card">
<div class="label">Buildings</div>
<div class="value">{{ building_count }}</div>
</div>
<div class="stat-card">
<div class="label">Guilds</div>
<div class="value">{{ guild_count }}</div>
</div>
<div class="stat-card">
<div class="label">Total Actors</div>
<div class="value">{{ actor_count }}</div>
</div>
</div>
{% if players_online %}
<div class="card" style="margin-bottom:20px;">
<div class="card-header">Online Players</div>
<div class="table-wrap">
<table>
<thead><tr><th>Character</th><th>Map</th><th>Status</th></tr></thead>
<tbody>
{% for p in players_online %}
<tr>
<td><a href="/players/{{ p.pawn_id }}">{{ p.character_name or 'Unknown' }}</a></td>
<td>{{ p.map or 'N/A' }}</td>
<td><span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
<div class="card">
<div class="card-header">Faction Distribution</div>
<div class="card-body">
{% if faction_dist %}
{% set total = faction_dist | sum(attribute='count') %}
{% for f in faction_dist %}
<div class="faction-bar">
<span class="bar-label badge badge-{{ f.name.lower() if f.name != 'None' else 'neutral' }}">{{ 'Neutral' if f.name == 'None' else f.name }}</span>
<div class="bar-bg">
<div class="bar-fill {{ f.name.lower() if f.name != 'None' else 'neutral' }}" style="width:{{ (f.count / total * 100)|round(1) if total > 0 else 0 }}%;"></div>
</div>
<span class="bar-count">{{ f.count }}</span>
</div>
{% endfor %}
{% else %}
<div class="empty">No faction data available</div>
{% endif %}
</div>
</div>
<div class="card">
<div class="card-header">Players Per Map</div>
<div class="card-body">
{% if per_map %}
{% set pmap_total = per_map | sum(attribute='count') %}
{% for m in per_map %}
<div class="faction-bar">
<span class="bar-label" style="font-weight:600;">{{ m.map }}</span>
<div class="bar-bg">
<div class="bar-fill" style="background:var(--primary);width:{{ (m.count / pmap_total * 100)|round(1) if pmap_total > 0 else 0 }}%;"></div>
</div>
<span class="bar-count">{{ m.count }}</span>
</div>
{% endfor %}
{% else %}
<div class="empty">No players found on any map</div>
{% endif %}
</div>
</div>
</div>
{% endif %}
{% endblock %}
+624
View File
@@ -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 %}
<div class="error-banner danger">
<strong>SSH Tunnel Not Detected</strong><br>
Start the SSH tunnel first, then refresh.
</div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% elif not_found %}
<div class="error-banner danger"><strong>Player Not Found</strong><br>The requested player character does not exist.</div>
{% else %}
<div class="page-header">
<h1>{{ player.player_name }}</h1>
<p>Actor ID: {{ player.id }} &middot; Controller ID: {{ player.player_controller_id or 'N/A' }}
{% if player.online_status %}
&middot; <span class="badge badge-{{ player.online_status.lower() }}">{{ player.online_status }}</span>
{% endif %}
{% if player.life_state %}
&middot; <span class="badge badge-{{ player.life_state.lower() }}">{{ player.life_state }}</span>
{% endif %}
</p>
</div>
{% if vitals and vitals.max_health %}
<div class="vitals-bar">
{% if not is_online %}
<button onclick="openModal('vitals-modal')" class="btn-edit" style="margin-right:8px;">Edit Vitals</button>
{% endif %}
<div class="vitals-item">
<span class="vitals-label">Health</span>
<span class="vitals-value" style="color:#e74c3c;">{{ "%.0f"|format(vitals.current_health or 0) }}/{{ "%.0f"|format(vitals.max_health or 0) }}</span>
{% if is_online %}<span style="font-size:10px;color:#e67e22;margin-left:4px;">(base &mdash; live value may differ)</span>{% else %}<span style="font-size:10px;color:var(--text-muted);margin-left:4px;">(base value)</span>{% endif %}
</div>
<div class="vitals-divider"></div>
<div class="vitals-item">
<span class="vitals-label">Hydration</span>
<span class="vitals-value" style="color:#3498db;">{{ "%.1f"|format(vitals.current_hydration | float if vitals.current_hydration else 0) }}</span>
{% if is_online %}<span style="font-size:10px;color:#2ecc71;margin-left:4px;">(live)</span>{% endif %}
</div>
<div class="vitals-divider"></div>
<div class="vitals-item">
<span class="vitals-label">Spice</span>
<span class="vitals-value" style="color:#f39c12;">{{ "%.0f"|format(vitals.current_spice | float if vitals.current_spice else 0) }}</span>
{% if is_online %}<span style="font-size:10px;color:#2ecc71;margin-left:4px;">(live)</span>{% endif %}
</div>
{% if vitals.spice_addiction_level is not none or vitals.spice_tolerance is not none %}
<div class="vitals-divider"></div>
<div class="vitals-item">
<span class="vitals-label">Spice Addiction</span>
<span class="vitals-value" style="color:#9b59b6;">{{ "%.1f"|format(vitals.spice_addiction_level | float if vitals.spice_addiction_level else 0) }}</span>
</div>
<div class="vitals-divider"></div>
<div class="vitals-item">
<span class="vitals-label">Spice Tolerance</span>
<span class="vitals-value" style="color:#9b59b6;">{{ "%.1f"|format(vitals.spice_tolerance | float if vitals.spice_tolerance else 0) }}</span>
</div>
{% endif %}
{% if is_online %}
<div style="width:100%;font-size:11px;color:#e67e22;margin-top:4px;">Player is online &mdash; edit vitals only when offline. Health shows base value only.</div>
{% endif %}
</div>
{% endif %}
<div class="detail-section">
<h2>Account Info</h2>
<div class="detail-grid">
<div class="detail-item">
<div class="dlabel">Character Name</div>
<div class="dvalue">{{ player.player_name or 'Unknown' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Funcom ID</div>
<div class="dvalue">{{ player.funcom_id or 'N/A' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Email / User</div>
<div class="dvalue">{{ player.account_email }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Platform ID</div>
<div class="dvalue" style="font-size:12px;">{{ player.platform_id or 'N/A' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Map</div>
<div class="dvalue">{{ player.map or 'N/A' }}</div>
</div>
<div class="detail-item">
<div class="dlabel">Position</div>
<div class="dvalue" style="font-size:11px;font-family:monospace;">{{ player.transform_text or 'N/A' }}</div>
</div>
</div>
</div>
{% if player.last_login_time or player.last_avatar_activity %}
<div class="detail-section">
<h2>Activity</h2>
<div class="detail-grid">
{% if player.last_login_time %}
<div class="detail-item">
<div class="dlabel">Last Login</div>
<div class="dvalue">{{ player.last_login_time.strftime('%Y-%m-%d %H:%M UTC') }}</div>
</div>
{% endif %}
{% if player.last_avatar_activity %}
<div class="detail-item">
<div class="dlabel">Last Activity</div>
<div class="dvalue">{{ player.last_avatar_activity.strftime('%Y-%m-%d %H:%M UTC') }}</div>
</div>
{% endif %}
</div>
</div>
{% endif %}
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
<div class="card">
<div class="card-header">Faction
{% if not is_online %}
<button onclick="openModal('faction-modal')" class="btn-edit">Edit</button>
{% endif %}
</div>
<div class="card-body">
{% if player.faction_name %}
<span class="badge badge-{{ player.faction_name.lower() }}">{{ player.faction_name }}</span>
{% if player.utc_time_faction_change %}<br><small style="color:var(--text-light);">Since {{ player.utc_time_faction_change.strftime('%Y-%m-%d') }}</small>{% endif %}
{% else %}<div class="empty">No faction</div>{% endif %}
</div>
</div>
<div class="card">
<div class="card-header">Guild</div>
<div class="card-body">
{% if guild %}
<div><a href="/guilds/{{ guild.guild_id }}" style="font-weight:600;">{{ guild.guild_name }}</a></div>
<div><span class="badge badge-{{ guild.faction_name.lower() if guild.faction_name else 'none' }}">{{ guild.faction_name or 'No faction' }}</span></div>
<div><span class="badge badge-{{ fmt_role(guild.role_id).lower() }}">{{ fmt_role(guild.role_id) }}</span></div>
{% if guild.guild_description %}<p style="margin-top:8px;font-size:13px;color:var(--text-light);">{{ guild.guild_description }}</p>{% endif %}
{% else %}<div class="empty">Not in a guild</div>{% endif %}
</div>
</div>
</div>
<div class="detail-section">
<h2>Currencies</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>Currency</th><th>Balance</th></tr></thead>
<tbody>
{% for c in currency %}
<tr>
<td>{{ c.currency_id | currency_label }}</td>
<td style="font-weight:600;">{{ c.balance | format_number }}</td>
</tr>
{% else %}
<tr><td colspan="2" class="empty">No currency data</td></tr>
{% endfor %}
</tbody>
</table>
<div style="font-size:10px;color:var(--text-muted);padding:4px 8px;">Note: Currency values may be stale due to game server behavior</div>
</div>
{% if is_online %}
<div style="font-size:12px;color:#e67e22;padding:8px 16px;">Player is online &mdash; editing disabled. Log out first.</div>
{% else %}
<button onclick="openCurrenciesModal()" class="btn-edit" style="margin:8px 16px;">Edit</button>
{% endif %}
<div style="font-size:11px;color:var(--text-muted);padding:4px 16px 8px;">Read-only. Balances reflect last game save — game server writes deltas on top of DB value.</div>
</div>
</div>
{% if specialization or tech_knowledge is not none %}
<div class="detail-section">
<h2>Specialization & XP
{% if not is_online %}
<button onclick="openModal('spec-modal')" class="btn-edit">Edit</button>
{% endif %}
</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>Track</th><th>XP</th><th>Level</th></tr></thead>
<tbody>
{% for s in specialization %}
<tr><td>{{ s.track_type }}</td><td>{{ s.xp_amount | format_number }}</td><td>{{ s.level }}</td></tr>
{% endfor %}
{% if tech_knowledge is not none %}
<tr><td>Tech Knowledge Points</td><td>{{ tech_knowledge | format_number }}</td><td>&mdash;</td></tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% if faction_reputation %}
<div class="detail-section">
<h2>Faction Reputation</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>Faction</th><th>Reputation</th></tr></thead>
<tbody>
{% for fr in faction_reputation %}
<tr>
<td>{{ fr.faction_name }}</td>
<td style="font-weight:600;">{{ fr.reputation_amount | format_number }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% if landsraad_info and landsraad_info.daily_reward_charges is not none %}
<div class="detail-section">
<h2>Landsraad</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>Info</th><th>Value</th></tr></thead>
<tbody>
{% if landsraad_info.daily_reward_charges is not none %}
<tr><td>Daily Reward Charges</td><td>{{ landsraad_info.daily_reward_charges }}</td></tr>
{% endif %}
{% if landsraad_info.last_viewed_term_id is not none %}
<tr><td>Last Viewed Term</td><td>{{ landsraad_info.last_viewed_term_id }}</td></tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% if vehicles %}
<div class="detail-section">
<h2>Vehicles ({{ vehicles|length }})</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>Type</th><th>Name</th><th>Map</th><th>Access</th><th>Position</th></tr></thead>
<tbody>
{% for v in vehicles %}
<tr>
<td style="font-size:12px;">{{ v.class | class_name }}</td>
<td>{{ v.actor_name or 'N/A' }}</td>
<td>{{ v.map or 'N/A' }}</td>
<td>{% if v.ownership_rank == 1 %}<span class="badge badge-leader">Owner</span>{% elif v.ownership_rank %}<span class="badge badge-officer">Rank {{ v.ownership_rank }}</span>{% endif %}</td>
<td style="font-size:11px;font-family:monospace;">{{ v.transform_text or '' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% if buildings %}
<div class="detail-section">
<h2>Buildings ({{ buildings|length }})</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>ID</th><th>Class</th><th>Map</th><th>Instances</th><th>Position</th></tr></thead>
<tbody>
{% for b in buildings %}
<tr>
<td>{{ b.id }}</td>
<td style="font-size:12px;">{{ b.class | class_name }}</td>
<td>{{ b.map or 'N/A' }}</td>
<td>{{ b.instance_count }}</td>
<td style="font-size:11px;font-family:monospace;">{{ b.transform_text or '' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
{% if inventories %}
<div class="detail-section">
<h2>Inventory</h2>
{% if is_online %}
<div style="font-size:12px;color:#e67e22;padding:0 16px 8px;">Player is online &mdash; editing disabled. Log out first.</div>
{% endif %}
<div class="card">
<div class="card-body">
{% for inv in inventories %}
<div class="inv-type">{{ inv.inventory_type | inv_label }} (ID: {{ inv.id }}, Slots: {{ inv.max_item_count or '?' }}, Volume: {{ inv.max_item_volume or '?' }})
{% if not is_online %}
<button onclick="openAddItemModal({{ inv.id }})" class="btn-edit" style="font-size:11px;padding:2px 8px;">+ Add Item</button>
{% endif %}
</div>
{% if inv.item_list %}
<div class="table-wrap" style="margin-bottom:12px;">
<table>
<thead><tr><th>Template</th><th>Stack</th><th>Quality</th><th>New</th>{% if not is_online %}<th>Actions</th>{% endif %}</tr></thead>
<tbody>
{% for item in inv.item_list %}
<tr id="item-row-{{ item.id }}">
<td style="font-size:11px;max-width:300px;word-break:break-all;" id="item-template-{{ item.id }}">{{ item.template_id }}</td>
<td><span id="item-stack-{{ item.id }}">{{ item.stack_size }}</span> {% if not is_online %}<button onclick="editItem({{ item.id }}, 'stack_size', {{ item.stack_size }})" class="btn-edit" style="font-size:10px;padding:1px 5px;">&#9998;</button>{% endif %}</td>
<td><span id="item-quality-{{ item.id }}">{{ item.quality_level or 0 }}</span> {% if not is_online %}<button onclick="editItem({{ item.id }}, 'quality_level', {{ item.quality_level or 0 }})" class="btn-edit" style="font-size:10px;padding:1px 5px;">&#9998;</button>{% endif %}</td>
<td>{{ item.is_new or False }}</td>
{% if not is_online %}<td><button onclick="deleteItem({{ item.id }}, '{{ item.template_id }}')" class="btn-danger" style="font-size:10px;padding:1px 5px;">Del</button></td>{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p style="color:var(--text-muted);font-size:13px;margin-bottom:12px;">(empty)</p>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if landclaims %}
<div class="detail-section">
<h2>Land Claims ({{ landclaims|length }})</h2>
<div class="card">
<div class="table-wrap">
<table>
<thead><tr><th>ID</th><th>Class</th><th>Map</th><th>Position</th></tr></thead>
<tbody>
{% for lc in landclaims %}
<tr>
<td>{{ lc.id }}</td>
<td style="font-size:12px;">{{ lc.class | class_name }}</td>
<td>{{ lc.map or 'N/A' }}</td>
<td style="font-size:11px;font-family:monospace;">{{ lc.transform_text or '' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endif %}
<!-- Faction Edit Modal -->
<div id="faction-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('faction-modal')">
<div class="modal">
<h3>Edit Faction</h3>
<form id="faction-form" onsubmit="return submitEdit(this, '/api/edit_faction')">
<input type="hidden" name="player_controller_id" value="{{ player.player_controller_id or '' }}">
<label>Faction:
<select name="faction_id">
<option value="1" {% if player.faction_id == 1 %}selected{% endif %}>Atreides</option>
<option value="2" {% if player.faction_id == 2 %}selected{% endif %}>Harkonnen</option>
<option value="3" {% if player.faction_id == 3 %}selected{% endif %}>None</option>
<option value="4" {% if player.faction_id == 4 %}selected{% endif %}>Smuggler</option>
</select>
</label>
<div class="modal-actions">
<button type="submit" class="btn-save">Save</button>
<button type="button" onclick="closeModal('faction-modal')" class="btn-cancel">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Vitals Edit Modal -->
<div id="vitals-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('vitals-modal')">
<div class="modal" style="max-width:500px;">
<h3>Edit Vitals</h3>
<p style="font-size:12px;color:var(--text-muted);margin-bottom:12px;">Health edits the <strong>base</strong> value only (in-game max includes equipment bonuses). Hydration/Spice are clamped at 0.</p>
<form id="vitals-form" onsubmit="return submitVitalsEdit()">
<input type="hidden" name="pawn_id" value="{{ player.state_pawn_id or player.id }}">
<label>Current Health:
<input type="number" name="current_health" step="1" min="0" max="{{ vitals.max_health | int if vitals.max_health else 150 }}" value="{{ "%.0f"|format(vitals.current_health or 0) }}" style="width:100px;">
</label>
<label>Max Health (Base):
<input type="number" name="max_health" step="1" min="0" max="9999" value="{{ "%.0f"|format(vitals.max_health or 150) }}" style="width:100px;">
</label>
<label>Hydration:
<input type="number" name="current_hydration" step="0.1" min="0" value="{{ "%.1f"|format(vitals.current_hydration | float if vitals.current_hydration else 0) }}" style="width:100px;">
</label>
<label>Spice:
<input type="number" name="current_spice" step="1" min="0" value="{{ "%.0f"|format(vitals.current_spice | float if vitals.current_spice else 0) }}" style="width:100px;">
</label>
<div class="modal-actions">
<button type="submit" class="btn-save">Save</button>
<button type="button" onclick="closeModal('vitals-modal')" class="btn-cancel">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Currencies Edit Modal -->
<div id="currencies-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('currencies-modal')">
<div class="modal" style="max-width:500px;">
<h3>Edit Currencies</h3>
<p style="font-size:12px;color:var(--text-muted);margin-bottom:12px;">Current balances. Enter a positive number to add, negative to subtract.</p>
<div id="currency-forms"></div>
<div class="modal-actions" style="margin-top:12px;">
<button type="button" onclick="closeModal('currencies-modal')" class="btn-cancel">Close</button>
</div>
</div>
</div>
<!-- Specialization/XP Edit Modal -->
<div id="spec-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('spec-modal')">
<div class="modal" style="max-width:500px;">
<h3>Edit Specialization & XP</h3>
<form id="spec-form" onsubmit="return submitSpecEdit()">
<input type="hidden" name="player_id" value="{{ player.player_controller_id or '' }}">
<label>Tech Knowledge Points (XP):
<input type="number" name="xp_points" value="{{ tech_knowledge if tech_knowledge is not none else 0 }}" style="width:150px;">
</label>
<button type="submit" class="btn-save" style="margin-top:8px;">Save XP</button>
</form>
{% for s in specialization %}
<hr style="margin:12px 0;border-color:var(--border);">
<form onsubmit="return submitEdit(this, '/api/edit_xp')">
<input type="hidden" name="player_id" value="{{ player.player_controller_id or '' }}">
<input type="hidden" name="track_type" value="{{ s.track_type }}">
<label>{{ s.track_type }} — XP: <input type="number" name="xp_amount" value="{{ s.xp_amount }}" style="width:100px;">
Level: <input type="number" step="0.1" name="level" value="{{ s.level }}" style="width:80px;">
</label>
<button type="submit" class="btn-save" style="font-size:11px;padding:2px 8px;">Save</button>
</form>
{% endfor %}
<div class="modal-actions" style="margin-top:12px;">
<button type="button" onclick="closeModal('spec-modal')" class="btn-cancel">Close</button>
</div>
</div>
</div>
<!-- Add Item Modal -->
<div id="add-item-modal" class="modal-overlay" style="display:none;" onclick="if(event.target===this)closeModal('add-item-modal')">
<div class="modal">
<h3>Add Item to Inventory</h3>
<form id="add-item-form" onsubmit="return submitAddItem()">
<input type="hidden" id="add-item-inv-id" name="inventory_id" value="">
<label>Template ID: <input type="text" name="template_id" placeholder="e.g. HealthPackRecipe" style="width:250px;"></label>
<label>Stack Size: <input type="number" name="stack_size" value="1" style="width:80px;"></label>
<label>Quality Level: <input type="number" name="quality_level" value="0" style="width:80px;"></label>
<div class="modal-actions">
<button type="submit" class="btn-save">Add</button>
<button type="button" onclick="closeModal('add-item-modal')" class="btn-cancel">Cancel</button>
</div>
</form>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
function openModal(id) {
document.getElementById(id).style.display = 'flex';
}
function closeModal(id) {
document.getElementById(id).style.display = 'none';
}
async function submitEdit(form, url) {
const data = new FormData(form);
try {
const resp = await fetch(url, { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
alert('Saved successfully!');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
return false;
}
async function submitSpecEdit() {
const form = document.getElementById('spec-form');
const data = new FormData(form);
try {
const resp = await fetch('/api/edit_tech_knowledge', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
alert('XP saved!');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
return false;
}
function openCurrenciesModal() {
const container = document.getElementById('currency-forms');
container.innerHTML = '';
{% for c in currency %}
{
const div = document.createElement('div');
div.style.marginBottom = '12px';
div.innerHTML = '<label style="display:flex;align-items:center;gap:8px;">{{ c.currency_id | currency_label | safe }}: <span style="font-weight:600;min-width:80px;">{{ c.balance | format_number | safe }}</span> <input type="number" name="delta_{{ c.currency_id }}" placeholder="+/-" style="width:120px;"> <button type="button" class="btn-save" style="font-size:11px;padding:2px 8px;" onclick="submitCurrencyEdit({{ c.currency_id }})">Apply</button></label>';
container.appendChild(div);
}
{% endfor %}
openModal('currencies-modal');
}
async function submitCurrencyEdit(currencyId) {
const input = document.querySelector(`input[name="delta_${currencyId}"]`);
const delta = parseInt(input ? input.value : 0);
if (isNaN(delta) || delta === 0) {
alert('Enter a non-zero amount to add or subtract.');
return;
}
const data = new FormData();
data.append('player_controller_id', '{{ player.player_controller_id }}');
data.append('currency_id', currencyId);
data.append('delta', delta);
try {
const resp = await fetch('/api/edit_currency', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
alert('Currency updated: ' + result.old_balance + ' → ' + result.new_balance + ' (delta: ' + (delta > 0 ? '+' : '') + delta + ')');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
}
async function submitVitalsEdit() {
const form = document.getElementById('vitals-form');
const data = new FormData(form);
try {
const resp = await fetch('/api/edit_vitals', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
alert('Vitals updated successfully!');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
return false;
}
async function editItem(itemId, field, currentValue) {
const newValue = prompt(`Edit ${field} for item ${itemId}:`, currentValue);
if (newValue === null || newValue === currentValue) return;
const data = new FormData();
data.append('item_id', itemId);
data.append('field', field);
data.append('value', newValue);
try {
const resp = await fetch('/api/edit_item', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
const span = document.getElementById('item-' + field.replace('_', '-') + '-' + itemId);
if (span) span.textContent = result.value;
else location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
}
async function deleteItem(itemId, templateName) {
if (!confirm(`Delete item "${templateName}" (ID: ${itemId})? This cannot be undone.`)) return;
const data = new FormData();
data.append('item_id', itemId);
try {
const resp = await fetch('/api/delete_item', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
const row = document.getElementById('item-row-' + itemId);
if (row) row.remove();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
}
function openAddItemModal(invId) {
document.getElementById('add-item-inv-id').value = invId;
openModal('add-item-modal');
}
async function submitAddItem() {
const form = document.getElementById('add-item-form');
const data = new FormData(form);
try {
const resp = await fetch('/api/add_item', { method: 'POST', body: data });
const result = await resp.json();
if (result.success) {
alert('Item added! ID: ' + result.item_id);
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
} catch (e) {
alert('Error: ' + e.message);
}
return false;
}
</script>
{% endblock %}
+261
View File
@@ -0,0 +1,261 @@
{% extends "base.html" %}
{% block title %}Players - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Players</h1>
<p>{{ players|length }} player characters shown <button onclick="detectIps()" style="margin-left:15px;padding:4px 12px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Detect IPs</button></p>
</div>
{% if tunnel_down %}
<div class="error-banner danger">
<strong>SSH Tunnel Not Detected</strong><br>
Start the SSH tunnel first, then refresh.
<br><code>ssh -i $env:TEMP\dune-awakening-server-sshKey -L 15433:localhost:15433 -N dune@65.21.198.100</code>
</div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<form method="get" class="filters">
<input type="text" name="search" placeholder="Search name or ID..." value="{{ search }}">
<select name="faction">
<option value="">All Factions</option>
{% for f in factions %}
<option value="{{ f.id }}" {% if sel_faction|string == f.id|string %}selected{% endif %}>{{ f.name }}</option>
{% endfor %}
</select>
<select name="guild">
<option value="">All Guilds</option>
{% for g in guilds %}
<option value="{{ g.guild_id }}" {% if sel_guild|string == g.guild_id|string %}selected{% endif %}>{{ g.guild_name }}</option>
{% endfor %}
</select>
<select name="map">
<option value="">All Maps</option>
{% for m in maps %}
<option value="{{ m.map }}" {% if sel_map == m.map %}selected{% endif %}>{{ m.map }}</option>
{% endfor %}
</select>
<select name="online">
<option value="">Any Status</option>
<option value="online" {% if sel_online == 'online' %}selected{% endif %}>Online</option>
<option value="offline" {% if sel_online == 'offline' %}selected{% endif %}>Offline</option>
</select>
<button type="submit">Filter</button>
{% if search or sel_faction or sel_guild or sel_map or sel_online %}
<a href="/players" style="font-size:13px;color:var(--text-light);">Clear filters</a>
{% endif %}
</form>
<div class="card">
<div class="table-wrap">
<table id="players-table">
<thead>
<tr>
<th data-col="name">Name</th>
<th data-col="status">Status</th>
<th data-col="faction">Faction</th>
<th data-col="guild">Guild</th>
<th data-col="map">Map</th>
<th data-col="ip">IP Address</th>
<th data-col="account">Account</th>
<th data-col="vehicles" class="sort-desc">Vehicles</th>
<th data-col="buildings">Buildings</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for p in players %}
<tr>
<td><a href="/players/{{ p.id }}">{{ p.player_name or 'Unknown' }}</a></td>
<td>{% if p.online_status %}<span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span>{% else %}<span class="badge badge-offline">Unknown</span>{% endif %}</td>
<td>{% if p.faction_name %}<span class="badge badge-{{ p.faction_name.lower() }}">{{ p.faction_name }}</span>{% else %}&mdash;{% endif %}</td>
<td>{% if p.guild_name %}{{ p.guild_name }}{% else %}&mdash;{% endif %}</td>
<td>{{ p.map or '&mdash;'|safe }}</td>
<td style="font-size:12px;">{% if p.player_controller_id %}<span class="ip-cell" data-id="{{ p.player_controller_id }}" data-ip="{{ p.ip_address or '' }}">{{ p.ip_address or '—' }}</span>{% else %}&mdash;{% endif %}</td>
<td style="font-size:12px;">{{ p.funcom_id or p.account_email }}</td>
<td>{{ p.vehicle_count }}</td>
<td>{{ p.building_count }}</td>
<td>{% if p.player_controller_id %}<button class="btn-action" data-id="{{ p.player_controller_id }}" data-name="{{ p.player_name }}" data-action="kick" style="padding:2px 8px;font-size:11px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;">Kick</button> <button class="btn-action" data-id="{{ p.player_controller_id }}" data-name="{{ p.player_name }}" data-action="ban" style="padding:2px 8px;font-size:11px;background:#c0392b;color:#fff;border:none;border-radius:4px;cursor:pointer;">Ban</button> <button class="btn-action" data-id="{{ p.player_controller_id }}" data-name="{{ p.player_name }}" data-action="viewban" style="padding:2px 8px;font-size:11px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;">Info</button> <button class="btn-action" data-id="{{ p.player_controller_id }}" data-name="{{ p.player_name }}" data-action="history" style="padding:2px 8px;font-size:11px;background:#9b59b6;color:#fff;border:none;border-radius:4px;cursor:pointer;">History</button> <button class="btn-action" data-id="{{ p.player_controller_id }}" data-name="{{ p.player_name }}" data-action="unban" style="padding:2px 8px;font-size:11px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;">Unban</button>{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="10" class="empty">No players found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#players-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.querySelector('#players-table tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#players-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
const na = parseFloat(va), nb = parseFloat(vb);
if (!isNaN(na) && !isNaN(nb)) return isAsc ? na - nb : nb - na;
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
document.querySelectorAll('.btn-action[data-action="kick"]').forEach(btn => {
btn.addEventListener('click', async function() {
const pid = this.dataset.id;
const name = this.dataset.name;
if (!confirm(`Kick player "${name}" for 60 seconds?`)) return;
try {
const form = new FormData();
form.append('player_id', pid);
const resp = await fetch('/api/kick_player', { method: 'POST', body: form });
const data = await resp.json();
alert(data.success ? data.message : 'Error: ' + (data.error || 'Failed'));
} catch (e) {
alert('Error: ' + e.message);
}
});
});
document.querySelectorAll('.btn-action[data-action="ban"]').forEach(btn => {
btn.addEventListener('click', async function() {
const pid = this.dataset.id;
const name = this.dataset.name;
const duration = prompt('Enter ban duration in minutes (0 = permanent):', '60');
if (duration === null) return;
const reason = prompt('Enter ban reason:', 'Violation of server rules');
if (reason === null) return;
const note = prompt('Enter admin note (optional):', '');
if (note === null) return;
try {
const form = new FormData();
form.append('player_id', pid);
form.append('duration', duration);
form.append('reason', reason);
form.append('note', note);
const resp = await fetch('/api/ban_player', { method: 'POST', body: form });
const data = await resp.json();
alert(data.success ? `Banned ${name} for ${duration} minutes` : 'Error: ' + (data.error || 'Failed'));
} catch (e) {
alert('Error: ' + e.message);
}
});
});
document.querySelectorAll('.btn-action[data-action="unban"]').forEach(btn => {
btn.addEventListener('click', async function() {
const pid = this.dataset.id;
const name = this.dataset.name;
if (!confirm(`Unban player "${name}" and remove IP block?`)) return;
try {
const form = new FormData();
form.append('player_id', pid);
const resp = await fetch('/api/unban_player', { method: 'POST', body: form });
const data = await resp.json();
alert(data.success ? `Unbanned ${name}` : 'Error: ' + (data.error || 'Failed'));
} catch (e) {
alert('Error: ' + e.message);
}
});
});
document.querySelectorAll('.btn-action[data-action="viewban"]').forEach(btn => {
btn.addEventListener('click', async function() {
const pid = this.dataset.id;
const name = this.dataset.name;
try {
const form = new FormData();
form.append('player_id', pid);
const resp = await fetch('/api/get_player_ban', { method: 'POST', body: form });
const data = await resp.json();
if (data.banned) {
alert(`Ban Info for ${name}:\n\nDuration: ${data.duration} minutes\nReason: ${data.reason}\nNote: ${data.note || 'None'}\nBanned: ${data.banned_at}\nExpires: ${data.expires_at}`);
} else {
alert(`${name} is not banned`);
}
} catch (e) {
alert('Error: ' + e.message);
}
});
});
document.querySelectorAll('.btn-action[data-action="history"]').forEach(btn => {
btn.addEventListener('click', async function() {
const pid = this.dataset.id;
const name = this.dataset.name;
try {
const form = new FormData();
form.append('player_id', pid);
const resp = await fetch('/api/get_player_history', { method: 'POST', body: form });
const data = await resp.json();
if (data.history && data.history.length > 0) {
let msg = `Action History for ${name}:\n\n`;
data.history.forEach(h => {
const action = h.action.toUpperCase();
const time = h.created_at ? h.created_at.replace('T', ' ').substring(0, 19) : '';
const reason = h.reason || '';
const ip = h.ip ? ` (IP: ${h.ip})` : '';
msg += `${time} - ${action}: ${reason}${ip}\n`;
});
alert(msg);
} else {
alert(`No action history for ${name}`);
}
} catch (e) {
alert('Error: ' + e.message);
}
});
});
document.querySelectorAll('.ip-cell').forEach(cell => {
cell.style.cursor = 'pointer';
cell.style.textDecoration = 'underline';
cell.title = 'Click to edit IP';
cell.addEventListener('click', async function() {
const pid = this.dataset.id;
const currentIp = this.dataset.ip || '';
const newIp = prompt('Enter IP address for player:', currentIp);
if (newIp === null) return;
if (newIp !== currentIp) {
try {
const form = new FormData();
form.append('player_id', pid);
form.append('ip_address', newIp);
const resp = await fetch('/api/set_player_ip', { method: 'POST', body: form });
const data = await resp.json();
if (data.success) {
this.textContent = newIp || '—';
this.dataset.ip = newIp;
alert('IP updated!');
} else {
alert('Error: ' + data.error);
}
} catch (e) {
alert('Error: ' + e.message);
}
}
});
});
async function detectIps() {
try {
const btn = document.querySelector('button[onclick="detectIps()"]');
if (btn) { btn.disabled = true; btn.textContent = 'Detecting...'; }
const resp = await fetch('/api/detect_player_ips', { method: 'POST' });
const data = await resp.json();
if (data.success) {
console.log('IP detection:', data.message);
}
if (btn) { btn.disabled = false; btn.textContent = 'Detect IPs'; }
} catch (e) {
console.log('IP detection failed:', e.message);
const btn = document.querySelector('button[onclick="detectIps()"]');
if (btn) { btn.disabled = false; btn.textContent = 'Detect IPs'; }
}
}
detectIps();
</script>
{% endblock %}
+367
View File
@@ -0,0 +1,367 @@
{% extends "base.html" %}
{% block title %}Server - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Server Status &amp; Control</h1>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div class="stats-grid">
<div class="stat-card">
<div class="label">Online Players</div>
<div class="value online">{{ online_count }}</div>
</div>
<div class="stat-card">
<div class="label">Overmap Players</div>
<div class="value">{{ overmap_count }}</div>
</div>
<div class="stat-card">
<div class="label">Active Servers</div>
<div class="value">{{ active_servers|length }}</div>
</div>
<div class="stat-card">
<div class="label">World Partitions</div>
<div class="value">{{ partitions|length }}</div>
</div>
{% if node_metrics.cpu %}
<div class="stat-card">
<div class="label">Node CPU</div>
<div class="value" id="node-cpu">{{ node_metrics.cpu }}</div>
</div>
<div class="stat-card">
<div class="label">Node Memory</div>
<div class="value" id="node-mem">{{ node_metrics.memory }}</div>
</div>
{% endif %}
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
<div class="card">
<div class="card-header">Players Per Map</div>
<div class="card-body">
{% if per_map %}
{% for m in per_map %}
<div class="faction-bar">
<span class="bar-label" style="font-weight:600;">{{ m.map }}</span>
<div class="bar-bg">
<div class="bar-fill" style="background:var(--primary);width:{{ (m.count / online_count * 100)|round(1) if online_count > 0 else 0 }}%;min-width:2px;"></div>
</div>
<span class="bar-count">{{ m.count }}</span>
</div>
{% endfor %}
{% else %}
<div class="empty">No data</div>
{% endif %}
</div>
</div>
<div class="card">
<div class="card-header">Online Players</div>
<div class="card-body">
{% if online_players %}
<table style="width:100%;">
{% for p in online_players %}
<tr>
<td><a href="/players/{{ p.character_name }}" style="font-weight:500;">{{ p.character_name or 'Unknown' }}</a></td>
<td>{{ p.map or 'N/A' }}</td>
<td><span class="badge badge-{{ p.online_status.lower() }}">{{ p.online_status }}</span></td>
</tr>
{% endfor %}
</table>
{% else %}
<div class="empty">No players online</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">Active Server IDs</div>
<div class="card-body">
{% if active_servers %}
<ul style="list-style:none;">
{% for s in active_servers %}
<li style="padding:4px 0;font-family:monospace;font-size:12px;">
<span style="font-weight:600;">{{ s.server_id }}</span>
{% if s.map %} — <span style="color:var(--primary);">{{ s.map }}</span>{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<div class="empty">No active servers</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">World Partitions</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Partition ID</th><th>Server ID</th><th>Map</th><th>Dimension</th><th>Blocked</th><th>Label</th><th>Actions</th></tr>
</thead>
<tbody>
{% for p in partitions %}
<tr>
<td>{{ p.partition_id }}</td>
<td style="font-family:monospace;font-size:11px;">{{ p.server_id }}</td>
<td>{{ p.map }}</td>
<td>{{ p.dimension_index }}</td>
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
<td>{{ p.label or '' }}</td>
<td>{% if p.deployment %}<button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>{% else %}&mdash;{% endif %}</td>
</tr>
{% else %}
<tr><td colspan="7" class="empty">No partitions found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Kubernetes Deployments</span>
{% if deploys_ok %}
<span style="font-size:12px;color:var(--success);">SSH connected</span>
{% else %}
<span style="font-size:12px;color:var(--danger);">SSH unavailable (key not loaded or VM unreachable)</span>
{% endif %}
</div>
<div class="card-body">
{% if deploys_ok %}
<div class="table-wrap">
<table>
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
<tbody>
{% for d in deployments %}
<tr>
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
<td>
<button class="btn-action" data-deploy="{{ d }}" data-action="restart" style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="status" style="padding:4px 12px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Status</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_0" style="padding:4px 12px;background:#e74c3c;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 0</button>
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p style="color:var(--text-light);font-size:14px;">
To enable server control, ensure the SSH key is available at
<code>$env:TEMP\dune-awakening-server-sshKey</code> and the VM is reachable.
</p>
{% if ssh_error %}
<pre style="background:#1a1a2e;color:#e74c3c;padding:12px;border-radius:6px;font-size:12px;margin-top:8px;">{{ ssh_error }}</pre>
{% endif %}
{% endif %}
<div id="action-output" style="margin-top:16px;display:none;">
<div class="card-header">Command Output</div>
<pre id="action-output-text" style="background:#1a1a2e;color:#e0d5c7;padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;margin-top:8px;"></pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Battlegroup Control</span>
<span id="bg-status-indicator" style="font-size:12px;color:var(--text-muted);">Click "Refresh Status" to load</span>
</div>
<div class="card-body">
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;">
<button id="bg-btn-start" class="bg-btn" style="padding:8px 20px;background:#27ae60;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Start</button>
<button id="bg-btn-stop" class="bg-btn" style="padding:8px 20px;background:#e74c3c;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Stop</button>
<button id="bg-btn-restart" class="bg-btn" style="padding:8px 20px;background:#e67e22;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Restart</button>
<button id="bg-btn-update" class="bg-btn" style="padding:8px 20px;background:#9b59b6;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600;">Update</button>
<button id="bg-btn-refresh" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Status</button>
</div>
<div id="bg-status-output">
<pre id="bg-status-text" style="background:#1a1a2e;color:#e0d5c7;padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;min-height:100px;">Click "Refresh Status" to load battlegroup status...</pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Admin Management</span>
<span style="font-size:12px;color:var(--text-muted);">Coming Soon</span>
</div>
<div class="card-body">
<p style="font-size:14px;color:var(--text-light);">
Server admin assignment and player permission management interface.
Requires integration with game server authentication system.
</p>
</div>
</div>
<div class="card">
<div class="card-header">Pod Status</div>
<div class="card-body">
<button id="refresh-pods" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Pods</button>
<div id="pods-output" style="margin-top:12px;">
<pre id="pods-text" style="background:#1a1a2e;color:#e0d5c7;padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;">Click refresh to load pod status...</pre>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
// Auto-refresh node metrics every 5 seconds
setInterval(async function() {
try {
const resp = await fetch('/server/metrics');
const data = await resp.json();
if (data.cpu) {
document.getElementById('node-cpu').textContent = data.cpu;
document.getElementById('node-mem').textContent = data.memory;
}
} catch (e) {}
}, 5000);
document.querySelectorAll('.btn-action').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const action = this.dataset.action;
const label = this.textContent.trim();
if (action === 'restart' || action === 'scale_0') {
const confirmMsg = action === 'restart'
? `Restart deployment "${deploy}"?`
: `Scale deployment "${deploy}" to 0 replicas (shutdown)?`;
if (!confirm(confirmMsg)) return;
if (!confirm('Are you sure? This will affect live players.')) return;
}
this.disabled = true;
this.textContent = 'Working...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Running ${action} on ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', action);
const resp = await fetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'Done' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
document.querySelectorAll('.partition-btn').forEach(btn => {
btn.addEventListener('click', async function() {
const deploy = this.dataset.deploy;
const map = this.dataset.map;
const label = this.textContent.trim();
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
this.disabled = true;
this.textContent = 'Restarting...';
const output = document.getElementById('action-output');
const outputText = document.getElementById('action-output-text');
output.style.display = 'block';
outputText.textContent = `Restarting ${deploy}...`;
try {
const form = new FormData();
form.append('deployment', deploy);
form.append('action', 'restart');
const resp = await fetch('/server/action', { method: 'POST', body: form });
const data = await resp.json();
outputText.textContent = data.output || (data.success ? 'Restart initiated' : 'Failed');
} catch (e) {
outputText.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = label;
});
});
document.getElementById('refresh-pods')?.addEventListener('click', async function() {
this.disabled = true;
this.textContent = 'Loading...';
const pre = document.getElementById('pods-text');
pre.textContent = 'Fetching pod list...';
try {
const resp = await fetch('/server/pods');
const data = await resp.json();
pre.textContent = data.output || (data.success ? 'No pods found' : 'Failed: ' + data.output);
} catch (e) {
pre.textContent = 'Error: ' + e.message;
}
this.disabled = false;
this.textContent = 'Refresh Pods';
});
async function bgAction(action, btn) {
const confirmMsgs = {
'stop': 'Stop the battlegroup? This will disconnect all players.',
'restart': 'Restart the battlegroup? This will disconnect all players.',
'update': 'Update the battlegroup? This will download new images and restart. This may take several minutes.'
};
if (confirmMsgs[action] && !confirm(confirmMsgs[action])) return;
if ((action === 'stop' || action === 'restart') && !confirm('Are you sure? This will affect live players.')) return;
btn.disabled = true;
const originalText = btn.textContent;
btn.textContent = action === 'update' ? 'Updating (may take several minutes)...' : 'Working...';
const pre = document.getElementById('bg-status-text');
pre.textContent = `Running ${action}...`;
try {
const url = action === 'update' ? '/server/battlegroup/update' : '/server/battlegroup/action';
const form = new FormData();
form.append('action', action);
const resp = await fetch(url, { method: 'POST', body: form });
const data = await resp.json();
pre.textContent = data.output || (data.success ? `${action} completed successfully` : `Failed: ${data.output}`);
} catch (e) {
pre.textContent = 'Error: ' + e.message;
}
btn.disabled = false;
btn.textContent = originalText;
}
async function bgRefreshStatus() {
const btn = document.getElementById('bg-btn-refresh');
const pre = document.getElementById('bg-status-text');
const indicator = document.getElementById('bg-status-indicator');
btn.disabled = true;
btn.textContent = 'Loading...';
pre.textContent = 'Fetching battlegroup status...';
try {
const resp = await fetch('/server/battlegroup/status');
const data = await resp.json();
pre.textContent = data.output || (data.success ? 'No status available' : 'Failed: ' + data.output);
indicator.textContent = data.success ? 'Status loaded' : 'Failed to load';
indicator.style.color = data.success ? 'var(--success)' : 'var(--danger)';
} catch (e) {
pre.textContent = 'Error: ' + e.message;
indicator.textContent = 'Error';
indicator.style.color = 'var(--danger)';
}
btn.disabled = false;
btn.textContent = 'Refresh Status';
}
document.getElementById('bg-btn-start')?.addEventListener('click', function() { bgAction('start', this); });
document.getElementById('bg-btn-stop')?.addEventListener('click', function() { bgAction('stop', this); });
document.getElementById('bg-btn-restart')?.addEventListener('click', function() { bgAction('restart', this); });
document.getElementById('bg-btn-update')?.addEventListener('click', function() { bgAction('update', this); });
document.getElementById('bg-btn-refresh')?.addEventListener('click', bgRefreshStatus);
</script>
{% endblock %}
+186
View File
@@ -0,0 +1,186 @@
{% extends "base.html" %}
{% block title %}Shell - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Shell Access</h1>
<p>Live terminal sessions - VM and Pod shells</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% else %}
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
<div class="card">
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
<span>VM Shell</span>
<button id="btn-shell-vm" onclick="toggleShell('vm')" style="padding:4px 12px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;">Connect</button>
</div>
<div id="terminal-vm" style="height:300px;background:#1a1a1a;padding:10px;font-family:monospace;font-size:12px;overflow:auto;"></div>
</div>
<div class="card">
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
<span>Pod Shell</span>
<select id="pod-select" style="padding:4px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;">
{% for pod in pods %}
<option value="{{ pod.name }}">{{ pod.name }}</option>
{% endfor %}
</select>
<button id="btn-shell-pod" onclick="toggleShell('pod')" style="padding:4px 12px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;">Connect</button>
</div>
<div id="terminal-pod" style="height:300px;background:#1a1a1a;padding:10px;font-family:monospace;font-size:12px;overflow:auto;"></div>
</div>
</div>
<div class="card">
<div class="card-header">Pods ({{ pods|length }})</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Name</th><th>Role</th><th>Status</th></tr>
</thead>
<tbody>
{% for pod in pods %}
<tr>
<td style="font-family:monospace;font-size:12px;">{{ pod.name }}</td>
<td><span class="badge badge-{{ pod.role.lower() if pod.role else 'default' }}">{{ pod.role or 'default' }}</span></td>
<td><span class="badge badge-{{ pod.status.lower() }}">{{ pod.status }}</span></td>
</tr>
{% else %}
<tr><td colspan="3" class="empty">No pods found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
<script>
const socket = io();
let termVM = null;
let termPod = null;
let connectedVM = false;
let connectedPod = false;
let shellIdVM = null;
let shellIdPod = null;
function createTerminal(elementId) {
const term = new Terminal({
cursorBlink: true,
fontSize: 14,
fontFamily: 'Consolas, "Courier New", monospace',
theme: {
background: '#1a1a1a',
foreground: '#cccccc'
},
rows: 20,
cols: 80
});
term.open(document.getElementById(elementId));
return term;
}
function toggleShell(type) {
if ((type === 'vm' && connectedVM) || (type === 'pod' && connectedPod)) {
disconnectShell(type);
} else {
startShell(type);
}
}
function startShell(type) {
const btnId = type === 'vm' ? 'btn-shell-vm' : 'btn-shell-pod';
const termId = type === 'vm' ? 'terminal-vm' : 'terminal-pod';
document.getElementById(btnId).disabled = true;
document.getElementById(btnId).textContent = 'Connecting...';
const data = { type: type };
if (type === 'pod') {
data.pod = document.getElementById('pod-select').value;
}
socket.emit('shell_create', data);
socket.once('shell_created', function(response) {
if (response.success) {
const shellId = response.shell_id;
if (type === 'vm') {
shellIdVM = shellId;
termVM = createTerminal(termId);
setupTerminalInput(termVM, 'vm');
connectedVM = true;
} else {
shellIdPod = shellId;
termPod = createTerminal(termId);
setupTerminalInput(termPod, 'pod');
connectedPod = true;
}
document.getElementById(btnId).textContent = 'Disconnect';
document.getElementById(btnId).style.background = '#dc3545';
document.getElementById(btnId).disabled = false;
} else {
document.getElementById(btnId).textContent = 'Failed';
document.getElementById(btnId).disabled = false;
alert('Connection failed: ' + response.error);
}
});
}
function disconnectShell(type) {
const btnId = type === 'vm' ? 'btn-shell-vm' : 'btn-shell-pod';
const termId = type === 'vm' ? 'terminal-vm' : 'terminal-pod';
const shellId = type === 'vm' ? shellIdVM : shellIdPod;
socket.emit('shell_disconnect', { shell_id: shellId, type: type });
if (type === 'vm') {
if (termVM) { termVM.dispose(); termVM = null; }
connectedVM = false;
shellIdVM = null;
} else {
if (termPod) { termPod.dispose(); termPod = null; }
connectedPod = false;
shellIdPod = null;
}
document.getElementById(btnId).textContent = 'Connect';
document.getElementById(btnId).style.background = 'var(--primary)';
document.getElementById(termId).innerHTML = '';
}
socket.on('shell_output', function(data) {
if (data.type === 'stdout') {
if (data.target === 'vm' && termVM) {
termVM.write(data.data);
}
if (data.target === 'pod' && termPod) {
termPod.write(data.data);
}
}
});
socket.on('connect', function() {
console.log('Socket connected');
});
function setupTerminalInput(term, type) {
term.onData(function(data) {
socket.emit('shell_input', {data: data, type: type});
});
}
</script>
<style>
.xterm { height: 100%; }
.xterm-viewport { overflow-y: auto !important; }
</style>
{% endblock %}
+78
View File
@@ -0,0 +1,78 @@
{% extends "base.html" %}
{% block title %}Vehicle {{ vehicle.id }} - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Vehicle #{{ vehicle.id }}</h1>
<p><a href="/vehicles">&larr; Back to Vehicles</a></p>
</div>
<div class="card" style="margin-bottom:16px;">
<div class="card-body" style="padding:12px 16px;background:var(--bg-hover);border-left:3px solid var(--accent);">
<strong>Note:</strong> 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.
</div>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif not_found %}
<div class="error-banner"><strong>Vehicle not found</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:16px;margin-bottom:24px;">
<div class="stat-card">
<div class="label">Type</div>
<div class="value" style="font-size:14px;">{{ vehicle.class | class_name }}</div>
</div>
<div class="stat-card">
<div class="label">Owner</div>
<div class="value">{% if vehicle.owner_name %}<a href="/players/{{ vehicle.owner_pawn_id }}">{{ vehicle.owner_name }}</a>{% else %}Unknown{% endif %}</div>
</div>
<div class="stat-card">
<div class="label">Map</div>
<div class="value">{{ vehicle.map or 'N/A' }}</div>
</div>
<div class="stat-card">
<div class="label">Modules</div>
<div class="value">{{ modules|length }}</div>
</div>
<div class="stat-card">
<div class="label">Fuel</div>
<div class="value" style="font-size:12px;color:var(--text-muted);">TBD</div>
</div>
</div>
<h2>Modules / Parts</h2>
<div class="card">
<table>
<thead>
<tr>
<th>ID</th>
<th>Module</th>
<th>Current</th>
<th>DB Max</th>
<th>%</th>
<th>Damage Cause</th>
</tr>
</thead>
<tbody>
{% for m in modules %}
<tr>
<td>{{ m.id }}</td>
<td>{{ m.name }}</td>
<td>{{ m.current }}</td>
<td>{{ m.max }}</td>
<td>{% set pct = (m.current / m.max * 100) if m.max > 0 else 0 %}{% if pct > 66 %}<span style="color:green">{{ "%.0f"|format(pct) }}%</span>{% elif pct > 33 %}<span style="color:orange">{{ "%.0f"|format(pct) }}%</span>{% else %}<span style="color:red">{{ "%.0f"|format(pct) }}%</span>{% endif %}</td>
<td style="font-size:11px;">{{ m.damage_cause or '-' }}</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty">No modules found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
+142
View File
@@ -0,0 +1,142 @@
{% extends "base.html" %}
{% block title %}Vehicles - Dune Awakening Dashboard{% endblock %}
{% block content %}
<div class="page-header">
<h1>Vehicles</h1>
<p>{{ vehicles|length }} vehicles shown</p>
</div>
{% if tunnel_down %}
<div class="error-banner danger"><strong>SSH Tunnel Not Detected</strong></div>
{% elif db_error %}
<div class="error-banner danger"><strong>Database Error:</strong> {{ db_error }}</div>
{% else %}
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:16px;">
<div class="stat-card">
<div class="label">Total Vehicles</div>
<div class="value">{{ vehicles|length }}</div>
</div>
<div class="stat-card">
<div class="label">Currently Piloted</div>
<div class="value">{{ vehicles|selectattr('pilot_name')|list|length }}</div>
</div>
<div class="stat-card">
<div class="label">Owned by Players</div>
<div class="value">{{ vehicles|selectattr('owner_name')|list|length }}</div>
</div>
</div>
<div style="margin-bottom:16px;">
<button id="group-toggle" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer;">Group by Type</button>
</div>
<div class="card">
<div class="table-wrap">
<table id="vehicles-table">
<thead>
<tr>
<th data-col="id">ID</th>
<th data-col="type">Type</th>
<th data-col="name">Name</th>
<th data-col="owner">Owner</th>
<th data-col="pilot">Piloted By</th>
<th data-col="map">Map</th>
<th data-col="pos">Position</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="vehicles-tbody">
{% for v in vehicles %}
<tr data-type="{{ v.class | class_name }}" data-owner="{{ v.owner_name or '' }}">
<td><a href="/vehicles/{{ v.id }}">{{ v.id }}</a></td>
<td style="font-size:12px;">{{ v.class | class_name }}</td>
<td>{{ v.actor_name or 'N/A' }}</td>
<td>{% if v.owner_name %}<a href="/players/{{ v.owner_pawn_id }}" style="font-weight:500;">{{ v.owner_name }}</a>{% else %}&mdash;{% endif %}</td>
<td>{% if v.pilot_name %}<span class="badge badge-online">Active</span> <a href="/players/{{ v.pilot_pawn_id }}">{{ v.pilot_name }}</a>{% else %}&mdash;{% endif %}</td>
<td>{{ v.map or 'N/A' }}</td>
<td style="font-size:11px;font-family:monospace;max-width:250px;word-break:break-all;">{{ v.transform_text or '' }}</td>
<td><button class="btn-delete" data-id="{{ v.id }}" data-type="vehicle" title="Delete">🗑️</button></td>
</tr>
{% else %}
<tr><td colspan="8" class="empty">No vehicles found</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
document.querySelectorAll('#vehicles-table thead th').forEach(th => {
th.addEventListener('click', () => {
const tbody = document.getElementById('vehicles-tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const col = Array.from(th.parentNode.children).indexOf(th);
const isAsc = th.classList.contains('sort-asc');
document.querySelectorAll('#vehicles-table thead th').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
th.classList.add(isAsc ? 'sort-desc' : 'sort-asc');
rows.sort((a, b) => {
const va = a.children[col]?.textContent.trim() || '';
const vb = b.children[col]?.textContent.trim() || '';
const na = parseFloat(va), nb = parseFloat(vb);
if (!isNaN(na) && !isNaN(nb)) return isAsc ? na - nb : nb - na;
return isAsc ? vb.localeCompare(va) : va.localeCompare(vb);
});
rows.forEach(r => tbody.appendChild(r));
});
});
let grouped = false;
document.getElementById('group-toggle')?.addEventListener('click', function() {
const tbody = document.getElementById('vehicles-tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
if (!grouped) {
const groups = {};
rows.forEach(r => {
const type = r.dataset.type || 'Other';
if (!groups[type]) groups[type] = [];
groups[type].push(r);
});
tbody.innerHTML = '';
Object.keys(groups).sort().forEach(type => {
const h = document.createElement('tr');
h.innerHTML = `<td colspan="8" style="background:#f8f6f2;font-weight:600;padding:8px 14px;font-size:13px;">${type} (${groups[type].length})</td>`;
tbody.appendChild(h);
groups[type].forEach(r => tbody.appendChild(r));
});
this.textContent = 'Ungroup';
grouped = true;
} else {
const all = [];
rows.forEach(r => { if (!r.classList.contains('group-header')) all.push(r); });
tbody.innerHTML = '';
all.forEach(r => tbody.appendChild(r));
this.textContent = 'Group by Type';
grouped = false;
}
});
document.querySelectorAll('.btn-delete').forEach(btn => {
btn.addEventListener('click', async function() {
const id = this.dataset.id;
const type = this.dataset.type;
if (!confirm(`Are you sure you want to delete this ${type}?`)) return;
try {
const resp = await fetch(`/api/${type === 'vehicle' ? 'vehicles' : 'buildings'}/${id}`, { method: 'DELETE' });
const data = await resp.json();
if (data.success) {
this.closest('tr').remove();
} else {
alert('Error: ' + (data.error || 'Failed to delete'));
}
} catch (e) {
alert('Error: ' + e.message);
}
});
});
</script>
{% endblock %}