Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
593345fb1f | ||
|
|
79818f6d5d | ||
|
|
f4ee1b85cf | ||
|
|
4a94bf68ce | ||
|
|
0f173dc107 |
No files matched your search
@@ -38,6 +38,9 @@ internal-scripts/ssh/sshKey
|
|||||||
# SSL Certificates
|
# SSL Certificates
|
||||||
ssl/
|
ssl/
|
||||||
|
|
||||||
|
# Let's Encrypt certbot runtime data
|
||||||
|
certbot/
|
||||||
|
|
||||||
# Temporary settings scripts (generated by launcher)
|
# Temporary settings scripts (generated by launcher)
|
||||||
read_settings*.py
|
read_settings*.py
|
||||||
hash_pw*.py
|
hash_pw*.py
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ This project is **Source Available** under the [Dune Dashboard Source License (D
|
|||||||
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
|
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
|
||||||
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
|
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
|
||||||
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
|
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
|
||||||
|
- **[9] Repair Game Database** — Fix dashboard schema ownership so game updates won't break servers
|
||||||
|
- **[10] Clean up Old Dashboard Schema** — Drop the old `dashboard` schema from the game database (after migration)
|
||||||
- **[Q] Quit** — Exit the launcher
|
- **[Q] Quit** — Exit the launcher
|
||||||
|
|
||||||
3. **First-time Setup** (option 2)
|
3. **First-time Setup** (option 2)
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ DEFAULTS = {
|
|||||||
'max_connections': 10,
|
'max_connections': 10,
|
||||||
'owner': 'dune',
|
'owner': 'dune',
|
||||||
'dashboard_schema': 'dashboard',
|
'dashboard_schema': 'dashboard',
|
||||||
|
'dashboard_database_name': 'dashboard',
|
||||||
},
|
},
|
||||||
'kubernetes': {
|
'kubernetes': {
|
||||||
'namespace': '',
|
'namespace': '',
|
||||||
|
|||||||
+37
-23
@@ -15,7 +15,7 @@ from flask_limiter.util import get_remote_address
|
|||||||
|
|
||||||
from app.config import load_settings
|
from app.config import load_settings
|
||||||
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
|
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
|
||||||
from app.services.database import DatabaseService
|
from app.services.database import DatabaseService, DashboardDatabaseService
|
||||||
from app.services.ssh import SSHService
|
from app.services.ssh import SSHService
|
||||||
from app.services.k8s import K8sService
|
from app.services.k8s import K8sService
|
||||||
from app.services.player import PlayerService
|
from app.services.player import PlayerService
|
||||||
@@ -24,6 +24,7 @@ from app.services.chat import ChatService
|
|||||||
from app.services.admin import AdminService
|
from app.services.admin import AdminService
|
||||||
from app.services.updater import UpdateService
|
from app.services.updater import UpdateService
|
||||||
from app.services.director import DirectorService
|
from app.services.director import DirectorService
|
||||||
|
from app.services.rmq import RmqService
|
||||||
from app.utils.cache import MultiCache
|
from app.utils.cache import MultiCache
|
||||||
from app.routes.main import register_routes
|
from app.routes.main import register_routes
|
||||||
from app.routes.api import register_api_routes
|
from app.routes.api import register_api_routes
|
||||||
@@ -43,8 +44,10 @@ def create_app(settings_path=None):
|
|||||||
static_url_path='/static'
|
static_url_path='/static'
|
||||||
)
|
)
|
||||||
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
|
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
|
||||||
|
app.config['TEMPLATES_AUTO_RELOAD'] = True # Pick up template changes without restart
|
||||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||||
|
app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours
|
||||||
app.config['WTF_CSRF_ENABLED'] = True
|
app.config['WTF_CSRF_ENABLED'] = True
|
||||||
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
||||||
|
|
||||||
@@ -58,7 +61,6 @@ def create_app(settings_path=None):
|
|||||||
and settings['dashboard']['ssl_key'] != 'null'
|
and settings['dashboard']['ssl_key'] != 'null'
|
||||||
)
|
)
|
||||||
|
|
||||||
# Set SESSION_COOKIE_SECURE conditional on SSL being enabled
|
|
||||||
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
|
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
|
||||||
|
|
||||||
# Add security headers manually (replaces deprecated Flask-Talisman)
|
# Add security headers manually (replaces deprecated Flask-Talisman)
|
||||||
@@ -188,19 +190,32 @@ def create_app(settings_path=None):
|
|||||||
'database': settings['database']['name'],
|
'database': settings['database']['name'],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dash_db_config = {
|
||||||
|
'host': db_host,
|
||||||
|
'port': settings['database']['port'],
|
||||||
|
'user': settings['database']['user'],
|
||||||
|
'password': settings['database']['password'],
|
||||||
|
'database': settings['database'].get('dashboard_database_name', 'dashboard'),
|
||||||
|
}
|
||||||
|
|
||||||
db_service = DatabaseService(
|
db_service = DatabaseService(
|
||||||
db_config,
|
db_config,
|
||||||
min_conn=settings['database']['min_connections'],
|
min_conn=settings['database']['min_connections'],
|
||||||
max_conn=settings['database']['max_connections'],
|
max_conn=settings['database']['max_connections'],
|
||||||
dashboard_schema=settings['database'].get('dashboard_schema', 'dashboard')
|
|
||||||
)
|
)
|
||||||
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
|
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
|
||||||
db_service.ensure_tables()
|
|
||||||
logging.debug("Database tables ensured")
|
dash_db_service = DashboardDatabaseService(
|
||||||
|
dash_db_config,
|
||||||
|
min_conn=settings['database']['min_connections'],
|
||||||
|
max_conn=settings['database']['max_connections'],
|
||||||
|
owner=settings['database'].get('owner', 'dune'),
|
||||||
|
)
|
||||||
|
dash_db_service.ensure_tables(game_db=db_service)
|
||||||
|
|
||||||
# Create performance indexes if they don't exist
|
# Create performance indexes if they don't exist
|
||||||
try:
|
try:
|
||||||
admin_svc_for_indexes = AdminService(db_service, None)
|
admin_svc_for_indexes = AdminService(db_service, None, dash_db=dash_db_service)
|
||||||
success, created, error = admin_svc_for_indexes.create_indexes()
|
success, created, error = admin_svc_for_indexes.create_indexes()
|
||||||
if success and created:
|
if success and created:
|
||||||
logging.info(f"Created {len(created)} database indexes")
|
logging.info(f"Created {len(created)} database indexes")
|
||||||
@@ -223,11 +238,11 @@ def create_app(settings_path=None):
|
|||||||
|
|
||||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||||
|
|
||||||
player_svc = PlayerService(db_service)
|
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
||||||
vehicle_svc = VehicleService(db_service)
|
vehicle_svc = VehicleService(db_service)
|
||||||
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
|
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service, static_cache)
|
||||||
logging.debug("ChatService initialized")
|
logging.debug("ChatService initialized")
|
||||||
admin_svc = AdminService(db_service, ssh_service)
|
admin_svc = AdminService(db_service, ssh_service, dash_db=dash_db_service)
|
||||||
logging.debug("AdminService initialized")
|
logging.debug("AdminService initialized")
|
||||||
updater_svc = UpdateService(base_dir)
|
updater_svc = UpdateService(base_dir)
|
||||||
logging.debug("UpdateService initialized")
|
logging.debug("UpdateService initialized")
|
||||||
@@ -239,9 +254,17 @@ def create_app(settings_path=None):
|
|||||||
namespace=settings['kubernetes']['namespace'],
|
namespace=settings['kubernetes']['namespace'],
|
||||||
)
|
)
|
||||||
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
|
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
|
||||||
|
rmq_svc = RmqService(
|
||||||
|
admin_port=settings.get('rabbitmq', {}).get('admin_port', 30325),
|
||||||
|
game_port=settings.get('rabbitmq', {}).get('game_port', 32716),
|
||||||
|
username=settings.get('rabbitmq', {}).get('username', 'dashboard_admin'),
|
||||||
|
password=settings.get('rabbitmq', {}).get('password', ''),
|
||||||
|
)
|
||||||
|
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
|
||||||
|
|
||||||
services = {
|
services = {
|
||||||
'db': db_service,
|
'db': db_service,
|
||||||
|
'dash_db': dash_db_service,
|
||||||
'ssh': ssh_service,
|
'ssh': ssh_service,
|
||||||
'k8s': k8s_service,
|
'k8s': k8s_service,
|
||||||
'player': player_svc,
|
'player': player_svc,
|
||||||
@@ -251,6 +274,7 @@ def create_app(settings_path=None):
|
|||||||
'static_cache': static_cache,
|
'static_cache': static_cache,
|
||||||
'updater': updater_svc,
|
'updater': updater_svc,
|
||||||
'director': director_svc,
|
'director': director_svc,
|
||||||
|
'rmq': rmq_svc,
|
||||||
}
|
}
|
||||||
logging.debug(f"All services registered: {list(services.keys())}")
|
logging.debug(f"All services registered: {list(services.keys())}")
|
||||||
|
|
||||||
@@ -266,11 +290,11 @@ def create_app(settings_path=None):
|
|||||||
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
|
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
|
||||||
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading')
|
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading')
|
||||||
|
|
||||||
# Initialize rate limiter (disabled)
|
# Initialize rate limiter (enabled, per-route limits only)
|
||||||
limiter = Limiter(
|
limiter = Limiter(
|
||||||
app=app,
|
app=app,
|
||||||
key_func=get_remote_address,
|
key_func=get_remote_address,
|
||||||
default_limits=[],
|
default_limits=[], # rate limits applied per-route only (login has 10/min)
|
||||||
storage_uri="memory://",
|
storage_uri="memory://",
|
||||||
)
|
)
|
||||||
app.limiter = limiter
|
app.limiter = limiter
|
||||||
@@ -278,22 +302,12 @@ def create_app(settings_path=None):
|
|||||||
if settings['auth']['enabled']:
|
if settings['auth']['enabled']:
|
||||||
init_auth(app, settings, limiter, audit_svc)
|
init_auth(app, settings, limiter, audit_svc)
|
||||||
|
|
||||||
# Auto-login for SPA frontend — bypasses login page
|
|
||||||
from flask_login import login_user
|
|
||||||
from app.routes.auth import AdminUser
|
|
||||||
|
|
||||||
@app.before_request
|
|
||||||
def auto_login_dev():
|
|
||||||
if not current_user.is_authenticated:
|
|
||||||
cfg_user = str(settings.get("auth", {}).get("username", "dune"))
|
|
||||||
login_user(AdminUser(cfg_user))
|
|
||||||
|
|
||||||
register_routes(app, services, settings)
|
register_routes(app, services, settings)
|
||||||
register_api_routes(app, services, settings)
|
register_api_routes(app, services, settings)
|
||||||
register_websocket_handlers(socketio, settings)
|
register_websocket_handlers(socketio, settings)
|
||||||
|
|
||||||
# Start update checker
|
# Start update checker (disabled — being reworked)
|
||||||
updater_svc.start_checker()
|
# updater_svc.start_checker()
|
||||||
|
|
||||||
@app.teardown_appcontext
|
@app.teardown_appcontext
|
||||||
def cleanup_db(exc):
|
def cleanup_db(exc):
|
||||||
|
|||||||
+273
-39
@@ -57,7 +57,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Server actions
|
# Server actions
|
||||||
@app.route('/server/action', methods=['POST'])
|
@app.route('/server/action', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def server_action():
|
def server_action():
|
||||||
deployment = request.form.get('deployment', '')
|
deployment = request.form.get('deployment', '')
|
||||||
action = request.form.get('action', '')
|
action = request.form.get('action', '')
|
||||||
@@ -114,7 +114,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/battlegroup/action', methods=['POST'])
|
@app.route('/server/battlegroup/action', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def battlegroup_action():
|
def battlegroup_action():
|
||||||
action = request.form.get('action', '')
|
action = request.form.get('action', '')
|
||||||
if action not in ('start', 'stop', 'restart'):
|
if action not in ('start', 'stop', 'restart'):
|
||||||
@@ -125,7 +125,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/battlegroup/update', methods=['POST'])
|
@app.route('/server/battlegroup/update', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def battlegroup_update():
|
def battlegroup_update():
|
||||||
bg_script = settings['kubernetes']['battlegroup_script']
|
bg_script = settings['kubernetes']['battlegroup_script']
|
||||||
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
|
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
|
||||||
@@ -195,7 +195,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/firewall/block', methods=['POST'])
|
@app.route('/server/firewall/block', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def firewall_block():
|
def firewall_block():
|
||||||
port = request.form.get('port', type=int)
|
port = request.form.get('port', type=int)
|
||||||
bgd_port = _get_bgd_nodeport()
|
bgd_port = _get_bgd_nodeport()
|
||||||
@@ -239,7 +239,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/firewall/unblock', methods=['POST'])
|
@app.route('/server/firewall/unblock', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def firewall_unblock():
|
def firewall_unblock():
|
||||||
port = request.form.get('port', type=int)
|
port = request.form.get('port', type=int)
|
||||||
bgd_port = _get_bgd_nodeport()
|
bgd_port = _get_bgd_nodeport()
|
||||||
@@ -345,7 +345,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Ban management
|
# Ban management
|
||||||
@app.route('/api/ban_player', methods=['POST'])
|
@app.route('/api/ban_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def api_ban_player():
|
def api_ban_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -408,7 +408,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/unban_player', methods=['POST'])
|
@app.route('/api/unban_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def api_unban_player():
|
def api_unban_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -434,7 +434,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/kick_player', methods=['POST'])
|
@app.route('/api/kick_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def api_kick_player():
|
def api_kick_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -449,7 +449,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Vitals editing
|
# Vitals editing
|
||||||
@app.route('/api/edit_vitals', methods=['POST'])
|
@app.route('/api/edit_vitals', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def api_edit_vitals():
|
def api_edit_vitals():
|
||||||
try:
|
try:
|
||||||
pawn_id = request.form.get('pawn_id', type=int)
|
pawn_id = request.form.get('pawn_id', type=int)
|
||||||
@@ -800,35 +800,66 @@ def register_api_routes(app, services, settings):
|
|||||||
FILEBROWSER_BASE_PATH = '/srv'
|
FILEBROWSER_BASE_PATH = '/srv'
|
||||||
|
|
||||||
def _validate_fb_path(path):
|
def _validate_fb_path(path):
|
||||||
"""Validate filebrowser path is within allowed directory."""
|
"""Validate filebrowser path — allow any path, block traversal."""
|
||||||
import posixpath
|
|
||||||
path_str = str(path or "").lstrip("/")
|
path_str = str(path or "").lstrip("/")
|
||||||
if '..' in path_str or '\x00' in path_str:
|
if '..' in path_str or '\x00' in path_str:
|
||||||
return False
|
return False
|
||||||
normalized = posixpath.normpath("/" + path_str)
|
return True
|
||||||
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
|
|
||||||
|
|
||||||
def _get_fb_pod():
|
def _get_fb_pod():
|
||||||
"""Get the FileBrowser pod name dynamically."""
|
"""Get the default FileBrowser pod name dynamically."""
|
||||||
pod = k8s.find_pod_by_pattern('fb-deploy')
|
pod = k8s.find_pod_by_pattern('fb-deploy')
|
||||||
return pod
|
return pod
|
||||||
|
|
||||||
def _fb_exec(command, timeout=10):
|
def _list_pods():
|
||||||
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement."""
|
"""List all running pods available for file browsing, plus VM host."""
|
||||||
pod = _get_fb_pod()
|
available = ['__VM__ (Host OS)']
|
||||||
|
pods = k8s.get_pods()
|
||||||
|
for p in pods:
|
||||||
|
if p.endswith('-sts-0') or '-deploy-' in p:
|
||||||
|
available.append(p)
|
||||||
|
return available
|
||||||
|
|
||||||
|
def _fb_exec(command, pod_name=None, timeout=10):
|
||||||
|
"""Execute a command on the VM host or in a K8s pod."""
|
||||||
|
if pod_name == '__VM__' or (pod_name and pod_name.startswith('__VM__')):
|
||||||
|
return k8s.ssh.run(command, timeout=timeout)
|
||||||
|
pod = pod_name or _get_fb_pod()
|
||||||
if not pod:
|
if not pod:
|
||||||
return '', 'FileBrowser pod not found', 1
|
return '', 'No pod specified or found', 1
|
||||||
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
|
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
return k8s.ssh.run(full_cmd, timeout=timeout)
|
||||||
|
|
||||||
|
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
||||||
|
"""Write a file to the pod filesystem."""
|
||||||
|
import base64
|
||||||
|
cmd = f"echo '{content_b64}' | base64 -d > '{path}'"
|
||||||
|
return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout)
|
||||||
|
|
||||||
|
def _get_pod_from_request():
|
||||||
|
pod = request.form.get('pod', '') or request.args.get('pod', '') or request.get_json(silent=True)
|
||||||
|
if isinstance(pod, dict):
|
||||||
|
pod = pod.get('pod', '')
|
||||||
|
return pod or None
|
||||||
|
|
||||||
|
@app.route('/api/files/pods')
|
||||||
|
@auth_req
|
||||||
|
def api_files_pods():
|
||||||
|
try:
|
||||||
|
pods = _list_pods()
|
||||||
|
return jsonify({'success': True, 'pods': pods})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
@app.route('/api/files/list', methods=['POST'])
|
@app.route('/api/files/list', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
def api_files_list():
|
def api_files_list():
|
||||||
path = request.form.get('path', '/srv')
|
path = request.form.get('path', '/srv')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
safe_path = quote_remote(path)
|
safe_path = quote_remote(path)
|
||||||
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
|
out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, timeout=10)
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
|
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
|
||||||
|
|
||||||
@@ -855,35 +886,90 @@ def register_api_routes(app, services, settings):
|
|||||||
@auth_req
|
@auth_req
|
||||||
def api_files_view():
|
def api_files_view():
|
||||||
path = request.args.get('path', '')
|
path = request.args.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not path:
|
if not path:
|
||||||
return jsonify({'success': False, 'error': 'Missing path'})
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
safe_path = quote_remote(path)
|
safe_path = quote_remote(path)
|
||||||
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
|
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, timeout=10)
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
||||||
return jsonify({'success': True, 'content': out, 'path': path})
|
return jsonify({'success': True, 'content': out, 'path': path})
|
||||||
|
|
||||||
@app.route('/api/files/save', methods=['POST'])
|
@app.route('/api/files/save', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def api_files_save():
|
def api_files_save():
|
||||||
path = request.form.get('path', '')
|
path = request.form.get('path', '')
|
||||||
content = request.form.get('content', '')
|
content = request.form.get('content', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not path:
|
if not path:
|
||||||
return jsonify({'success': False, 'error': 'Missing path'})
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
import base64
|
import base64
|
||||||
content_b64 = base64.b64encode(content.encode()).decode()
|
content_b64 = base64.b64encode(content.encode()).decode()
|
||||||
safe_path = quote_remote(path)
|
out, err, rc = _fb_write_file(content_b64, path, pod_name)
|
||||||
save_script = quote_remote(f"base64 -d > {safe_path}")
|
|
||||||
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
|
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to save file'})
|
return jsonify({'success': False, 'error': err or 'Failed to save file'})
|
||||||
return jsonify({'success': True})
|
return jsonify({'success': True})
|
||||||
|
|
||||||
|
@app.route('/api/files/download', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def api_files_download():
|
||||||
|
path = request.form.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not path:
|
||||||
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
|
if not _validate_fb_path(path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
import base64
|
||||||
|
safe_path = quote_remote(path)
|
||||||
|
out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
||||||
|
filename = path.rsplit('/', 1)[-1] if '/' in path else path
|
||||||
|
return jsonify({'success': True, 'content': out.strip(), 'filename': filename})
|
||||||
|
|
||||||
|
@app.route('/api/files/upload', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
|
||||||
|
def api_files_upload():
|
||||||
|
target_path = request.form.get('path', '/srv')
|
||||||
|
uploaded = request.files.get('file')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not uploaded:
|
||||||
|
return jsonify({'success': False, 'error': 'No file provided'})
|
||||||
|
if not _validate_fb_path(target_path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
import base64
|
||||||
|
filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file'
|
||||||
|
dest = target_path.rstrip('/') + '/' + filename
|
||||||
|
if not _validate_fb_path(dest):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid destination path'})
|
||||||
|
content = uploaded.read()
|
||||||
|
content_b64 = base64.b64encode(content).decode()
|
||||||
|
out, err, rc = _fb_write_file(content_b64, dest, pod_name)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to upload file'})
|
||||||
|
return jsonify({'success': True, 'filename': filename})
|
||||||
|
|
||||||
|
@app.route('/api/files/delete', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def api_files_delete():
|
||||||
|
path = request.form.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not path:
|
||||||
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
|
if not _validate_fb_path(path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
safe_path = quote_remote(path)
|
||||||
|
out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to delete'})
|
||||||
|
return jsonify({'success': True})
|
||||||
|
|
||||||
director_svc = services.get('director')
|
director_svc = services.get('director')
|
||||||
director_port = settings.get('director', {}).get('port', 32479)
|
director_port = settings.get('director', {}).get('port', 32479)
|
||||||
|
|
||||||
@@ -922,7 +1008,8 @@ def register_api_routes(app, services, settings):
|
|||||||
if map_name:
|
if map_name:
|
||||||
kv = director_svc.extract_server_config_kv(config)
|
kv = director_svc.extract_server_config_kv(config)
|
||||||
if kv:
|
if kv:
|
||||||
director_svc.update_ini_section(map_name, kv)
|
if not director_svc.update_ini_section(map_name, kv):
|
||||||
|
logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name)
|
||||||
|
|
||||||
return result, 200, {'Content-Type': 'application/json'}
|
return result, 200, {'Content-Type': 'application/json'}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -992,6 +1079,41 @@ def register_api_routes(app, services, settings):
|
|||||||
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
|
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
|
||||||
return jsonify({'success': False, 'error': str(e)}), 500
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/director/server_set_scale/<map_name>')
|
||||||
|
@auth_req
|
||||||
|
def director_server_set_scale_get(map_name):
|
||||||
|
try:
|
||||||
|
if not director_svc:
|
||||||
|
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||||
|
scale = director_svc.get_server_set_scale(map_name)
|
||||||
|
if scale is None:
|
||||||
|
return jsonify({'replicas': 0, 'partitions': []})
|
||||||
|
spec = scale.get('spec', {})
|
||||||
|
return jsonify({
|
||||||
|
'replicas': spec.get('replicas', 0),
|
||||||
|
'partitions': [p for p in spec.get('partitions', []) if p is not None],
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/director/server_set_scale/<map_name>', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def director_server_set_scale_patch(map_name):
|
||||||
|
try:
|
||||||
|
if not director_svc:
|
||||||
|
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||||
|
config = request.get_json()
|
||||||
|
replicas = int(config.get('replicas', 1))
|
||||||
|
partitions_raw = config.get('partitions', [])
|
||||||
|
partitions = [int(p) for p in partitions_raw if p is not None]
|
||||||
|
if replicas > len(partitions):
|
||||||
|
return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400
|
||||||
|
if not director_svc.patch_server_set_scale(map_name, replicas, partitions):
|
||||||
|
return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500
|
||||||
|
return jsonify({'success': True})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
# Update management
|
# Update management
|
||||||
@app.route('/api/update/status')
|
@app.route('/api/update/status')
|
||||||
@auth_req
|
@auth_req
|
||||||
@@ -1219,7 +1341,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Broadcast ─────────────────────────────────
|
# ── Admin Experimental: Broadcast ─────────────────────────────────
|
||||||
@app.route('/api/admin-experimental/broadcast', methods=['POST'])
|
@app.route('/api/admin-experimental/broadcast', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_broadcast():
|
def admin_broadcast():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
title = (data.get('title') or '').strip()
|
title = (data.get('title') or '').strip()
|
||||||
@@ -1236,7 +1358,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Query Database ────────────────────────────
|
# ── Admin Experimental: Query Database ────────────────────────────
|
||||||
@app.route('/api/admin-experimental/query', methods=['POST'])
|
@app.route('/api/admin-experimental/query', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("300 per hour")
|
|
||||||
def admin_query():
|
def admin_query():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
sql = (data.get('sql') or '').strip()
|
sql = (data.get('sql') or '').strip()
|
||||||
@@ -1275,7 +1397,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Adjust Currency ───────────────────────────
|
# ── Admin Experimental: Adjust Currency ───────────────────────────
|
||||||
@app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
|
@app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_adjust_currency():
|
def admin_adjust_currency():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
pid = data.get('player_controller_id')
|
pid = data.get('player_controller_id')
|
||||||
@@ -1289,7 +1411,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Change Faction ────────────────────────────
|
# ── Admin Experimental: Change Faction ────────────────────────────
|
||||||
@app.route('/api/admin-experimental/change-faction', methods=['POST'])
|
@app.route('/api/admin-experimental/change-faction', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_change_faction():
|
def admin_change_faction():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
pid = data.get('player_id')
|
pid = data.get('player_id')
|
||||||
@@ -1329,7 +1451,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Teleport Player ───────────────────────────
|
# ── Admin Experimental: Teleport Player ───────────────────────────
|
||||||
@app.route('/api/admin-experimental/teleport', methods=['POST'])
|
@app.route('/api/admin-experimental/teleport', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_teleport():
|
def admin_teleport():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
fls_id = data.get('fls_id')
|
fls_id = data.get('fls_id')
|
||||||
@@ -1413,7 +1535,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/disband-guild', methods=['POST'])
|
@app.route('/api/admin-experimental/disband-guild', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def admin_disband_guild():
|
def admin_disband_guild():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
guild_id = data.get('guild_id')
|
guild_id = data.get('guild_id')
|
||||||
@@ -1427,7 +1549,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
|
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_remove_guild_member():
|
def admin_remove_guild_member():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
guild_id = data.get('guild_id')
|
guild_id = data.get('guild_id')
|
||||||
@@ -1460,7 +1582,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
|
@app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def admin_flag_cheater():
|
def admin_flag_cheater():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
account_id = data.get('account_id')
|
account_id = data.get('account_id')
|
||||||
@@ -1519,7 +1641,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/delete-character', methods=['POST'])
|
@app.route('/api/admin-experimental/delete-character', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("20 per hour")
|
|
||||||
def admin_delete_character():
|
def admin_delete_character():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
actor_id = data.get('actor_id')
|
actor_id = data.get('actor_id')
|
||||||
@@ -1533,7 +1655,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/delete-account', methods=['POST'])
|
@app.route('/api/admin-experimental/delete-account', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("10 per hour")
|
|
||||||
def admin_delete_account():
|
def admin_delete_account():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
user_id = data.get('user_id')
|
user_id = data.get('user_id')
|
||||||
@@ -1650,7 +1772,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Spice Fields ──────────────────────────────
|
# ── Admin Experimental: Spice Fields ──────────────────────────────
|
||||||
@app.route('/api/admin-experimental/spice', methods=['POST'])
|
@app.route('/api/admin-experimental/spice', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("30 per hour")
|
|
||||||
def admin_spice():
|
def admin_spice():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
try:
|
try:
|
||||||
@@ -1665,7 +1787,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Server Tools ──────────────────────────────
|
# ── Admin Experimental: Server Tools ──────────────────────────────
|
||||||
@app.route('/api/admin-experimental/server-tools', methods=['POST'])
|
@app.route('/api/admin-experimental/server-tools', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("30 per hour")
|
|
||||||
def admin_server_tools():
|
def admin_server_tools():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
try:
|
try:
|
||||||
@@ -1696,6 +1818,118 @@ def register_api_routes(app, services, settings):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({'success': False, 'error': str(e)})
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
# ── Admin Experimental: RMQ Explorer ─────────────────────────────
|
||||||
|
@app.route('/api/admin-experimental/rmq/overview')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_overview():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_overview()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/queues')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_queues():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_queues()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/exchanges')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_exchanges():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_exchanges()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/bindings')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_bindings():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.bindings()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/consumers')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_consumers():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.consumers()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/peek', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_peek():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
cfg = request.get_json() or {}
|
||||||
|
queue_name = cfg.get('queue', '')
|
||||||
|
count = int(cfg.get('count', 5))
|
||||||
|
if not queue_name:
|
||||||
|
return jsonify({'success': False, 'error': 'queue name required'}), 400
|
||||||
|
data = rmq.peek_messages(queue_name, count=count)
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/publish', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_publish():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
cfg = request.get_json() or {}
|
||||||
|
exchange = cfg.get('exchange', '')
|
||||||
|
routing_key = cfg.get('routing_key', '')
|
||||||
|
message = cfg.get('message', '')
|
||||||
|
side = cfg.get('side', 'admin')
|
||||||
|
if not exchange:
|
||||||
|
return jsonify({'success': False, 'error': 'exchange name required'}), 400
|
||||||
|
if side == 'game':
|
||||||
|
result = rmq.game_publish(exchange, routing_key, message)
|
||||||
|
else:
|
||||||
|
result = rmq.publish(exchange, routing_key, message)
|
||||||
|
return jsonify({'success': True, 'data': result})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/health')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_health():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.health()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
# ── Admin Experimental: Function Explorer ─────────────────────────
|
# ── Admin Experimental: Function Explorer ─────────────────────────
|
||||||
@app.route('/api/admin-experimental/functions', methods=['GET'])
|
@app.route('/api/admin-experimental/functions', methods=['GET'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@@ -1719,7 +1953,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
|
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_execute_function(name):
|
def admin_execute_function(name):
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
params = data.get('params', [])
|
params = data.get('params', [])
|
||||||
@@ -1735,7 +1969,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: SQL Execute (admin functions) ─────────────
|
# ── Admin Experimental: SQL Execute (admin functions) ─────────────
|
||||||
@app.route('/api/admin-experimental/execute', methods=['POST'])
|
@app.route('/api/admin-experimental/execute', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_execute():
|
def admin_execute():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
sql = (data.get('sql') or '').strip()
|
sql = (data.get('sql') or '').strip()
|
||||||
|
|||||||
+44
-30
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import time
|
import time
|
||||||
import threading
|
import threading
|
||||||
from flask import render_template, request, redirect, url_for, flash
|
from flask import render_template, request, redirect, url_for, flash, session, make_response
|
||||||
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
||||||
from flask_limiter import Limiter
|
from flask_limiter import Limiter
|
||||||
from flask_limiter.util import get_remote_address
|
from flask_limiter.util import get_remote_address
|
||||||
@@ -14,6 +14,15 @@ login_manager.login_message = 'Please log in.'
|
|||||||
# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}}
|
# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}}
|
||||||
_failed_attempts = {}
|
_failed_attempts = {}
|
||||||
_failed_lock = threading.Lock()
|
_failed_lock = threading.Lock()
|
||||||
|
|
||||||
|
# Reusable Argon2 verifier (created once, not per-request)
|
||||||
|
try:
|
||||||
|
from argon2 import PasswordHasher, exceptions as argon2_exceptions
|
||||||
|
_password_hasher = PasswordHasher(time_cost=3, memory_cost=65536)
|
||||||
|
except ImportError:
|
||||||
|
_password_hasher = None
|
||||||
|
argon2_exceptions = None
|
||||||
|
_failed_lock = threading.Lock()
|
||||||
_MAX_FAILED_ATTEMPTS = 5
|
_MAX_FAILED_ATTEMPTS = 5
|
||||||
_BLOCK_DURATION = 900 # 15 minutes
|
_BLOCK_DURATION = 900 # 15 minutes
|
||||||
|
|
||||||
@@ -82,39 +91,41 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
|
|||||||
u = request.form.get('username', '')
|
u = request.form.get('username', '')
|
||||||
p = request.form.get('password', '')
|
p = request.form.get('password', '')
|
||||||
auth = settings.get('auth', {})
|
auth = settings.get('auth', {})
|
||||||
|
|
||||||
cfg_u = str(auth.get('username', ''))
|
cfg_u = str(auth.get('username', ''))
|
||||||
password_hash = auth.get('password_hash')
|
password_hash = auth.get('password_hash')
|
||||||
|
|
||||||
if u != cfg_u:
|
if not password_hash:
|
||||||
if audit_svc:
|
flash('Authentication not configured. Please run setup.')
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_username'}, user='unknown', severity='warning')
|
return render_template('login.html')
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Always run Argon2 verify regardless of username (prevents timing enumeration)
|
||||||
|
from argon2 import exceptions
|
||||||
|
_DUMMY = '$argon2id$v=19$m=65536,t=3,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
|
||||||
|
hash_to_verify = password_hash if u == cfg_u else _DUMMY
|
||||||
|
verified = _password_hasher.verify(hash_to_verify, p)
|
||||||
|
|
||||||
|
if verified and u == cfg_u:
|
||||||
|
_clear_failed_attempts(client_ip)
|
||||||
|
login_user(AdminUser(u))
|
||||||
|
if audit_svc:
|
||||||
|
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
|
||||||
|
return redirect(url_for('overview'))
|
||||||
|
else:
|
||||||
|
# Dummy always fails; wrong password also fails here
|
||||||
|
_record_failed_attempt(client_ip)
|
||||||
|
if u == cfg_u and audit_svc:
|
||||||
|
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
||||||
|
elif audit_svc:
|
||||||
|
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_credentials'}, user='unknown', severity='warning')
|
||||||
|
flash('Invalid username or password')
|
||||||
|
return render_template('login.html')
|
||||||
|
except exceptions.VerifyMismatchError:
|
||||||
_record_failed_attempt(client_ip)
|
_record_failed_attempt(client_ip)
|
||||||
flash('Invalid username or password')
|
flash('Invalid username or password')
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
except Exception as e:
|
||||||
if password_hash:
|
flash('Authentication error. Please try again.')
|
||||||
try:
|
|
||||||
from argon2 import PasswordHasher, exceptions
|
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
|
||||||
if ph.verify(password_hash, p):
|
|
||||||
_clear_failed_attempts(client_ip)
|
|
||||||
login_user(AdminUser(u))
|
|
||||||
if audit_svc:
|
|
||||||
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
|
|
||||||
return redirect(url_for('overview'))
|
|
||||||
else:
|
|
||||||
if audit_svc:
|
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
|
||||||
except exceptions.VerifyMismatchError:
|
|
||||||
if audit_svc:
|
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
|
||||||
pass
|
|
||||||
except Exception:
|
|
||||||
flash('Authentication error. Please try again.')
|
|
||||||
return render_template('login.html')
|
|
||||||
else:
|
|
||||||
flash('Authentication not configured. Please run setup.')
|
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
_record_failed_attempt(client_ip)
|
_record_failed_attempt(client_ip)
|
||||||
@@ -123,10 +134,13 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
|
|||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
@app.route('/logout')
|
@app.route('/logout')
|
||||||
@login_required
|
|
||||||
def logout():
|
def logout():
|
||||||
user = current_user.id if current_user.is_authenticated else 'unknown'
|
user = current_user.id if current_user.is_authenticated else 'unknown'
|
||||||
logout_user()
|
logout_user()
|
||||||
|
session.clear()
|
||||||
if audit_svc:
|
if audit_svc:
|
||||||
audit_svc.log('logout', {}, user=user, severity='info')
|
audit_svc.log('logout', {}, user=user, severity='info')
|
||||||
return redirect(url_for('login'))
|
resp = make_response(redirect(url_for('login')))
|
||||||
|
resp.delete_cookie('session')
|
||||||
|
resp.delete_cookie('remember_token')
|
||||||
|
return resp
|
||||||
+77
-18
@@ -6,6 +6,7 @@ from flask import Blueprint, render_template, request, jsonify
|
|||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
||||||
from app.utils.debug_logging import sanitize_for_log
|
from app.utils.debug_logging import sanitize_for_log
|
||||||
|
from app.services.player import LIKE_PC
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -326,20 +327,32 @@ def register_routes(app, services, settings):
|
|||||||
try:
|
try:
|
||||||
buildings_list = db.query("""
|
buildings_list = db.query("""
|
||||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
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,
|
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name,
|
||||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count,
|
(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_bIsPowered' as is_powered,
|
||||||
a.properties->>'m_PowerLevel' as power_level,
|
a.properties->>'m_PowerLevel' as power_level,
|
||||||
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
|
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
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 LATERAL (
|
||||||
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
|
FROM dune.building_instances bi
|
||||||
)
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT ps.character_name
|
||||||
|
FROM dune.actors pawn
|
||||||
|
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
ORDER BY owner_name
|
ORDER BY owner_name
|
||||||
LIMIT 200
|
LIMIT 200
|
||||||
""") or []
|
""", [LIKE_PC]) or []
|
||||||
return render_template('buildings.html', buildings=buildings_list)
|
return render_template('buildings.html', buildings=buildings_list)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error in buildings route")
|
logger.exception("Error in buildings route")
|
||||||
@@ -426,7 +439,7 @@ def register_routes(app, services, settings):
|
|||||||
def server_status():
|
def server_status():
|
||||||
logger.debug(f"Page access: /server by user={current_user.id}")
|
logger.debug(f"Page access: /server by user={current_user.id}")
|
||||||
try:
|
try:
|
||||||
active_servers = db.query("""
|
active_servers_raw = db.query("""
|
||||||
SELECT server_id, map
|
SELECT server_id, map
|
||||||
FROM dune.world_partition
|
FROM dune.world_partition
|
||||||
WHERE server_id IS NOT NULL
|
WHERE server_id IS NOT NULL
|
||||||
@@ -448,6 +461,34 @@ def register_routes(app, services, settings):
|
|||||||
deployments = k8s.get_deployments()
|
deployments = k8s.get_deployments()
|
||||||
node_metrics = k8s.get_node_metrics()
|
node_metrics = k8s.get_node_metrics()
|
||||||
|
|
||||||
|
active_servers = []
|
||||||
|
for s in active_servers_raw:
|
||||||
|
sid = (s.get('server_id') or '').lower().replace('_', '-')
|
||||||
|
s['deployment'] = ''
|
||||||
|
mp = (s.get('map') or '').lower().replace('_', '-')
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if sid and sid in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if mp and mp in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if not s['deployment']:
|
||||||
|
mid = '-sg-' + sid
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if mid in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if not s['deployment'] and mp:
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if mp in short.lower() and 'pod' in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
active_servers.append(s)
|
||||||
|
|
||||||
for p in partitions:
|
for p in partitions:
|
||||||
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
||||||
p['deployment'] = ''
|
p['deployment'] = ''
|
||||||
@@ -482,7 +523,7 @@ def register_routes(app, services, settings):
|
|||||||
online_players=online_players, partitions=partitions,
|
online_players=online_players, partitions=partitions,
|
||||||
overmap_count=overmap_count.get('c') if overmap_count else 0,
|
overmap_count=overmap_count.get('c') if overmap_count else 0,
|
||||||
online_count=online_count.get('c') if online_count else 0,
|
online_count=online_count.get('c') if online_count else 0,
|
||||||
deployments=deployments, deploys_ok=True, ssh_error='',
|
deployments=deployments, deploys_ok=len(deployments) > 0, ssh_error='',
|
||||||
node_metrics=node_metrics)
|
node_metrics=node_metrics)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error in server_status route")
|
logger.exception("Error in server_status route")
|
||||||
@@ -524,7 +565,7 @@ def register_routes(app, services, settings):
|
|||||||
name: cfg for name, cfg in map_config.items()
|
name: cfg for name, cfg in map_config.items()
|
||||||
if isinstance(cfg, dict) and cfg.get('image') and cfg.get('bounds')
|
if isinstance(cfg, dict) and cfg.get('image') and cfg.get('bounds')
|
||||||
}
|
}
|
||||||
default_map = map_config.get('default_map', 'DeepDesert')
|
default_map = map_config.get('default_map', 'HaggaBasin')
|
||||||
|
|
||||||
return map_config, configured_maps, default_map
|
return map_config, configured_maps, default_map
|
||||||
|
|
||||||
@@ -535,6 +576,7 @@ def register_routes(app, services, settings):
|
|||||||
map_options = []
|
map_options = []
|
||||||
for key, cfg in configured_maps.items():
|
for key, cfg in configured_maps.items():
|
||||||
image_size = cfg.get('image_size', {})
|
image_size = cfg.get('image_size', {})
|
||||||
|
bounds = cfg.get('bounds', {})
|
||||||
map_options.append({
|
map_options.append({
|
||||||
'key': key,
|
'key': key,
|
||||||
'label': cfg.get('label') or key,
|
'label': cfg.get('label') or key,
|
||||||
@@ -542,6 +584,7 @@ def register_routes(app, services, settings):
|
|||||||
'width': image_size.get('width', 1000),
|
'width': image_size.get('width', 1000),
|
||||||
'height': image_size.get('height', 1000),
|
'height': image_size.get('height', 1000),
|
||||||
'default_zoom': cfg.get('default_zoom', 0.5),
|
'default_zoom': cfg.get('default_zoom', 0.5),
|
||||||
|
'bounds': bounds,
|
||||||
'counts': {
|
'counts': {
|
||||||
'players': sum(1 for p in player_locations if p.get('map') == key and p.get('in_bounds')),
|
'players': sum(1 for p in player_locations if p.get('map') == key and p.get('in_bounds')),
|
||||||
'vehicles': sum(1 for v in vehicle_locations if v.get('map') == key and v.get('in_bounds')),
|
'vehicles': sum(1 for v in vehicle_locations if v.get('map') == key and v.get('in_bounds')),
|
||||||
@@ -569,27 +612,43 @@ def register_routes(app, services, settings):
|
|||||||
|
|
||||||
# Get vehicles with coordinates for configured map assets
|
# Get vehicles with coordinates for configured map assets
|
||||||
vehicles = db.query("""
|
vehicles = db.query("""
|
||||||
SELECT v.id, a.map, a.transform, a.class
|
SELECT DISTINCT ON (v.id)
|
||||||
|
v.id, a.map, a.transform, a.class,
|
||||||
|
COALESCE(NULLIF(ps.character_name, ''), 'Vehicle ' || v.id::text) as owner_name
|
||||||
FROM dune.vehicles v
|
FROM dune.vehicles v
|
||||||
JOIN dune.actors a ON v.id = a.id
|
JOIN dune.actors a ON v.id = a.id
|
||||||
|
LEFT JOIN dune.permission_actor_rank par ON par.permission_actor_id = v.id
|
||||||
|
LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id
|
||||||
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
||||||
ORDER BY a.map, a.class
|
ORDER BY v.id, par.rank ASC
|
||||||
""", [selected_map_keys]) or []
|
""", [selected_map_keys]) or []
|
||||||
|
|
||||||
# Get bases/buildings with coordinates for configured map assets
|
# Get bases/buildings with coordinates for configured map assets
|
||||||
buildings = db.query("""
|
buildings = db.query("""
|
||||||
SELECT b.id, a.map, a.transform, a.class,
|
SELECT b.id, a.map, a.transform, a.class,
|
||||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'Base ' || b.id::text) as owner_name
|
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
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 LATERAL (
|
||||||
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
|
FROM dune.building_instances bi
|
||||||
)
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT ps.character_name
|
||||||
|
FROM dune.actors pawn
|
||||||
|
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
||||||
ORDER BY a.map
|
ORDER BY a.map
|
||||||
LIMIT 500
|
LIMIT 500
|
||||||
""", [selected_map_keys]) or []
|
""", [LIKE_PC, selected_map_keys]) or []
|
||||||
|
|
||||||
# Parse coordinates from transform field
|
# Parse coordinates from transform field
|
||||||
def parse_transform(t):
|
def parse_transform(t):
|
||||||
@@ -631,7 +690,7 @@ def register_routes(app, services, settings):
|
|||||||
if coords:
|
if coords:
|
||||||
vehicle_locations.append({
|
vehicle_locations.append({
|
||||||
'id': v['id'],
|
'id': v['id'],
|
||||||
'name': v.get('name', 'Unknown'),
|
'name': v.get('owner_name') or v.get('class', '').split('/')[-1] if v.get('class') else f'Vehicle {v["id"]}',
|
||||||
'map': v['map'],
|
'map': v['map'],
|
||||||
'class': v.get('class', '').split('/')[-1] if v.get('class') else '',
|
'class': v.get('class', '').split('/')[-1] if v.get('class') else '',
|
||||||
'x': coords['x'],
|
'x': coords['x'],
|
||||||
|
|||||||
+76
-86
@@ -26,9 +26,10 @@ def _validate_ip(ip):
|
|||||||
class AdminService:
|
class AdminService:
|
||||||
_iptables_lock = threading.Lock()
|
_iptables_lock = threading.Lock()
|
||||||
|
|
||||||
def __init__(self, db_service, ssh_service):
|
def __init__(self, db_service, ssh_service, dash_db=None):
|
||||||
self.db = db_service
|
self.db = db_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
|
self.dash_db = dash_db or db_service
|
||||||
|
|
||||||
def ban_player(self, player_id, duration=0, reason='', note=''):
|
def ban_player(self, player_id, duration=0, reason='', note=''):
|
||||||
try:
|
try:
|
||||||
@@ -44,17 +45,11 @@ class AdminService:
|
|||||||
account_id = player_row.get('account_id') if player_row else None
|
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'
|
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:
|
try:
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
if account_id:
|
if account_id:
|
||||||
if duration_int == 0:
|
if duration_int == 0:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
|
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||||
@@ -62,8 +57,8 @@ class AdminService:
|
|||||||
banned_at = NOW(), expires_at = NULL, active = TRUE
|
banned_at = NOW(), expires_at = NULL, active = TRUE
|
||||||
""", [player_id, account_id, reason, note, duration_int])
|
""", [player_id, account_id, reason, note, duration_int])
|
||||||
else:
|
else:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO 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)
|
VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||||
@@ -72,8 +67,8 @@ class AdminService:
|
|||||||
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
||||||
else:
|
else:
|
||||||
if duration_int == 0:
|
if duration_int == 0:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
|
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||||
@@ -81,8 +76,8 @@ class AdminService:
|
|||||||
expires_at = NULL, active = TRUE
|
expires_at = NULL, active = TRUE
|
||||||
""", [player_id, reason, note, duration_int])
|
""", [player_id, reason, note, duration_int])
|
||||||
else:
|
else:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||||
@@ -90,47 +85,47 @@ class AdminService:
|
|||||||
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||||
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
|
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
|
||||||
return True, f"Player {player_name} banned for {duration_int} minutes"
|
return True, f"Player {player_name} banned for {duration_int} minutes"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to ban player {player_id}: {e}")
|
logger.error(f"Failed to ban player {player_id}: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def unban_player(self, player_id):
|
def unban_player(self, player_id):
|
||||||
conn = self.db.get_connection()
|
|
||||||
if not conn:
|
|
||||||
return False, "Database connection failed"
|
|
||||||
cur = None
|
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
# Delete from dashboard bans
|
||||||
cur.execute("DELETE FROM dashboard.bans WHERE player_id = %s", [player_id])
|
self.dash_db.execute("DELETE FROM 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])
|
# Look up account info from game database
|
||||||
account_row = cur.fetchone()
|
account_row = self.db.query(
|
||||||
account_id = account_row[0] if account_row and isinstance(account_row, (tuple, list)) else (account_row.get('account_id') if account_row else None)
|
"SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s",
|
||||||
|
[player_id], one=True
|
||||||
|
)
|
||||||
|
account_id = account_row.get('account_id') if account_row else None
|
||||||
|
|
||||||
ips_to_unblock = []
|
ips_to_unblock = []
|
||||||
if account_id:
|
if account_id:
|
||||||
all_ips = self.db.query("""
|
game_account_players = self.db.query(
|
||||||
SELECT ip_address FROM dashboard.player_ips
|
"SELECT player_controller_id FROM dune.player_state WHERE account_id = %s",
|
||||||
WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s)
|
[account_id]
|
||||||
""", [account_id]) or []
|
) or []
|
||||||
ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')]
|
account_player_ids = [r['player_controller_id'] for r in game_account_players]
|
||||||
|
if account_player_ids:
|
||||||
|
placeholders = ','.join(['%s'] * len(account_player_ids))
|
||||||
|
ips_rows = self.dash_db.query(
|
||||||
|
f"SELECT ip_address FROM player_ips WHERE player_id IN ({placeholders})",
|
||||||
|
account_player_ids
|
||||||
|
) or []
|
||||||
|
ips_to_unblock = [r.get('ip_address') for r in ips_rows if r.get('ip_address')]
|
||||||
else:
|
else:
|
||||||
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
|
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
|
||||||
if ip_row and ip_row.get('ip_address'):
|
if ip_row and ip_row.get('ip_address'):
|
||||||
ips_to_unblock.append(ip_row.get('ip_address'))
|
ips_to_unblock.append(ip_row.get('ip_address'))
|
||||||
|
|
||||||
cur.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
|
self.dash_db.execute(
|
||||||
conn.commit()
|
"INSERT INTO player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)",
|
||||||
|
[player_id]
|
||||||
|
)
|
||||||
|
|
||||||
with self._iptables_lock:
|
with self._iptables_lock:
|
||||||
for ip in ips_to_unblock:
|
for ip in ips_to_unblock:
|
||||||
@@ -144,13 +139,7 @@ class AdminService:
|
|||||||
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
|
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to unban player {player_id}: {e}")
|
logger.error(f"Failed to unban player {player_id}: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def kick_player(self, player_id):
|
def kick_player(self, player_id):
|
||||||
player = self.db.query("""
|
player = self.db.query("""
|
||||||
@@ -163,7 +152,7 @@ class AdminService:
|
|||||||
return False, "Player not found"
|
return False, "Player not found"
|
||||||
|
|
||||||
player_name = player.get('character_name', 'Unknown')
|
player_name = player.get('character_name', 'Unknown')
|
||||||
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
|
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
|
||||||
player_ip = ip_row.get('ip_address') if ip_row else None
|
player_ip = ip_row.get('ip_address') if ip_row else None
|
||||||
|
|
||||||
if not player_ip:
|
if not player_ip:
|
||||||
@@ -184,7 +173,7 @@ class AdminService:
|
|||||||
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
self.db.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
self.dash_db.execute("INSERT INTO player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
||||||
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
|
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
|
||||||
|
|
||||||
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
||||||
@@ -262,14 +251,8 @@ class AdminService:
|
|||||||
if not game_pods:
|
if not game_pods:
|
||||||
return False, "No game server pods found"
|
return False, "No game server pods found"
|
||||||
|
|
||||||
conn = self.db.get_connection()
|
|
||||||
if not conn:
|
|
||||||
return False, "Database connection failed"
|
|
||||||
cur = None
|
|
||||||
updated = 0
|
updated = 0
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
for pod_name, map_name in game_pods:
|
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'
|
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)
|
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
|
||||||
@@ -302,26 +285,25 @@ class AdminService:
|
|||||||
|
|
||||||
if ip_to_player:
|
if ip_to_player:
|
||||||
for ip, name in ip_to_player.items():
|
for ip, name in ip_to_player.items():
|
||||||
cur.execute("""
|
player_row = self.db.query("""
|
||||||
SELECT ps.player_controller_id, ps.account_id
|
SELECT ps.player_controller_id, ps.account_id
|
||||||
FROM dune.player_state ps
|
FROM dune.player_state ps
|
||||||
JOIN dune.accounts a ON ps.account_id = a.id
|
JOIN dune.accounts a ON ps.account_id = a.id
|
||||||
WHERE a.funcom_id = %s OR ps.character_name = %s
|
WHERE a.funcom_id = %s OR ps.character_name = %s
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""", [name, name])
|
""", [name, name], one=True)
|
||||||
row = cur.fetchone()
|
if player_row:
|
||||||
if row:
|
pid = player_row.get('player_controller_id')
|
||||||
pid = row[0] if isinstance(row, (tuple, list)) else row.get('funcom_id')
|
account_id = player_row.get('account_id')
|
||||||
account_id = row[1] if isinstance(row, (tuple, list)) else row.get('account_id')
|
self.dash_db.execute("""
|
||||||
cur.execute("""
|
INSERT INTO player_ips (player_id, ip_address, updated_at)
|
||||||
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
|
|
||||||
VALUES (%s, %s, NOW())
|
VALUES (%s, %s, NOW())
|
||||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||||
""", [pid, ip])
|
""", [pid, ip])
|
||||||
updated += 1
|
updated += 1
|
||||||
|
|
||||||
ban_check = self.db.query("""
|
ban_check = self.dash_db.query("""
|
||||||
SELECT player_id FROM dashboard.bans
|
SELECT player_id FROM bans
|
||||||
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""", [pid, account_id], one=True)
|
""", [pid, account_id], one=True)
|
||||||
@@ -334,21 +316,14 @@ class AdminService:
|
|||||||
else:
|
else:
|
||||||
logger.warning(f"Skipping invalid IP for ban block: {ip}")
|
logger.warning(f"Skipping invalid IP for ban block: {ip}")
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
return True, f"Updated {updated} player IPs from game logs"
|
return True, f"Updated {updated} player IPs from game logs"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to detect player IPs: {e}")
|
logger.error(f"Failed to detect player IPs: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def set_player_ip(self, player_id, ip_address):
|
def set_player_ip(self, player_id, ip_address):
|
||||||
return self.db.execute("""
|
return self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
|
INSERT INTO player_ips (player_id, ip_address, updated_at)
|
||||||
VALUES (%s, %s, NOW())
|
VALUES (%s, %s, NOW())
|
||||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||||
""", [player_id, ip_address])
|
""", [player_id, ip_address])
|
||||||
@@ -363,21 +338,31 @@ class AdminService:
|
|||||||
return True, f"Unblocked {ip}"
|
return True, f"Unblocked {ip}"
|
||||||
|
|
||||||
def get_bans(self, limit=50):
|
def get_bans(self, limit=50):
|
||||||
return self.db.query("""
|
bans = self.dash_db.query("""
|
||||||
SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name
|
SELECT id, player_id, reason, active, banned_at, expires_at
|
||||||
FROM dashboard.bans b
|
FROM bans
|
||||||
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
|
ORDER BY banned_at DESC
|
||||||
ORDER BY b.banned_at DESC
|
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""", [limit]) or []
|
""", [limit]) or []
|
||||||
|
for ban in bans:
|
||||||
|
pid = ban.get('player_id')
|
||||||
|
if pid:
|
||||||
|
player = self.db.query(
|
||||||
|
"SELECT character_name FROM dune.player_state WHERE player_controller_id = %s",
|
||||||
|
[pid], one=True
|
||||||
|
)
|
||||||
|
ban['character_name'] = player.get('character_name', '') if player else ''
|
||||||
|
else:
|
||||||
|
ban['character_name'] = ''
|
||||||
|
return bans
|
||||||
|
|
||||||
def get_player_ban(self, player_id):
|
def get_player_ban(self, player_id):
|
||||||
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dashboard.bans WHERE player_id = %s", [player_id], one=True)
|
return self.dash_db.query("SELECT reason, note, duration, banned_at, expires_at FROM bans WHERE player_id = %s", [player_id], one=True)
|
||||||
|
|
||||||
def get_player_history(self, player_id, limit=20):
|
def get_player_history(self, player_id, limit=20):
|
||||||
return self.db.query("""
|
return self.dash_db.query("""
|
||||||
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
||||||
FROM dashboard.player_actions
|
FROM player_actions
|
||||||
WHERE player_id = %s
|
WHERE player_id = %s
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
@@ -813,17 +798,22 @@ class AdminService:
|
|||||||
try:
|
try:
|
||||||
import base64
|
import base64
|
||||||
import json as _json
|
import json as _json
|
||||||
title_json = _json.dumps(title)[1:-1]
|
import os
|
||||||
message_json = _json.dumps(message)[1:-1]
|
|
||||||
|
token = os.environ.get('DUNE_BROADCAST_TOKEN',
|
||||||
|
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
|
||||||
|
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
|
||||||
|
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
|
||||||
|
|
||||||
erl = (
|
erl = (
|
||||||
f'Title = unicode:characters_to_binary(<<"{title_json}">>, utf8), '
|
f'Title = base64:decode(<<"{title_b64}">>), '
|
||||||
f'Body = unicode:characters_to_binary(<<"{message_json}">>, utf8), '
|
f'Body = base64:decode(<<"{message_b64}">>), '
|
||||||
f'Duration = {duration}, '
|
f'Duration = {duration}, '
|
||||||
|
f'Token = <<"{token}">>, '
|
||||||
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
||||||
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, <<"MessageContent">> => Inner})), '
|
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => Token, <<"MessageContent">> => Inner})), '
|
||||||
'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), '
|
'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), '
|
||||||
'X = rabbit_exchange:lookup_or_die(XName), '
|
'X = rabbit_exchange:lookup_or_die(XName), '
|
||||||
'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), '
|
'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), '
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class ChatService:
|
class ChatService:
|
||||||
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
||||||
self.db = db_service
|
self.db = db_service # DashboardDatabaseService
|
||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.cache = cache
|
self.cache = cache
|
||||||
@@ -20,7 +20,7 @@ class ChatService:
|
|||||||
return True
|
return True
|
||||||
try:
|
try:
|
||||||
self.db.execute("""
|
self.db.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
|
CREATE TABLE IF NOT EXISTS chat_history (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
timestamp TIMESTAMP DEFAULT NOW(),
|
||||||
channel VARCHAR(50),
|
channel VARCHAR(50),
|
||||||
@@ -33,7 +33,7 @@ class ChatService:
|
|||||||
is_admin BOOLEAN DEFAULT FALSE
|
is_admin BOOLEAN DEFAULT FALSE
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)")
|
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC)")
|
||||||
self.ensured_table = True
|
self.ensured_table = True
|
||||||
logger.info("Chat history table ready")
|
logger.info("Chat history table ready")
|
||||||
return True
|
return True
|
||||||
@@ -46,7 +46,7 @@ class ChatService:
|
|||||||
loc_y = location.get('Y', 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
|
loc_z = location.get('Z', 0) if location else 0
|
||||||
return self.db.execute("""
|
return self.db.execute("""
|
||||||
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
|
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ class ChatService:
|
|||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
""", [
|
""", [
|
||||||
msg['channel'], msg['sender'], msg['message'],
|
msg['channel'], msg['sender'], msg['message'],
|
||||||
@@ -87,7 +87,7 @@ class ChatService:
|
|||||||
return self.db.query("""
|
return self.db.query("""
|
||||||
SELECT id, timestamp, channel, sender, message, target,
|
SELECT id, timestamp, channel, sender, message, target,
|
||||||
location_x, location_y, location_z, is_admin
|
location_x, location_y, location_z, is_admin
|
||||||
FROM dashboard.chat_history
|
FROM chat_history
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""", [limit])
|
""", [limit])
|
||||||
|
|||||||
+248
-12
@@ -10,11 +10,10 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class DatabaseService:
|
class DatabaseService:
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema='dashboard'):
|
def __init__(self, db_config, min_conn=2, max_conn=10):
|
||||||
self.db_config = db_config
|
self.db_config = db_config
|
||||||
self.min_conn = min_conn
|
self.min_conn = min_conn
|
||||||
self.max_conn = max_conn
|
self.max_conn = max_conn
|
||||||
self.dashboard_schema = dashboard_schema
|
|
||||||
self.pool = None
|
self.pool = None
|
||||||
|
|
||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
@@ -138,23 +137,186 @@ class DatabaseService:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
def ensure_tables(self):
|
def ensure_tables(self):
|
||||||
|
"""No-op: dashboard tables now live in a separate database."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DashboardDatabaseService:
|
||||||
|
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
|
||||||
|
|
||||||
|
def __init__(self, db_config, min_conn=2, max_conn=10, owner='dune'):
|
||||||
|
self.db_config = db_config
|
||||||
|
self.min_conn = min_conn
|
||||||
|
self.max_conn = max_conn
|
||||||
|
self.owner = owner
|
||||||
|
self.pool = None
|
||||||
|
self._migrated = False
|
||||||
|
|
||||||
|
def init_pool(self):
|
||||||
|
if self.pool is not None:
|
||||||
|
return self.pool
|
||||||
|
for attempt in range(10):
|
||||||
|
try:
|
||||||
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
|
minconn=self.min_conn,
|
||||||
|
maxconn=self.max_conn,
|
||||||
|
**self.db_config
|
||||||
|
)
|
||||||
|
logger.info("Dashboard database pool initialized")
|
||||||
|
return self.pool
|
||||||
|
except psycopg2.OperationalError as e:
|
||||||
|
if 'does not exist' in str(e) and attempt == 0:
|
||||||
|
logger.info("Dashboard database does not exist, creating...")
|
||||||
|
self._ensure_database()
|
||||||
|
continue
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
except Exception as e:
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
return self.pool
|
||||||
|
|
||||||
|
def _ensure_database(self):
|
||||||
|
try:
|
||||||
|
admin_config = dict(self.db_config)
|
||||||
|
admin_config['database'] = 'postgres'
|
||||||
|
conn = psycopg2.connect(**admin_config)
|
||||||
|
conn.autocommit = True
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", [self.db_config['database']])
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute(f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}")
|
||||||
|
logger.info("Created dashboard database '%s'", self.db_config['database'])
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to create dashboard database: %s", e)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _migrate_old_schema(self, game_db):
|
||||||
|
if self._migrated:
|
||||||
|
return
|
||||||
|
tables = ['settings', 'bans', 'player_ips', 'player_actions', 'audit_log', 'chat_history']
|
||||||
|
migrated = False
|
||||||
|
for table in tables:
|
||||||
|
try:
|
||||||
|
rows = game_db.query(f"SELECT count(*) as cnt FROM dashboard.{table}", one=True)
|
||||||
|
if rows and rows.get('cnt', 0) > 0:
|
||||||
|
logger.info("Migrating %d rows from dashboard.%s", rows['cnt'], table)
|
||||||
|
old_rows = game_db.query(f"SELECT * FROM dashboard.{table}")
|
||||||
|
if old_rows:
|
||||||
|
cols = list(old_rows[0].keys())
|
||||||
|
placeholders = ','.join(['%s'] * len(cols))
|
||||||
|
col_names = ','.join(cols)
|
||||||
|
for row in old_rows:
|
||||||
|
vals = [row[c] for c in cols]
|
||||||
|
self.execute(
|
||||||
|
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
|
||||||
|
vals,
|
||||||
|
)
|
||||||
|
migrated = True
|
||||||
|
logger.info("Migrated dashboard.%s -> %s (%d rows)", table, table, rows['cnt'])
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
|
||||||
|
if migrated:
|
||||||
|
logger.info("Data migration from old dashboard schema complete")
|
||||||
|
self._migrated = True
|
||||||
|
|
||||||
|
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("Failed to get dashboard connection: %s", 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("Error closing dashboard pool: %s", 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("Dashboard query error: %s", 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("Dashboard execute error: %s", e)
|
||||||
|
if conn:
|
||||||
|
conn.rollback()
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
if cur:
|
||||||
|
cur.close()
|
||||||
|
self.return_connection(conn)
|
||||||
|
|
||||||
|
def ensure_tables(self, game_db=None):
|
||||||
conn = self.get_connection()
|
conn = self.get_connection()
|
||||||
if not conn:
|
if not conn:
|
||||||
return
|
return
|
||||||
cur = None
|
cur = None
|
||||||
schema = self.dashboard_schema
|
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
|
cur.execute("""
|
||||||
cur.execute(f"""
|
CREATE TABLE IF NOT EXISTS player_ips (
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
|
|
||||||
player_id BIGINT PRIMARY KEY,
|
player_id BIGINT PRIMARY KEY,
|
||||||
ip_address INET NOT NULL,
|
ip_address INET NOT NULL,
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
cur.execute(f"""
|
cur.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.bans (
|
CREATE TABLE IF NOT EXISTS bans (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT UNIQUE,
|
player_id BIGINT UNIQUE,
|
||||||
account_id BIGINT,
|
account_id BIGINT,
|
||||||
@@ -166,8 +328,8 @@ class DatabaseService:
|
|||||||
active BOOLEAN DEFAULT TRUE
|
active BOOLEAN DEFAULT TRUE
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
cur.execute(f"""
|
cur.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
|
CREATE TABLE IF NOT EXISTS player_actions (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT NOT NULL,
|
player_id BIGINT NOT NULL,
|
||||||
action_type VARCHAR(50) NOT NULL,
|
action_type VARCHAR(50) NOT NULL,
|
||||||
@@ -178,13 +340,87 @@ class DatabaseService:
|
|||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
action_type VARCHAR(50) NOT NULL,
|
||||||
|
user_name VARCHAR(100) NOT NULL,
|
||||||
|
target_player_id BIGINT,
|
||||||
|
details JSONB DEFAULT '{}',
|
||||||
|
source_ip INET,
|
||||||
|
severity VARCHAR(20) DEFAULT 'info',
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS 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
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
key VARCHAR(255) PRIMARY KEY,
|
||||||
|
value TEXT DEFAULT '',
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
owner = self.owner
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
logger.info(f"Dashboard tables ensured in schema '{schema}' (player_ips, bans, player_actions)")
|
logger.info("Legacy dashboard tables ensured, owner=%s", owner)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Failed to ensure dashboard tables: {e}")
|
logger.warning("Failed to ensure legacy dashboard tables: %s", e)
|
||||||
if conn:
|
if conn:
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
finally:
|
finally:
|
||||||
if cur:
|
if cur:
|
||||||
cur.close()
|
cur.close()
|
||||||
self.return_connection(conn)
|
self.return_connection(conn)
|
||||||
|
|
||||||
|
if game_db is not None:
|
||||||
|
self._migrate_old_schema(game_db)
|
||||||
|
|
||||||
|
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 as e:
|
||||||
|
logger.warning("Dashboard health check FAILED: %s", e)
|
||||||
|
return False
|
||||||
@@ -27,7 +27,13 @@ class DirectorService:
|
|||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
self.cm_name = f"{namespace}-bgd-conf-cm"
|
resource_prefix = namespace
|
||||||
|
for prefix in ['funcom-seabass-']:
|
||||||
|
if resource_prefix.startswith(prefix):
|
||||||
|
resource_prefix = resource_prefix[len(prefix):]
|
||||||
|
break
|
||||||
|
self.resource_prefix = resource_prefix
|
||||||
|
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
||||||
|
|
||||||
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
||||||
timeout: int = 15, raw_data: bool = False) -> str:
|
timeout: int = 15, raw_data: bool = False) -> str:
|
||||||
@@ -141,8 +147,9 @@ class DirectorService:
|
|||||||
Returns:
|
Returns:
|
||||||
True if the update succeeded, False otherwise.
|
True if the update succeeded, False otherwise.
|
||||||
"""
|
"""
|
||||||
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
||||||
if cm_rc != 0 or not cm_out:
|
if cm_rc != 0 or not cm_out:
|
||||||
|
logger.warning("update_ini_section: could not get ConfigMap %s: %s", self.cm_name, cm_err)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
cm = json.loads(cm_out)
|
cm = json.loads(cm_out)
|
||||||
@@ -165,6 +172,39 @@ class DirectorService:
|
|||||||
cfg.write(buf)
|
cfg.write(buf)
|
||||||
return self.patch_configmap(buf.getvalue())
|
return self.patch_configmap(buf.getvalue())
|
||||||
|
|
||||||
|
# ── ServerSetScale management ────────────────────────────────────
|
||||||
|
|
||||||
|
def _map_to_scale_name(self, map_name: str) -> str:
|
||||||
|
safe = map_name.lower().replace('_', '-')
|
||||||
|
return f"{self.resource_prefix}-{safe}"
|
||||||
|
|
||||||
|
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||||
|
name = self._map_to_scale_name(map_name)
|
||||||
|
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||||
|
f'get serversetscale {name} -o json')
|
||||||
|
if cm_rc != 0 or not cm_out:
|
||||||
|
return None
|
||||||
|
return json.loads(cm_out)
|
||||||
|
|
||||||
|
def patch_server_set_scale(self, map_name: str, replicas: int,
|
||||||
|
partitions: list) -> bool:
|
||||||
|
name = self._map_to_scale_name(map_name)
|
||||||
|
patch = json.dumps({
|
||||||
|
'spec': {
|
||||||
|
'partitions': partitions,
|
||||||
|
'replicas': replicas,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
patch_b64 = base64.b64encode(patch.encode()).decode()
|
||||||
|
cmd = (f'echo {patch_b64} | base64 -d | '
|
||||||
|
f'sudo kubectl patch serversetscale {name} -n {self.namespace} '
|
||||||
|
f'--type merge --patch-file /dev/stdin')
|
||||||
|
out, err, rc = self.ssh.run(cmd, timeout=15)
|
||||||
|
if rc != 0:
|
||||||
|
logger.warning("ServerSetScale patch failed for %s: %s", map_name, err)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
# ── Helper: extract config values for INI update ─────────────────
|
# ── Helper: extract config values for INI update ─────────────────
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
+36
-6
@@ -41,8 +41,9 @@ def _build_player_filters(search='', faction_id='', guild_id='', map_filter='',
|
|||||||
|
|
||||||
|
|
||||||
class PlayerService:
|
class PlayerService:
|
||||||
def __init__(self, db_service):
|
def __init__(self, db_service, dash_db=None):
|
||||||
self.db = db_service
|
self.db = db_service
|
||||||
|
self.dash_db = dash_db
|
||||||
|
|
||||||
def is_online(self, player_controller_id):
|
def is_online(self, player_controller_id):
|
||||||
result = self.db.query(
|
result = self.db.query(
|
||||||
@@ -131,8 +132,7 @@ class PlayerService:
|
|||||||
ea.id as account_id, ea.user as account_email,
|
ea.id as account_id, ea.user as account_email,
|
||||||
acc.funcom_id,
|
acc.funcom_id,
|
||||||
ps.player_controller_id,
|
ps.player_controller_id,
|
||||||
f.name as faction_name, g.guild_name,
|
f.name as faction_name, g.guild_name
|
||||||
pi.ip_address
|
|
||||||
FROM dune.actors a
|
FROM dune.actors a
|
||||||
JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id
|
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.accounts acc ON ea.id = acc.id
|
||||||
@@ -141,7 +141,6 @@ class PlayerService:
|
|||||||
LEFT JOIN dune.factions f ON pf.faction_id = f.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.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.guilds g ON gm.guild_id = g.guild_id
|
||||||
LEFT JOIN dashboard.player_ips pi ON ps.player_controller_id = pi.player_id
|
|
||||||
WHERE {where_clause}
|
WHERE {where_clause}
|
||||||
ORDER BY player_name
|
ORDER BY player_name
|
||||||
LIMIT %s OFFSET %s
|
LIMIT %s OFFSET %s
|
||||||
@@ -151,6 +150,22 @@ class PlayerService:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
||||||
|
|
||||||
|
# Fetch IPs from the dashboard database separately and merge
|
||||||
|
ip_map = {}
|
||||||
|
if self.dash_db and player_ids:
|
||||||
|
placeholders = ','.join(['%s'] * len(player_ids))
|
||||||
|
ip_rows = self.dash_db.query(
|
||||||
|
f"SELECT player_id, ip_address FROM player_ips WHERE player_id IN ({placeholders})",
|
||||||
|
player_ids
|
||||||
|
) or []
|
||||||
|
ip_map = {r['player_id']: r['ip_address'] for r in ip_rows if r.get('player_id')}
|
||||||
|
for p in players:
|
||||||
|
pid = p.get('player_controller_id')
|
||||||
|
if pid and pid in ip_map:
|
||||||
|
p['ip_address'] = ip_map[pid]
|
||||||
|
else:
|
||||||
|
p['ip_address'] = None
|
||||||
actor_ids = [p.get('id') for p in players if p.get('id')]
|
actor_ids = [p.get('id') for p in players if p.get('id')]
|
||||||
|
|
||||||
vehicle_counts = {}
|
vehicle_counts = {}
|
||||||
@@ -254,9 +269,24 @@ class PlayerService:
|
|||||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
JOIN dune.actors a ON b.id = a.id
|
||||||
WHERE b.owner_id = %s
|
JOIN LATERAL (
|
||||||
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
|
FROM dune.building_instances bi
|
||||||
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
JOIN LATERAL (
|
||||||
|
SELECT pawn.id as pawn_id
|
||||||
|
FROM dune.actors pawn
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
|
WHERE owner.pawn_id = %s
|
||||||
ORDER BY a.map
|
ORDER BY a.map
|
||||||
""", [player_id]) or []
|
""", [LIKE_PC, player_id]) or []
|
||||||
except Exception:
|
except Exception:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""RMQ service - RabbitMQ Management HTTP API client."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import base64
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RmqService:
|
||||||
|
"""RabbitMQ Management HTTP API client.
|
||||||
|
|
||||||
|
Communicates with RMQ Admin (port 30325) and RMQ Game (port 32716)
|
||||||
|
HTTP API endpoints via SSH tunnel (localhost).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, admin_port: int = 30325, game_port: int = 32716,
|
||||||
|
username: str = 'dashboard_admin', password: str = ''):
|
||||||
|
self.admin_port = admin_port
|
||||||
|
self.game_port = game_port
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self._auth = base64.b64encode(
|
||||||
|
f"{username}:{password}".encode()).decode()
|
||||||
|
logger.info("RmqService initialized: admin=localhost:%s game=localhost:%s",
|
||||||
|
admin_port, game_port)
|
||||||
|
|
||||||
|
def _request(self, port: int, path: str, method: str = 'GET',
|
||||||
|
body: Any = None, timeout: int = 15) -> Optional[Any]:
|
||||||
|
"""Execute an HTTP request against an RMQ API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
port: Tunnel port (30325 for admin, 32716 for game).
|
||||||
|
path: API path (e.g., '/api/overview').
|
||||||
|
method: HTTP method.
|
||||||
|
body: Optional JSON-serializable request body.
|
||||||
|
timeout: Request timeout in seconds.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Parsed JSON response, or None on failure.
|
||||||
|
"""
|
||||||
|
url = f"http://127.0.0.1:{port}{path}"
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Basic {self._auth}',
|
||||||
|
}
|
||||||
|
if body is not None:
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
data = json.dumps(body).encode()
|
||||||
|
else:
|
||||||
|
data = None
|
||||||
|
|
||||||
|
req = urllib.request.Request(url, data=data, headers=headers)
|
||||||
|
|
||||||
|
if method != 'GET' and method != 'POST':
|
||||||
|
req.method = method
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
raw = resp.read().decode()
|
||||||
|
return json.loads(raw) if raw.strip() else {}
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("RMQ HTTP %s %s -> %s: %s", method, url, e.code,
|
||||||
|
e.read().decode()[:200] if e.fp else '')
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("RMQ request error %s %s: %s", method, url, e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _encode_vhost(vhost: str = '/') -> str:
|
||||||
|
return vhost.replace('/', '%2F')
|
||||||
|
|
||||||
|
# ── Admin API (port 30325) ───────────────────────────────────────
|
||||||
|
|
||||||
|
def overview(self) -> Optional[Dict]:
|
||||||
|
"""Cluster overview: node info, message stats, queue totals."""
|
||||||
|
return self._request(self.admin_port, '/api/overview')
|
||||||
|
|
||||||
|
def nodes(self) -> Optional[List]:
|
||||||
|
"""List nodes with memory and disk info."""
|
||||||
|
return self._request(self.admin_port, '/api/nodes')
|
||||||
|
|
||||||
|
def exchanges(self) -> Optional[List]:
|
||||||
|
"""List all exchanges with message stats."""
|
||||||
|
return self._request(self.admin_port, '/api/exchanges')
|
||||||
|
|
||||||
|
def queues(self) -> Optional[List]:
|
||||||
|
"""List all queues with consumer counts and message depths."""
|
||||||
|
return self._request(self.admin_port, '/api/queues')
|
||||||
|
|
||||||
|
def bindings(self) -> Optional[List]:
|
||||||
|
"""List all bindings (source -> destination mappings)."""
|
||||||
|
return self._request(self.admin_port, '/api/bindings')
|
||||||
|
|
||||||
|
def consumers(self) -> Optional[List]:
|
||||||
|
"""List active consumers."""
|
||||||
|
return self._request(self.admin_port, '/api/consumers')
|
||||||
|
|
||||||
|
def connections(self) -> Optional[List]:
|
||||||
|
"""List active AMQP connections."""
|
||||||
|
return self._request(self.admin_port, '/api/connections')
|
||||||
|
|
||||||
|
def channels(self) -> Optional[List]:
|
||||||
|
"""List active channels."""
|
||||||
|
return self._request(self.admin_port, '/api/channels')
|
||||||
|
|
||||||
|
def health(self) -> Optional[Dict]:
|
||||||
|
"""Cluster health and alarm status."""
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
'/api/health/checks/alarms')
|
||||||
|
|
||||||
|
def peek_messages(self, queue_name: str, vhost: str = '/',
|
||||||
|
count: int = 5) -> Optional[List]:
|
||||||
|
"""Peek at messages in a queue without consuming them."""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'count': count,
|
||||||
|
'ackmode': 'ack_requeue_true',
|
||||||
|
'encoding': 'auto',
|
||||||
|
}
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/queues/{vh}/{queue_name}/get',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
def publish(self, exchange: str, routing_key: str, message: Any,
|
||||||
|
vhost: str = '/') -> Optional[Dict]:
|
||||||
|
"""Publish a message to an exchange.
|
||||||
|
|
||||||
|
NOTE: RMQ HTTP API sets user_id to the authenticated username,
|
||||||
|
which the game server may reject. For ServerCommands on the
|
||||||
|
game RPC exchange, use the Erlang eval approach instead.
|
||||||
|
"""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'properties': {},
|
||||||
|
'routing_key': routing_key,
|
||||||
|
'payload': json.dumps(message) if not isinstance(message, str)
|
||||||
|
else message,
|
||||||
|
'payload_encoding': 'string',
|
||||||
|
}
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/publish',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
def get_queue_bindings(self, queue_name: str,
|
||||||
|
vhost: str = '/') -> Optional[List]:
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/queues/{vh}/{queue_name}/bindings')
|
||||||
|
|
||||||
|
def get_exchange_bindings(self, exchange: str,
|
||||||
|
vhost: str = '/') -> Optional[List]:
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/bindings/source')
|
||||||
|
|
||||||
|
# ── Game API (port 32716) ────────────────────────────────────────
|
||||||
|
|
||||||
|
def game_overview(self) -> Optional[Dict]:
|
||||||
|
"""Game RMQ cluster overview."""
|
||||||
|
return self._request(self.game_port, '/api/overview')
|
||||||
|
|
||||||
|
def game_queues(self) -> Optional[List]:
|
||||||
|
"""Game RMQ queues."""
|
||||||
|
return self._request(self.game_port, '/api/queues')
|
||||||
|
|
||||||
|
def game_exchanges(self) -> Optional[List]:
|
||||||
|
"""Game RMQ exchanges."""
|
||||||
|
return self._request(self.game_port, '/api/exchanges')
|
||||||
|
|
||||||
|
def game_publish(self, exchange: str, routing_key: str,
|
||||||
|
message: Any, vhost: str = '/') -> Optional[Dict]:
|
||||||
|
"""Publish a message to the game RMQ."""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'properties': {},
|
||||||
|
'routing_key': routing_key,
|
||||||
|
'payload': json.dumps(message) if not isinstance(message, str)
|
||||||
|
else message,
|
||||||
|
'payload_encoding': 'string',
|
||||||
|
}
|
||||||
|
return self._request(self.game_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/publish',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
# ── Combined / convenience ───────────────────────────────────────
|
||||||
|
|
||||||
|
def combined_overview(self) -> Dict[str, Any]:
|
||||||
|
"""Get overview from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.overview(),
|
||||||
|
'game': self.game_overview(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def combined_queues(self) -> Dict[str, Any]:
|
||||||
|
"""Get queues from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.queues(),
|
||||||
|
'game': self.game_queues(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def combined_exchanges(self) -> Dict[str, Any]:
|
||||||
|
"""Get exchanges from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.exchanges(),
|
||||||
|
'game': self.game_exchanges(),
|
||||||
|
}
|
||||||
@@ -81,5 +81,5 @@ NAV_PAGES = [
|
|||||||
('/guilds', 'Guilds'),
|
('/guilds', 'Guilds'),
|
||||||
('/buildings', 'Buildings'),
|
('/buildings', 'Buildings'),
|
||||||
('/map', 'Map'),
|
('/map', 'Map'),
|
||||||
('/admin-experimental', 'Admin Experimental'),
|
('/admin-experimental', 'Experimental'),
|
||||||
]
|
]
|
||||||
+6
-1
@@ -108,7 +108,12 @@ def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
|
|||||||
])
|
])
|
||||||
|
|
||||||
# Build SAN entries
|
# Build SAN entries
|
||||||
san_entries = [x509.DNSName(common_name)]
|
san_entries = []
|
||||||
|
# Add common_name as the appropriate SAN type
|
||||||
|
try:
|
||||||
|
san_entries.append(x509.IPAddress(ipaddress.ip_address(common_name)))
|
||||||
|
except ValueError:
|
||||||
|
san_entries.append(x509.DNSName(common_name))
|
||||||
if san_ips:
|
if san_ips:
|
||||||
for ip in san_ips:
|
for ip in san_ips:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ DEFAULTS = {
|
|||||||
"max_connections": 10,
|
"max_connections": 10,
|
||||||
"owner": "dune",
|
"owner": "dune",
|
||||||
"dashboard_schema": "dashboard",
|
"dashboard_schema": "dashboard",
|
||||||
|
"dashboard_database_name": "dashboard",
|
||||||
},
|
},
|
||||||
"kubernetes": {
|
"kubernetes": {
|
||||||
"namespace": "",
|
"namespace": "",
|
||||||
|
|||||||
+20
-5
@@ -24,7 +24,7 @@ from app.routes.debug import debug_bp
|
|||||||
from app.routes.chat import chat_bp
|
from app.routes.chat import chat_bp
|
||||||
from app.websocket.shell import register_websocket_handlers
|
from app.websocket.shell import register_websocket_handlers
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
from app.services.database import DatabaseService, DashboardDatabaseService
|
||||||
from app.services.ssh import SSHService
|
from app.services.ssh import SSHService
|
||||||
from app.services.k8s import K8sService
|
from app.services.k8s import K8sService
|
||||||
from app.services.bg_director import BgDirectorService
|
from app.services.bg_director import BgDirectorService
|
||||||
@@ -156,13 +156,27 @@ def create_app(settings_path=None):
|
|||||||
"database": settings["database"]["name"],
|
"database": settings["database"]["name"],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dash_db_config = {
|
||||||
|
"host": settings["database"]["host"],
|
||||||
|
"port": settings["database"]["port"],
|
||||||
|
"user": settings["database"]["user"],
|
||||||
|
"password": settings["database"]["password"],
|
||||||
|
"database": settings["database"].get("dashboard_database_name", "dashboard"),
|
||||||
|
}
|
||||||
|
|
||||||
db_service = DatabaseService(
|
db_service = DatabaseService(
|
||||||
db_config,
|
db_config,
|
||||||
min_conn=settings["database"]["min_connections"],
|
min_conn=settings["database"]["min_connections"],
|
||||||
max_conn=settings["database"]["max_connections"],
|
max_conn=settings["database"]["max_connections"],
|
||||||
dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"),
|
|
||||||
)
|
)
|
||||||
db_service.ensure_tables()
|
|
||||||
|
dash_db_service = DashboardDatabaseService(
|
||||||
|
dash_db_config,
|
||||||
|
min_conn=settings["database"]["min_connections"],
|
||||||
|
max_conn=settings["database"]["max_connections"],
|
||||||
|
owner=settings["database"].get("owner", "dune"),
|
||||||
|
)
|
||||||
|
dash_db_service.ensure_tables(game_db=db_service)
|
||||||
|
|
||||||
ssh_service = SSHService(
|
ssh_service = SSHService(
|
||||||
host=settings["server"]["host"],
|
host=settings["server"]["host"],
|
||||||
@@ -200,14 +214,15 @@ def create_app(settings_path=None):
|
|||||||
world_svc = WorldService(db_service)
|
world_svc = WorldService(db_service)
|
||||||
progression_svc = ProgressionService(db_service)
|
progression_svc = ProgressionService(db_service)
|
||||||
character_svc = CharacterService(db_service)
|
character_svc = CharacterService(db_service)
|
||||||
audit_svc = AuditService(db_service)
|
audit_svc = AuditService(dash_db_service)
|
||||||
chat_svc = ChatService(db_service, k8s_service, ssh_service)
|
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service)
|
||||||
|
|
||||||
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
|
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
|
||||||
realtime_svc.start()
|
realtime_svc.start()
|
||||||
|
|
||||||
_services = {
|
_services = {
|
||||||
"db": db_service,
|
"db": db_service,
|
||||||
|
"dash_db": dash_db_service,
|
||||||
"ssh": ssh_service,
|
"ssh": ssh_service,
|
||||||
"k8s": k8s_service,
|
"k8s": k8s_service,
|
||||||
"bg_director": bg_director,
|
"bg_director": bg_director,
|
||||||
|
|||||||
+18
-17
@@ -875,8 +875,9 @@ def get_audit_stats():
|
|||||||
@login_required
|
@login_required
|
||||||
def get_settings():
|
def get_settings():
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
settings = get_services()["db"].execute_readonly(
|
dash_db = get_services()["dash_db"]
|
||||||
"SELECT key, value, updated_at FROM dashboard.settings ORDER BY key"
|
settings = dash_db.execute_readonly(
|
||||||
|
"SELECT key, value, updated_at FROM settings ORDER BY key"
|
||||||
)
|
)
|
||||||
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
|
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
|
||||||
|
|
||||||
@@ -891,10 +892,10 @@ def update_settings():
|
|||||||
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
|
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
|
||||||
).model_dump()), 400
|
).model_dump()), 400
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
db = get_services()["db"]
|
dash_db = get_services()["dash_db"]
|
||||||
for key, value in data.items():
|
for key, value in data.items():
|
||||||
db.execute_mutation(
|
dash_db.execute_mutation(
|
||||||
"""INSERT INTO dashboard.settings (key, value, updated_at)
|
"""INSERT INTO settings (key, value, updated_at)
|
||||||
VALUES (%s, %s, NOW())
|
VALUES (%s, %s, NOW())
|
||||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
|
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
|
||||||
[key, str(value)],
|
[key, str(value)],
|
||||||
@@ -912,9 +913,9 @@ def ban_player(player_id):
|
|||||||
reason = data.get("reason", "admin")
|
reason = data.get("reason", "admin")
|
||||||
duration = data.get("duration_hours", 0)
|
duration = data.get("duration_hours", 0)
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
db = get_services()["db"]
|
dash_db = get_services()["dash_db"]
|
||||||
db.execute_mutation(
|
dash_db.execute_mutation(
|
||||||
"""INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active)
|
"""INSERT INTO bans (player_id, reason, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
|
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
|
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
|
||||||
[player_id, reason, duration, duration, duration],
|
[player_id, reason, duration, duration, duration],
|
||||||
@@ -927,9 +928,9 @@ def ban_player(player_id):
|
|||||||
@login_required
|
@login_required
|
||||||
def unban_player(player_id):
|
def unban_player(player_id):
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
db = get_services()["db"]
|
dash_db = get_services()["dash_db"]
|
||||||
db.execute_mutation(
|
dash_db.execute_mutation(
|
||||||
"UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s",
|
"UPDATE bans SET active = FALSE WHERE player_id = %s",
|
||||||
[player_id],
|
[player_id],
|
||||||
)
|
)
|
||||||
_audit("player_unban", {"player_id": player_id})
|
_audit("player_unban", {"player_id": player_id})
|
||||||
@@ -940,9 +941,9 @@ def unban_player(player_id):
|
|||||||
@login_required
|
@login_required
|
||||||
def get_player_ban(player_id):
|
def get_player_ban(player_id):
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
db = get_services()["db"]
|
dash_db = get_services()["dash_db"]
|
||||||
rows = db.execute_readonly(
|
rows = dash_db.execute_readonly(
|
||||||
"SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE",
|
"SELECT * FROM bans WHERE player_id = %s AND active = TRUE",
|
||||||
[player_id],
|
[player_id],
|
||||||
)
|
)
|
||||||
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
|
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
|
||||||
@@ -961,9 +962,9 @@ def kick_player(player_id):
|
|||||||
@login_required
|
@login_required
|
||||||
def get_player_history(player_id):
|
def get_player_history(player_id):
|
||||||
from app.factory import get_services
|
from app.factory import get_services
|
||||||
db = get_services()["db"]
|
dash_db = get_services()["dash_db"]
|
||||||
logs = db.execute_readonly(
|
logs = dash_db.execute_readonly(
|
||||||
"""SELECT * FROM dashboard.audit_log
|
"""SELECT * FROM audit_log
|
||||||
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
|
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
|
||||||
ORDER BY created_at DESC LIMIT 100""",
|
ORDER BY created_at DESC LIMIT 100""",
|
||||||
[player_id, player_id],
|
[player_id, player_id],
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
from app.services.database import DashboardDatabaseService
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AuditService:
|
class AuditService:
|
||||||
def __init__(self, db: DatabaseService):
|
def __init__(self, db: DashboardDatabaseService):
|
||||||
self.db = db
|
self.db = db
|
||||||
|
|
||||||
def log(self, action: str, user: str, details: dict | None = None,
|
def log(self, action: str, user: str, details: dict | None = None,
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
from app.services.database import DashboardDatabaseService
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class ChatService:
|
class ChatService:
|
||||||
def __init__(self, db: DatabaseService, k8s_service, ssh_service):
|
def __init__(self, db: DashboardDatabaseService, k8s_service, ssh_service):
|
||||||
self.db = db
|
self.db = db
|
||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
from typing import Any, List
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
import psycopg
|
import psycopg
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
@@ -12,11 +12,12 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class DatabaseService:
|
class DatabaseService:
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema="dashboard"):
|
"""Service for game database queries (dune schema functions/procedures)."""
|
||||||
|
|
||||||
|
def __init__(self, db_config, min_conn=2, max_conn=10):
|
||||||
self.db_config = db_config
|
self.db_config = db_config
|
||||||
self.min_conn = min_conn
|
self.min_conn = min_conn
|
||||||
self.max_conn = max_conn
|
self.max_conn = max_conn
|
||||||
self.dashboard_schema = dashboard_schema
|
|
||||||
self.pool = None
|
self.pool = None
|
||||||
|
|
||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
@@ -80,7 +81,7 @@ class DatabaseService:
|
|||||||
cur.execute(sql, args)
|
cur.execute(sql, args)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
def execute_readonly(self, sql: str, params: List[Any] | None = None) -> List[dict]:
|
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
|
||||||
"""Execute a read-only SELECT query."""
|
"""Execute a read-only SELECT query."""
|
||||||
pool = self.init_pool()
|
pool = self.init_pool()
|
||||||
if not pool:
|
if not pool:
|
||||||
@@ -92,7 +93,7 @@ class DatabaseService:
|
|||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
return rows if rows else []
|
return rows if rows else []
|
||||||
|
|
||||||
def execute_mutation(self, sql: str, params: List[Any] | None = None) -> int:
|
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
|
||||||
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
|
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
|
||||||
pool = self.init_pool()
|
pool = self.init_pool()
|
||||||
if not pool:
|
if not pool:
|
||||||
@@ -118,38 +119,164 @@ class DatabaseService:
|
|||||||
logger.warning(f"Database health check FAILED: {e}")
|
logger.warning(f"Database health check FAILED: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def ensure_tables(self):
|
def close(self):
|
||||||
"""Ensure dashboard schema tables exist."""
|
if self.pool:
|
||||||
|
try:
|
||||||
|
self.pool.close()
|
||||||
|
logger.info("Database pool closed")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error closing pool: {e}")
|
||||||
|
self.pool = None
|
||||||
|
|
||||||
|
|
||||||
|
class DashboardDatabaseService:
|
||||||
|
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
|
||||||
|
|
||||||
|
def __init__(self, db_config, min_conn=2, max_conn=10, owner="dune"):
|
||||||
|
self.db_config = db_config
|
||||||
|
self.min_conn = min_conn
|
||||||
|
self.max_conn = max_conn
|
||||||
|
self.owner = owner
|
||||||
|
self.pool = None
|
||||||
|
self._migrated = False
|
||||||
|
|
||||||
|
def _conninfo(self, dbname=None):
|
||||||
|
return (
|
||||||
|
f"host={self.db_config['host']} "
|
||||||
|
f"port={self.db_config['port']} "
|
||||||
|
f"dbname={dbname or self.db_config['database']} "
|
||||||
|
f"user={self.db_config['user']} "
|
||||||
|
f"password={self.db_config['password']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _temp_connection(self, dbname="postgres"):
|
||||||
|
"""Get a temporary single connection (for database creation)."""
|
||||||
|
conn = psycopg.connect(self._conninfo(dbname))
|
||||||
|
conn.autocommit = True
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def init_pool(self):
|
||||||
|
if self.pool is not None:
|
||||||
|
return self.pool
|
||||||
|
|
||||||
|
conninfo = self._conninfo()
|
||||||
|
|
||||||
|
for attempt in range(10):
|
||||||
|
try:
|
||||||
|
self.pool = ConnectionPool(
|
||||||
|
conninfo=conninfo,
|
||||||
|
min_size=self.min_conn,
|
||||||
|
max_size=self.max_conn,
|
||||||
|
open=False,
|
||||||
|
)
|
||||||
|
self.pool.open(wait=True, timeout=20)
|
||||||
|
logger.info("Dashboard database pool initialized")
|
||||||
|
return self.pool
|
||||||
|
except psycopg.errors.OperationalError as e:
|
||||||
|
if "does not exist" in str(e) and attempt == 0:
|
||||||
|
logger.info("Dashboard database does not exist, creating...")
|
||||||
|
self._ensure_database()
|
||||||
|
continue
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
except Exception as e:
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
return self.pool
|
||||||
|
|
||||||
|
def _ensure_database(self):
|
||||||
|
"""Create the dashboard database if it doesn't exist."""
|
||||||
|
try:
|
||||||
|
conn = self._temp_connection("postgres")
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT 1 FROM pg_database WHERE datname = %s",
|
||||||
|
[self.db_config["database"]],
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute(
|
||||||
|
f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}"
|
||||||
|
)
|
||||||
|
logger.info("Created dashboard database '%s'", self.db_config["database"])
|
||||||
|
else:
|
||||||
|
logger.debug("Dashboard database already exists")
|
||||||
|
conn.close()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to create dashboard database: %s", e)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _migrate_old_schema(self, game_db):
|
||||||
|
"""Migrate data from old dashboard schema in the game database."""
|
||||||
|
if self._migrated:
|
||||||
|
return
|
||||||
|
|
||||||
|
tables = ["settings", "bans", "player_ips", "player_actions", "audit_log", "chat_history"]
|
||||||
|
migrated = False
|
||||||
|
|
||||||
|
for table in tables:
|
||||||
|
try:
|
||||||
|
rows = game_db.execute_readonly(
|
||||||
|
f"SELECT count(*) as cnt FROM dashboard.{table}"
|
||||||
|
)
|
||||||
|
if rows and rows[0]["cnt"] > 0:
|
||||||
|
logger.info("Migrating %d rows from dashboard.%s", rows[0]["cnt"], table)
|
||||||
|
old_rows = game_db.execute_readonly(f"SELECT * FROM dashboard.{table}")
|
||||||
|
if old_rows:
|
||||||
|
cols = list(old_rows[0].keys())
|
||||||
|
placeholders = ",".join([f"%s"] * len(cols))
|
||||||
|
col_names = ",".join(cols)
|
||||||
|
for row in old_rows:
|
||||||
|
vals = [row[c] for c in cols]
|
||||||
|
self.execute_mutation(
|
||||||
|
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders})",
|
||||||
|
vals,
|
||||||
|
)
|
||||||
|
migrated = True
|
||||||
|
logger.info("Migrated dashboard.%s → %s (%d rows)", table, table, rows[0]["cnt"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
|
||||||
|
|
||||||
|
if migrated:
|
||||||
|
logger.info("Data migration from old dashboard schema complete")
|
||||||
|
self._migrated = True
|
||||||
|
|
||||||
|
def ensure_tables(self, game_db=None):
|
||||||
|
"""Ensure tables exist in the dashboard database and migrate if needed."""
|
||||||
pool = self.init_pool()
|
pool = self.init_pool()
|
||||||
if not pool:
|
if not pool:
|
||||||
return
|
return
|
||||||
|
|
||||||
schema = self.dashboard_schema
|
ddl = """
|
||||||
ddl = f"""
|
CREATE TABLE IF NOT EXISTS audit_log (
|
||||||
CREATE SCHEMA IF NOT EXISTS {schema};
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.audit_log (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
action_type VARCHAR(50) NOT NULL,
|
action_type VARCHAR(50) NOT NULL,
|
||||||
user_name VARCHAR(100) NOT NULL,
|
user_name VARCHAR(100) NOT NULL,
|
||||||
target_player_id BIGINT,
|
target_player_id BIGINT,
|
||||||
details JSONB DEFAULT '{{}}',
|
details JSONB DEFAULT '{}',
|
||||||
source_ip INET,
|
source_ip INET,
|
||||||
severity VARCHAR(20) DEFAULT 'info',
|
severity VARCHAR(20) DEFAULT 'info',
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON {schema}.audit_log (created_at DESC);
|
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON audit_log (created_at DESC);
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_action ON {schema}.audit_log (action_type);
|
CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log (action_type);
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_user ON {schema}.audit_log (user_name);
|
CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log (user_name);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
|
CREATE TABLE IF NOT EXISTS player_ips (
|
||||||
player_id BIGINT PRIMARY KEY,
|
player_id BIGINT PRIMARY KEY,
|
||||||
ip_address INET NOT NULL,
|
ip_address INET NOT NULL,
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.bans (
|
CREATE TABLE IF NOT EXISTS bans (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT UNIQUE,
|
player_id BIGINT UNIQUE,
|
||||||
account_id BIGINT,
|
account_id BIGINT,
|
||||||
@@ -161,7 +288,7 @@ class DatabaseService:
|
|||||||
active BOOLEAN DEFAULT TRUE
|
active BOOLEAN DEFAULT TRUE
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
|
CREATE TABLE IF NOT EXISTS player_actions (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT NOT NULL,
|
player_id BIGINT NOT NULL,
|
||||||
action_type VARCHAR(50) NOT NULL,
|
action_type VARCHAR(50) NOT NULL,
|
||||||
@@ -172,7 +299,7 @@ class DatabaseService:
|
|||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.chat_history (
|
CREATE TABLE IF NOT EXISTS chat_history (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
timestamp TIMESTAMP DEFAULT NOW(),
|
||||||
channel VARCHAR(50),
|
channel VARCHAR(50),
|
||||||
@@ -185,9 +312,9 @@ class DatabaseService:
|
|||||||
is_admin BOOLEAN DEFAULT FALSE
|
is_admin BOOLEAN DEFAULT FALSE
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON {schema}.chat_history (timestamp DESC);
|
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.settings (
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
key VARCHAR(255) PRIMARY KEY,
|
key VARCHAR(255) PRIMARY KEY,
|
||||||
value TEXT DEFAULT '',
|
value TEXT DEFAULT '',
|
||||||
updated_at TIMESTAMP DEFAULT NOW()
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
@@ -197,14 +324,77 @@ class DatabaseService:
|
|||||||
with pool.connection() as conn:
|
with pool.connection() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
cur.execute(ddl)
|
cur.execute(ddl)
|
||||||
|
|
||||||
|
owner = self.owner
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
logger.info(f"Dashboard tables ensured in schema '{schema}'")
|
|
||||||
|
logger.info("Dashboard tables ensured, owner=%s", owner)
|
||||||
|
|
||||||
|
if game_db is not None:
|
||||||
|
self._migrate_old_schema(game_db)
|
||||||
|
|
||||||
|
def execute_readonly(self, sql: str, params: Optional[List[Any]] = None) -> List[dict]:
|
||||||
|
pool = self.init_pool()
|
||||||
|
if not pool:
|
||||||
|
raise ConnectionError("Dashboard database pool not available")
|
||||||
|
|
||||||
|
with pool.connection() as conn:
|
||||||
|
with conn.cursor(row_factory=dict_row) as cur:
|
||||||
|
cur.execute(sql, params or [])
|
||||||
|
rows = cur.fetchall()
|
||||||
|
return rows if rows else []
|
||||||
|
|
||||||
|
def execute_mutation(self, sql: str, params: Optional[List[Any]] = None) -> int:
|
||||||
|
pool = self.init_pool()
|
||||||
|
if not pool:
|
||||||
|
raise ConnectionError("Dashboard database pool not available")
|
||||||
|
|
||||||
|
with pool.connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(sql, params or [])
|
||||||
|
conn.commit()
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
def health_check(self) -> bool:
|
||||||
|
try:
|
||||||
|
pool = self.init_pool()
|
||||||
|
if not pool:
|
||||||
|
return False
|
||||||
|
with pool.connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT 1")
|
||||||
|
cur.fetchone()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Dashboard database health check FAILED: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
if self.pool:
|
if self.pool:
|
||||||
try:
|
try:
|
||||||
self.pool.close()
|
self.pool.close()
|
||||||
logger.info("Database pool closed")
|
logger.info("Dashboard database pool closed")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error closing pool: {e}")
|
logger.error("Error closing dashboard pool: %s", e)
|
||||||
self.pool = None
|
self.pool = None
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
@@ -93,7 +94,7 @@ class RmqGameService:
|
|||||||
}
|
}
|
||||||
body = {
|
body = {
|
||||||
"Version": 2,
|
"Version": 2,
|
||||||
"AuthToken": "Nu6VmPWUMvdPMeB7qErr",
|
"AuthToken": os.environ.get("DUNE_BROADCAST_TOKEN", "Nu6VmPWUMvdPMeB7qErr"),
|
||||||
"MessageContent": inner,
|
"MessageContent": inner,
|
||||||
}
|
}
|
||||||
return self.publish(
|
return self.publish(
|
||||||
|
|||||||
+272
-18
@@ -302,10 +302,19 @@ function Show-Menu {
|
|||||||
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
|
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
|
||||||
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
|
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
|
||||||
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
|
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
|
||||||
|
Write-Host " NOTE: Not complete. Do not report bugs. May not even work." -ForegroundColor DarkGray
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " [8] Reset to Factory Defaults" -ForegroundColor Red
|
Write-Host " [8] Reset to Factory Defaults" -ForegroundColor Red
|
||||||
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
|
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
Write-Host " [9] Repair Game Database" -ForegroundColor Yellow
|
||||||
|
Write-Host " Fixes dashboard schema ownership so game updates won't break." -ForegroundColor DarkGray
|
||||||
|
Write-Host " Run this if game servers fail to start after an update." -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [10] Clean up Old Dashboard Schema" -ForegroundColor Red
|
||||||
|
Write-Host " Drops the old dashboard schema from the game database." -ForegroundColor DarkGray
|
||||||
|
Write-Host " Only run after confirming dashboard migrated successfully." -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
Write-Host " [Q] Quit" -ForegroundColor White
|
Write-Host " [Q] Quit" -ForegroundColor White
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
}
|
}
|
||||||
@@ -1526,6 +1535,9 @@ function Run-Setup {
|
|||||||
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
|
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
|
||||||
$CertDir = Join-Path $ProjectRoot "ssl"
|
$CertDir = Join-Path $ProjectRoot "ssl"
|
||||||
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
|
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
|
||||||
|
$LeConfigDir = Join-Path $ProjectRoot "certbot\config"
|
||||||
|
$LeWorkDir = Join-Path $ProjectRoot "certbot\work"
|
||||||
|
$LeLogsDir = Join-Path $ProjectRoot "certbot\logs"
|
||||||
$CaCertPath = Join-Path $CertDir "ca.pem"
|
$CaCertPath = Join-Path $CertDir "ca.pem"
|
||||||
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
|
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
|
||||||
$SslCertPath = Join-Path $CertDir "cert.pem"
|
$SslCertPath = Join-Path $CertDir "cert.pem"
|
||||||
@@ -1572,8 +1584,14 @@ function Run-Setup {
|
|||||||
|
|
||||||
$certbotUseModule = ($certbotCmd.Source -eq "python")
|
$certbotUseModule = ($certbotCmd.Source -eq "python")
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Path $LeConfigDir -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path $LeWorkDir -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path $LeLogsDir -Force | Out-Null
|
||||||
|
|
||||||
|
$certbotDirArgs = @("--config-dir", $LeConfigDir, "--work-dir", $LeWorkDir, "--logs-dir", $LeLogsDir)
|
||||||
|
|
||||||
if ($certbotUseModule) {
|
if ($certbotUseModule) {
|
||||||
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos")
|
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + $certbotDirArgs
|
||||||
if ($LeEmail) {
|
if ($LeEmail) {
|
||||||
$certbotArgs += "--email"
|
$certbotArgs += "--email"
|
||||||
$certbotArgs += $LeEmail
|
$certbotArgs += $LeEmail
|
||||||
@@ -1587,7 +1605,7 @@ function Run-Setup {
|
|||||||
"-d", $DomainName,
|
"-d", $DomainName,
|
||||||
"--non-interactive",
|
"--non-interactive",
|
||||||
"--agree-tos"
|
"--agree-tos"
|
||||||
)
|
) + $certbotDirArgs
|
||||||
if ($LeEmail) {
|
if ($LeEmail) {
|
||||||
$certbotArgs += "--email"
|
$certbotArgs += "--email"
|
||||||
$certbotArgs += $LeEmail
|
$certbotArgs += $LeEmail
|
||||||
@@ -1600,13 +1618,9 @@ function Run-Setup {
|
|||||||
|
|
||||||
if ($certbotResult.ExitCode -eq 0) {
|
if ($certbotResult.ExitCode -eq 0) {
|
||||||
$UseLetsEncrypt = $true
|
$UseLetsEncrypt = $true
|
||||||
$LeCertPath = "C:\ProgramData\certbot\live\$DomainName\fullchain.pem"
|
$LeLiveDir = Join-Path $LeConfigDir "live\$DomainName"
|
||||||
$LeKeyPath = "C:\ProgramData\certbot\live\$DomainName\privkey.pem"
|
$LeCertPath = Join-Path $LeLiveDir "fullchain.pem"
|
||||||
|
$LeKeyPath = Join-Path $LeLiveDir "privkey.pem"
|
||||||
if (-not (Test-Path $LeCertPath)) {
|
|
||||||
$LeCertPath = "C:\Certbot\live\$DomainName\fullchain.pem"
|
|
||||||
$LeKeyPath = "C:\Certbot\live\$DomainName\privkey.pem"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Test-Path $LeCertPath) {
|
if (Test-Path $LeCertPath) {
|
||||||
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
|
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
|
||||||
@@ -1645,8 +1659,11 @@ function Run-Setup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
|
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
|
||||||
|
$SanDnsArray = "['localhost'"
|
||||||
|
if ($DomainName) { $SanDnsArray += ", '" + $DomainName + "'" }
|
||||||
|
$SanDnsArray += "]"
|
||||||
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
|
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
|
||||||
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=['localhost'])"
|
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=$SanDnsArray)"
|
||||||
$SslCert = "'$SslCertPath'"
|
$SslCert = "'$SslCertPath'"
|
||||||
$SslKey = "'$SslKeyPath'"
|
$SslKey = "'$SslKeyPath'"
|
||||||
|
|
||||||
@@ -1778,7 +1795,7 @@ function Run-Setup {
|
|||||||
$certbotPath = "certbot"
|
$certbotPath = "certbot"
|
||||||
}
|
}
|
||||||
|
|
||||||
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet"
|
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet --config-dir `"$LeConfigDir`" --work-dir `"$LeWorkDir`" --logs-dir `"$LeLogsDir`""
|
||||||
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
|
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
|
||||||
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||||
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
|
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
|
||||||
@@ -2052,6 +2069,10 @@ function Start-Dashboard {
|
|||||||
$Namespace = $settings.kubernetes.namespace
|
$Namespace = $settings.kubernetes.namespace
|
||||||
$DashboardPort = [int]$settings.dashboard.port
|
$DashboardPort = [int]$settings.dashboard.port
|
||||||
$DirectorPort = [int]$settings.director.port
|
$DirectorPort = [int]$settings.director.port
|
||||||
|
$RmqAdminPort = [int]($settings.rabbitmq | ForEach-Object { $_.admin_port })
|
||||||
|
if (-not $RmqAdminPort) { $RmqAdminPort = 30325 }
|
||||||
|
$RmqGamePort = [int]($settings.rabbitmq | ForEach-Object { $_.game_port })
|
||||||
|
if (-not $RmqGamePort) { $RmqGamePort = 32716 }
|
||||||
|
|
||||||
# Register sensitive values for log sanitization
|
# Register sensitive values for log sanitization
|
||||||
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
||||||
@@ -2156,13 +2177,19 @@ function Start-Dashboard {
|
|||||||
Write-Log -Message "Namespace: $Namespace" -Category "k8s"
|
Write-Log -Message "Namespace: $Namespace" -Category "k8s"
|
||||||
|
|
||||||
# Kill existing SSH tunnels on the DB/Director ports
|
# Kill existing SSH tunnels on the DB/Director ports
|
||||||
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort and $DirectorPort" -Category "ssh"
|
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort, $DirectorPort, $RmqAdminPort, $RmqGamePort" -Category "ssh"
|
||||||
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqAdminPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqGamePort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
Start-Sleep 1
|
Start-Sleep 1
|
||||||
|
|
||||||
# [1/4] SSH Tunnel
|
# [1/4] SSH Tunnel
|
||||||
@@ -2176,6 +2203,8 @@ function Start-Dashboard {
|
|||||||
"-o", "ServerAliveCountMax=3",
|
"-o", "ServerAliveCountMax=3",
|
||||||
"-L", "${LocalPort}:localhost:${LocalPort}",
|
"-L", "${LocalPort}:localhost:${LocalPort}",
|
||||||
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
||||||
|
"-L", "${RmqAdminPort}:localhost:${RmqAdminPort}",
|
||||||
|
"-L", "${RmqGamePort}:localhost:${RmqGamePort}",
|
||||||
"-N", "${SSHUser}@${ServerHost}"
|
"-N", "${SSHUser}@${ServerHost}"
|
||||||
)
|
)
|
||||||
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
||||||
@@ -2220,7 +2249,7 @@ function Start-Dashboard {
|
|||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director)" -ForegroundColor Green
|
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director), localhost:$RmqAdminPort (RMQ Admin), localhost:$RmqGamePort (RMQ Game)" -ForegroundColor Green
|
||||||
Write-Log -Message "SSH tunnel connected successfully" -Category "ssh"
|
Write-Log -Message "SSH tunnel connected successfully" -Category "ssh"
|
||||||
|
|
||||||
# [2/4] DB Port-Forward
|
# [2/4] DB Port-Forward
|
||||||
@@ -2432,7 +2461,7 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k 15433/tcp 32479/tcp 2>/dev/null"'
|
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k 15433/tcp 32479/tcp 30325/tcp 32716/tcp 2>/dev/null"'
|
||||||
cmd /c $pkillCmd 2>$null
|
cmd /c $pkillCmd 2>$null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2583,6 +2612,10 @@ function Start-NewDashboard {
|
|||||||
$Namespace = $settings.kubernetes.namespace
|
$Namespace = $settings.kubernetes.namespace
|
||||||
$DashboardPort = [int]$settings.dashboard.port
|
$DashboardPort = [int]$settings.dashboard.port
|
||||||
$DirectorPort = [int]$settings.director.port
|
$DirectorPort = [int]$settings.director.port
|
||||||
|
$RmqAdminPort = [int]($settings.rabbitmq | ForEach-Object { $_.admin_port })
|
||||||
|
if (-not $RmqAdminPort) { $RmqAdminPort = 30325 }
|
||||||
|
$RmqGamePort = [int]($settings.rabbitmq | ForEach-Object { $_.game_port })
|
||||||
|
if (-not $RmqGamePort) { $RmqGamePort = 32716 }
|
||||||
|
|
||||||
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
||||||
Register-SensitiveValue -Key "Namespace" -Value $Namespace
|
Register-SensitiveValue -Key "Namespace" -Value $Namespace
|
||||||
@@ -2661,6 +2694,21 @@ function Start-NewDashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# ── SSH Tunnel ────────────────────────────────────────────────────────
|
# ── SSH Tunnel ────────────────────────────────────────────────────────
|
||||||
|
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort, $DirectorPort, $RmqAdminPort, $RmqGamePort" -Category "ssh"
|
||||||
|
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqAdminPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqGamePort -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/5] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
|
Write-Host "[1/5] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
|
||||||
|
|
||||||
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
@@ -2678,6 +2726,8 @@ function Start-NewDashboard {
|
|||||||
"-o", "ServerAliveCountMax=3",
|
"-o", "ServerAliveCountMax=3",
|
||||||
"-L", "${LocalPort}:localhost:${LocalPort}",
|
"-L", "${LocalPort}:localhost:${LocalPort}",
|
||||||
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
||||||
|
"-L", "${RmqAdminPort}:localhost:${RmqAdminPort}",
|
||||||
|
"-L", "${RmqGamePort}:localhost:${RmqGamePort}",
|
||||||
"-N", "${SSHUser}@${ServerHost}"
|
"-N", "${SSHUser}@${ServerHost}"
|
||||||
)
|
)
|
||||||
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
||||||
@@ -2703,7 +2753,7 @@ function Start-NewDashboard {
|
|||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green
|
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director), localhost:$RmqAdminPort (RMQ Admin), localhost:$RmqGamePort (RMQ Game)" -ForegroundColor Green
|
||||||
|
|
||||||
# ── DB Port-Forward ───────────────────────────────────────────────────
|
# ── DB Port-Forward ───────────────────────────────────────────────────
|
||||||
Write-Host "[2/5] Starting DB port-forward on VM..." -ForegroundColor Yellow
|
Write-Host "[2/5] Starting DB port-forward on VM..." -ForegroundColor Yellow
|
||||||
@@ -2722,7 +2772,7 @@ function Start-NewDashboard {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$RemotePort = 15432
|
$RemotePort = 15432
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
|
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp ${RmqAdminPort}/tcp ${RmqGamePort}/tcp 2>/dev/null; sleep 1" 2>$null
|
||||||
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
|
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
|
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
|
||||||
Start-Sleep -Seconds 2
|
Start-Sleep -Seconds 2
|
||||||
@@ -2866,12 +2916,214 @@ function Start-NewDashboard {
|
|||||||
Stop-Process -Id $frontendProcess.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $frontendProcess.Id -Force -ErrorAction SilentlyContinue
|
||||||
Stop-Process -Id $backendProcess.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $backendProcess.Id -Force -ErrorAction SilentlyContinue
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k ' + $LocalPort + '/tcp ' + $DirectorPort + '/tcp 2>/dev/null"'
|
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k ' + $LocalPort + '/tcp ' + $DirectorPort + '/tcp ' + $RmqAdminPort + '/tcp ' + $RmqGamePort + '/tcp 2>/dev/null"'
|
||||||
cmd /c $pkillCmd 2>$null
|
cmd /c $pkillCmd 2>$null
|
||||||
Write-Host " All services stopped." -ForegroundColor Green
|
Write-Host " All services stopped." -ForegroundColor Green
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Repair-GameDatabase {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Game Database Repair" -ForegroundColor Cyan
|
||||||
|
Write-Host " =====================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
|
||||||
|
if (-not (Test-Path $settingsFile)) {
|
||||||
|
Write-Host "[ERROR] settings.yaml not found. Run setup first (option 2)." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
|
||||||
|
if (-not $settingsJson) {
|
||||||
|
Write-Host "[ERROR] Could not read settings.yaml." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
$settings = $settingsJson | ConvertFrom-Json
|
||||||
|
|
||||||
|
$ServerHost = $settings.server.host
|
||||||
|
$SSHUser = $settings.server.user
|
||||||
|
$Namespace = $settings.kubernetes.namespace
|
||||||
|
|
||||||
|
$SSHKey = $null
|
||||||
|
if ($settings.server.ssh_key -and $settings.server.ssh_key -ne 'null') {
|
||||||
|
$SSHKey = $settings.server.ssh_key
|
||||||
|
}
|
||||||
|
if (-not $SSHKey) {
|
||||||
|
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP') {
|
||||||
|
Write-Host "[ERROR] Server IP not configured in settings.yaml." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (-not $Namespace) {
|
||||||
|
Write-Host "[ERROR] Kubernetes namespace not configured." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (-not (Test-Path $SSHKey)) {
|
||||||
|
Write-Host "[ERROR] SSH key not found at: $SSHKey" -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host " Server: $ServerHost" -ForegroundColor White
|
||||||
|
Write-Host " Namespace: $Namespace" -ForegroundColor White
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$confirm = Read-Host " This will transfer dashboard schema ownership to the dune user. Continue? (y/N)"
|
||||||
|
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# 1. Find the database pod
|
||||||
|
Write-Host "[1/4] Finding database pod..." -ForegroundColor Yellow
|
||||||
|
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
|
||||||
|
if (-not $dbPod) {
|
||||||
|
Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write-Host " [OK] Database pod: $dbPod" -ForegroundColor Green
|
||||||
|
|
||||||
|
# 2. Run the ownership fix SQL
|
||||||
|
Write-Host "[2/4] Running ownership fix..." -ForegroundColor Yellow
|
||||||
|
|
||||||
|
# Build a temp .ps1 script where each line uses --% with values directly embedded.
|
||||||
|
# After --%, PowerShell passes everything literally to ssh.exe — no parsing issues.
|
||||||
|
$tmpFile = Join-Path $env:TEMP "dune_repair_$([System.IO.Path]::GetRandomFileName()).ps1"
|
||||||
|
$sshBase = "ssh --% -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -i `"$SSHKey`" `"$SSHUser@$ServerHost`""
|
||||||
|
|
||||||
|
$scriptLines = @(
|
||||||
|
"$sshBase `"printf 'ALTER SCHEMA dashboard OWNER TO dune;\n' > /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER TABLE dashboard.\x27 || quote_ident(r.tablename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER SEQUENCE dashboard.\x27 || quote_ident(r.sequencename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON TABLES TO dune;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON SEQUENCES TO dune;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"cat /tmp/repair.sql | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune`""
|
||||||
|
"$sshBase `"printf 'CREATE SCHEMA IF NOT EXISTS dashboard;\nGRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;\n' | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d template1`""
|
||||||
|
)
|
||||||
|
|
||||||
|
$scriptLines | Out-File -FilePath $tmpFile -Encoding ASCII
|
||||||
|
|
||||||
|
$sqlResult = powershell -NoProfile -File $tmpFile 2>&1
|
||||||
|
Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue
|
||||||
|
Write-Host " $sqlResult" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Ownership fix applied" -ForegroundColor Green
|
||||||
|
|
||||||
|
# 3. Delete failed util pods
|
||||||
|
Write-Host "[3/4] Cleaning up failed utility pods..." -ForegroundColor Yellow
|
||||||
|
$deleted = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace | grep 'db.*util' | grep -v Running | awk '{print \$1}' | xargs -r sudo kubectl delete pod -n $Namespace --wait=false" 2>$null
|
||||||
|
if ($deleted) {
|
||||||
|
Write-Host " $deleted" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Failed util pods deleted" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host " [OK] No failed util pods found" -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
# 4. Instructions
|
||||||
|
Write-Host "[4/4] Done!" -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================================" -ForegroundColor Cyan
|
||||||
|
Write-Host " Repair Complete!" -ForegroundColor Green
|
||||||
|
Write-Host "============================================================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " If game servers still show errors, restart the battlegroup:" -ForegroundColor White
|
||||||
|
Write-Host " 1. In the battlegroup management UI, select option 5" -ForegroundColor White
|
||||||
|
Write-Host " (Restart battlegroup)" -ForegroundColor DarkGray
|
||||||
|
Write-Host " 2. Wait for all pods to come back healthy" -ForegroundColor White
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " The dashboard will auto-fix ownership on every startup," -ForegroundColor Green
|
||||||
|
Write-Host " so this should not happen again." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return to the menu..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
}
|
||||||
|
|
||||||
|
function Cleanup-OldDashboardSchema {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Clean Up Old Dashboard Schema" -ForegroundColor Cyan
|
||||||
|
Write-Host " ===============================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
|
||||||
|
if ( -not (Test-Path $settingsFile) ) {
|
||||||
|
Write-Host "[ERROR] settings.yaml not found." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
|
||||||
|
if ( -not $settingsJson ) { Write-Host "[ERROR] Could not read settings." -ForegroundColor Red; return }
|
||||||
|
$settings = $settingsJson | ConvertFrom-Json
|
||||||
|
$ServerHost = $settings.server.host
|
||||||
|
$SSHUser = $settings.server.user
|
||||||
|
$Namespace = $settings.kubernetes.namespace
|
||||||
|
$SSHKey = $settings.server.ssh_key
|
||||||
|
if ( -not $SSHKey -or $SSHKey -eq 'null' ) {
|
||||||
|
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( -not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP' ) { Write-Host "[ERROR] Server IP not configured." -ForegroundColor Red; return }
|
||||||
|
if ( -not $Namespace ) { Write-Host "[ERROR] Namespace not configured." -ForegroundColor Red; return }
|
||||||
|
if ( -not (Test-Path $SSHKey) ) { Write-Host "[ERROR] SSH key not found." -ForegroundColor Red; return }
|
||||||
|
|
||||||
|
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
|
||||||
|
if ( -not $dbPod ) { Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red; return }
|
||||||
|
|
||||||
|
$hasOldSchema = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -t -c ""SELECT count(*) FROM information_schema.schemata WHERE schema_name = 'dashboard'"" 2>&1" 2>$null
|
||||||
|
$hasOldSchema = $hasOldSchema.Trim()
|
||||||
|
|
||||||
|
if ( $hasOldSchema -eq '0' ) {
|
||||||
|
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ( -not $hasOldSchema ) {
|
||||||
|
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host " [WARN] Old dashboard schema found in the game database." -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " This drops: dashboard.audit_log, dashboard.bans, dashboard.player_ips," -ForegroundColor White
|
||||||
|
Write-Host " dashboard.player_actions, dashboard.chat_history, dashboard.settings" -ForegroundColor White
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Make sure the dashboard has migrated this data to the new database first." -ForegroundColor Yellow
|
||||||
|
Write-Host " (The dashboard does this automatically on next startup.)" -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$confirm = Read-Host " Type 'yes' to drop the old dashboard schema"
|
||||||
|
if ($confirm -ne 'yes') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$confirm2 = Read-Host " REALLY drop? This cannot be undone. Type 'yes' again"
|
||||||
|
if ($confirm2 -ne 'yes') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Dropping old dashboard schema..." -ForegroundColor Yellow
|
||||||
|
$result = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -c ""DROP SCHEMA IF EXISTS dashboard CASCADE"" 2>&1"
|
||||||
|
Write-Host " $result" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Old dashboard schema dropped." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
}
|
||||||
|
|
||||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Show-Banner
|
Show-Banner
|
||||||
@@ -2889,9 +3141,11 @@ while ($true) {
|
|||||||
"6" { Start-DashboardDebug; break }
|
"6" { Start-DashboardDebug; break }
|
||||||
"7" { Start-NewDashboard; break }
|
"7" { Start-NewDashboard; break }
|
||||||
"8" { Reset-ToFactoryDefaults; break }
|
"8" { Reset-ToFactoryDefaults; break }
|
||||||
|
"9" { Repair-GameDatabase; break }
|
||||||
|
"10" { Cleanup-OldDashboardSchema; break }
|
||||||
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
||||||
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
||||||
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-8, or Q." -ForegroundColor Yellow; Write-Host "" }
|
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-10, or Q." -ForegroundColor Yellow; Write-Host "" }
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ database:
|
|||||||
min_connections: 2
|
min_connections: 2
|
||||||
max_connections: 10
|
max_connections: 10
|
||||||
dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility)
|
dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility)
|
||||||
|
dashboard_database_name: "dashboard" # Dedicated database for dashboard tables (auto-created on startup)
|
||||||
|
|
||||||
# Kubernetes
|
# Kubernetes
|
||||||
kubernetes:
|
kubernetes:
|
||||||
|
|||||||
+2
-1
@@ -224,7 +224,8 @@ table {
|
|||||||
}
|
}
|
||||||
|
|
||||||
thead th {
|
thead th {
|
||||||
background: #f8f6f2;
|
background: var(--table-header);
|
||||||
|
color: var(--text);
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
+88
-27
@@ -322,6 +322,24 @@
|
|||||||
--code-bg: #fafaf5;
|
--code-bg: #fafaf5;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== Dark Variants (for light themes) ===== */
|
||||||
|
[data-theme="default-dark"] { --primary:#c9a24e; --primary-dark:#a8862e; --primary-light:#e0c97a; --bg:#1a1a1e; --card-bg:#252528; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#c9a24e; --danger:#c0392b; --success:#27ae60; --nav-bg:#0d0d12; --nav-text:#c0c0c0; --nav-active:#c9a24e; --hover:#2a2a2e; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2a2e; --code-bg:#1e1e22; }
|
||||||
|
[data-theme="atreides-dark"] { --primary:#2d5a27; --primary-dark:#1e3d19; --primary-light:#4a8c42; --bg:#1a1e1a; --card-bg:#252825; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#3d7a37; --danger:#cc4422; --success:#4a8c42; --nav-bg:#0d120d; --nav-text:#c0c0c0; --nav-active:#6abf6a; --hover:#2a2e2a; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2a; --code-bg:#1e221e; }
|
||||||
|
[data-theme="fremen-dark"] { --primary:#d4a853; --primary-dark:#b8913f; --primary-light:#e8c87a; --bg:#1e1a15; --card-bg:#282420; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#d4a853; --danger:#c45030; --success:#6b8e23; --nav-bg:#100c08; --nav-text:#c0b8a8; --nav-active:#d4a853; --hover:#2a2520; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2520; --code-bg:#1e1c18; }
|
||||||
|
[data-theme="bene-gesserit-dark"] { --primary:#a8a8a8; --primary-dark:#888; --primary-light:#c8c8c8; --bg:#1a1a1c; --card-bg:#252528; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#888; --danger:#c41e3a; --success:#2e8b57; --nav-bg:#0d0d0e; --nav-text:#c0c0c0; --nav-active:#ccc; --hover:#2a2a2c; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2a2c; --code-bg:#1e1e20; }
|
||||||
|
[data-theme="corrino-dark"] { --primary:#b02020; --primary-dark:#8b0000; --primary-light:#d44040; --bg:#1e1a1a; --card-bg:#282525; --text:#e0d8d8; --text-light:#a09090; --text-muted:#705858; --border:#383333; --accent:#c43030; --danger:#c0392b; --success:#27ae60; --nav-bg:#120d0d; --nav-text:#c0b8b8; --nav-active:#ff6b6b; --hover:#2e2a2a; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2e2a2a; --code-bg:#221e1e; }
|
||||||
|
[data-theme="mentat-dark"] { --primary:#008b8b; --primary-dark:#006666; --primary-light:#20b2aa; --bg:#1a1e1e; --card-bg:#252828; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#008b8b; --danger:#c44569; --success:#20b2aa; --nav-bg:#0d1212; --nav-text:#c0c0c0; --nav-active:#00ced1; --hover:#2a2e2e; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2e; --code-bg:#1e2222; }
|
||||||
|
[data-theme="sardaukar-dark"] { --primary:#cd853f; --primary-dark:#a0522d; --primary-light:#deb887; --bg:#1e1a15; --card-bg:#282420; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#cd853f; --danger:#cc4422; --success:#6b8e23; --nav-bg:#100c08; --nav-text:#c0b8a8; --nav-active:#cd853f; --hover:#2a2520; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2520; --code-bg:#1e1c18; }
|
||||||
|
[data-theme="ordos-dark"] { --primary:#2e8b57; --primary-dark:#1c5c3a; --primary-light:#3cb371; --bg:#1a1e1c; --card-bg:#252825; --text:#e0e0d8; --text-light:#a0a090; --text-muted:#707060; --border:#333a33; --accent:#3cb371; --danger:#cc5c3a; --success:#3cb371; --nav-bg:#0d120d; --nav-text:#c0c8c0; --nav-active:#3cb371; --hover:#2a2e2c; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2c; --code-bg:#1e221e; }
|
||||||
|
[data-theme="ix-dark"] { --primary:#4169e1; --primary-dark:#2c4db8; --primary-light:#6495ed; --bg:#1a1c22; --card-bg:#252530; --text:#e0e0e8; --text-light:#a0a0c0; --text-muted:#707090; --border:#333a50; --accent:#6495ed; --danger:#c44569; --success:#32cd32; --nav-bg:#0d0d15; --nav-text:#c0c0d8; --nav-active:#6495ed; --hover:#2a2c38; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2c38; --code-bg:#1e1e28; }
|
||||||
|
[data-theme="choam-dark"] { --primary:#daa520; --primary-dark:#b8860b; --primary-light:#e8c840; --bg:#1e1c15; --card-bg:#282520; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#daa520; --danger:#b22222; --success:#228b22; --nav-bg:#100e08; --nav-text:#c0b8a8; --nav-active:#daa520; --hover:#2a2820; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2820; --code-bg:#1e1c18; }
|
||||||
|
|
||||||
|
/* ===== Light Variants (for dark themes) ===== */
|
||||||
|
[data-theme="harkonnen-light"] { --primary:#ff6b00; --primary-dark:#cc5500; --primary-light:#ff8c33; --bg:#f5f0e8; --card-bg:#ffffff; --text:#1a1a1a; --text-light:#505050; --text-muted:#808080; --border:#e0d8c8; --accent:#ff4500; --danger:#cc0000; --success:#00aa33; --nav-bg:#1a1a1a; --nav-text:#d0d0d0; --nav-active:#ff6b00; --hover:#f0e8d8; --shadow:0 2px 8px rgba(0,0,0,0.08); --table-header:#e8e0d0; --code-bg:#faf8f5; }
|
||||||
|
[data-theme="spacing-guild-light"] { --primary:#4a90d9; --primary-dark:#2e6ab3; --primary-light:#6baee8; --bg:#e8edf5; --card-bg:#ffffff; --text:#1a2230; --text-light:#404860; --text-muted:#687080; --border:#d0d8e8; --accent:#4a90d9; --danger:#d94545; --success:#45d985; --nav-bg:#1a1a2e; --nav-text:#c0c8d0; --nav-active:#4a90d9; --hover:#e0e8f0; --shadow:0 2px 8px rgba(0,0,40,0.1); --table-header:#d8e0ed; --code-bg:#f4f6fa; }
|
||||||
|
[data-theme="emperor-light"] { --primary:#d4af37; --primary-dark:#b8962f; --primary-light:#e8c962; --bg:#faf8f0; --card-bg:#ffffff; --text:#1a1a1a; --text-light:#505050; --text-muted:#808080; --border:#e0d8c0; --accent:#d4af37; --danger:#c0392b; --success:#27ae60; --nav-bg:#1a1a1a; --nav-text:#d0d0d0; --nav-active:#d4af37; --hover:#f0ece0; --shadow:0 2px 8px rgba(0,0,0,0.08); --table-header:#e8e4d8; --code-bg:#fafaf5; }
|
||||||
|
[data-theme="tleilax-light"] { --primary:#6b20b0; --primary-dark:#4a0080; --primary-light:#9966cc; --bg:#f4f0f8; --card-bg:#ffffff; --text:#1a1a24; --text-light:#404060; --text-muted:#686880; --border:#d8d0e8; --accent:#8030cc; --danger:#c41e3a; --success:#00c080; --nav-bg:#1a1a24; --nav-text:#d0d0d8; --nav-active:#9966cc; --hover:#f0e8f8; --shadow:0 2px 8px rgba(40,0,60,0.1); --table-header:#e0d8f0; --code-bg:#f8f4fc; }
|
||||||
|
|
||||||
/* Theme Selector Button */
|
/* Theme Selector Button */
|
||||||
.theme-btn {
|
.theme-btn {
|
||||||
background: none;
|
background: none;
|
||||||
@@ -350,43 +368,70 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
right: 0;
|
right: 0;
|
||||||
background: #252530;
|
background: #252530;
|
||||||
min-width: 180px;
|
min-width: 290px;
|
||||||
|
max-height: 80vh;
|
||||||
|
overflow-y: auto;
|
||||||
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
padding: 8px 0;
|
padding: 12px;
|
||||||
border: 1px solid #404050;
|
border: 1px solid #404050;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.theme-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 4px;
|
||||||
|
border-radius: 6px;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row:hover {
|
||||||
|
background: rgba(255,255,255,0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row-label {
|
||||||
|
flex: 1;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #d0d0d8;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.15s, box-shadow 0.15s;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch:hover {
|
||||||
|
transform: scale(1.2);
|
||||||
|
box-shadow: 0 0 8px rgba(255,255,255,0.3);
|
||||||
|
border-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch.active-theme {
|
||||||
|
border-color: #fff;
|
||||||
|
box-shadow: 0 0 6px rgba(255,255,255,0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.theme-dropdown:hover .theme-dropdown-content {
|
.theme-dropdown:hover .theme-dropdown-content {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-option {
|
/* Theme swatches base */
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
padding: 10px 16px;
|
|
||||||
cursor: pointer;
|
|
||||||
color: #d0d0d8;
|
|
||||||
font-size: 13px;
|
|
||||||
transition: background 0.15s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option:hover {
|
|
||||||
background: rgba(255,255,255,0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option.active {
|
|
||||||
background: var(--primary);
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option.active:hover {
|
|
||||||
background: var(--primary-dark);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Theme swatches */
|
|
||||||
.theme-swatch {
|
.theme-swatch {
|
||||||
width: 20px;
|
width: 20px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
@@ -410,6 +455,22 @@
|
|||||||
.theme-swatch.ix { background: linear-gradient(135deg, #4169e1 50%, #e8edf8 50%); }
|
.theme-swatch.ix { background: linear-gradient(135deg, #4169e1 50%, #e8edf8 50%); }
|
||||||
.theme-swatch.choam { background: linear-gradient(135deg, #b8860b 50%, #faf8f0 50%); }
|
.theme-swatch.choam { background: linear-gradient(135deg, #b8860b 50%, #faf8f0 50%); }
|
||||||
|
|
||||||
|
/* Variant swatches */
|
||||||
|
.theme-swatch.default-dark { background: linear-gradient(135deg, #c9a24e 50%, #1a1a1e 50%); }
|
||||||
|
.theme-swatch.atreides-dark { background: linear-gradient(135deg, #2d5a27 50%, #1a1e1a 50%); }
|
||||||
|
.theme-swatch.harkonnen-light { background: linear-gradient(135deg, #ff6b00 50%, #f5f0e8 50%); }
|
||||||
|
.theme-swatch.fremen-dark { background: linear-gradient(135deg, #d4a853 50%, #1e1a15 50%); }
|
||||||
|
.theme-swatch.bene-gesserit-dark { background: linear-gradient(135deg, #a8a8a8 50%, #1a1a1c 50%); }
|
||||||
|
.theme-swatch.spacing-guild-light { background: linear-gradient(135deg, #4a90d9 50%, #e8edf5 50%); }
|
||||||
|
.theme-swatch.emperor-light { background: linear-gradient(135deg, #d4af37 50%, #faf8f0 50%); }
|
||||||
|
.theme-swatch.corrino-dark { background: linear-gradient(135deg, #b02020 50%, #1e1a1a 50%); }
|
||||||
|
.theme-swatch.mentat-dark { background: linear-gradient(135deg, #008b8b 50%, #1a1e1e 50%); }
|
||||||
|
.theme-swatch.sardaukar-dark { background: linear-gradient(135deg, #cd853f 50%, #1e1a15 50%); }
|
||||||
|
.theme-swatch.tleilax-light { background: linear-gradient(135deg, #6b20b0 50%, #f4f0f8 50%); }
|
||||||
|
.theme-swatch.ordos-dark { background: linear-gradient(135deg, #2e8b57 50%, #1a1e1c 50%); }
|
||||||
|
.theme-swatch.ix-dark { background: linear-gradient(135deg, #4169e1 50%, #1a1c22 50%); }
|
||||||
|
.theme-swatch.choam-dark { background: linear-gradient(135deg, #daa520 50%, #1e1c15 50%); }
|
||||||
|
|
||||||
/* Current theme indicator */
|
/* Current theme indicator */
|
||||||
#current-theme-display {
|
#current-theme-display {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
|
|||||||
@@ -1,12 +1,41 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block title %}Admin Experimental - Dune Awakening Dashboard{% endblock %}
|
{% block title %}Experimental - Dune Awakening Dashboard{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
|
<div id="exp-gate" class="exp-gate">
|
||||||
|
<div class="exp-gate-box">
|
||||||
|
<div class="exp-gate-icon">⚠</div>
|
||||||
|
<h2>Experimental Features — Proceed with Caution</h2>
|
||||||
|
<p>This area contains <strong>untested, experimental tools</strong> that interact directly with your game server's internal systems (RabbitMQ, PostgreSQL, Battlegroup Director).</p>
|
||||||
|
<p>These tools <strong>can corrupt data, crash servers, or delete characters</strong>. Do not report bugs about this page. Always snapshot or backup your server first.</p>
|
||||||
|
<div class="exp-gate-actions">
|
||||||
|
<button onclick="denyExperimental()" class="exp-gate-btn deny">Take Me Back to Safety</button>
|
||||||
|
<button onclick="acceptExperimental()" class="exp-gate-btn accept">I Understand the Risks — Proceed</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="exp-content" style="display:none;">
|
||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>Admin Experimental</h1>
|
<h1>Experimental</h1>
|
||||||
<p>Experimental tools discovered through server research</p>
|
<p>Experimental tools discovered through server research</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="experimental-warning">
|
||||||
|
<div class="experimental-warning-title">⚠ DANGER — EXPERIMENTAL FEATURES</div>
|
||||||
|
<div class="experimental-warning-body">
|
||||||
|
<p>This page contains <strong>experimental and potentially destructive</strong> tools that interact directly with your game server's internal systems (RabbitMQ, PostgreSQL, Battlegroup Director).</p>
|
||||||
|
<p><strong>These tools can corrupt your database, crash game servers, delete player data, or render your cluster inoperable.</strong></p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>DO NOT report bugs</strong> found on this page — these features are untested and in active research.</li>
|
||||||
|
<li><strong>USE AT YOUR OWN RISK.</strong> The dashboard authors are not responsible for any damage caused.</li>
|
||||||
|
<li><strong>SNAPSHOT OR BACKUP YOUR SERVER</strong> before using ANY tool on this page.</li>
|
||||||
|
<li>If you don't understand what a button does, <strong>DO NOT CLICK IT.</strong></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">In-Game Broadcast</div>
|
<div class="card-header">In-Game Broadcast</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@@ -405,12 +434,98 @@
|
|||||||
<option value="in_demo">In Demo</option>
|
<option value="in_demo">In Demo</option>
|
||||||
<option value="demo_expired">Demo Expired</option>
|
<option value="demo_expired">Demo Expired</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button onclick="setDemoState()" style="margin-top:8px;padding:8px 16px;background:var(--bg-hover);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;">Set Demo State</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:24px;">
|
||||||
|
<h2 style="margin-bottom:16px;">RabbitMQ Explorer</h2>
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:16px;">
|
||||||
|
Inspect the RMQ clusters. Both Admin (port 30325) and Game (port 32716) instances via SSH tunnel.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Overview</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">Cluster health, node info, message stats.</p>
|
||||||
|
<div id="rmq-overview-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqOverview()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<pre id="rmq-overview-data" style="max-height:300px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Queues</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">All queues with consumer counts and message depths.</p>
|
||||||
|
<div id="rmq-queues-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqQueues()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<div id="rmq-queues-data" style="max-height:300px;overflow:auto;font-size:11px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Exchanges</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">All exchanges with type, durability, and message stats.</p>
|
||||||
|
<div id="rmq-exchanges-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqExchanges()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<div id="rmq-exchanges-data" style="max-height:300px;overflow:auto;font-size:11px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Message Inspector</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">Peek at messages in any queue without consuming them.</p>
|
||||||
|
<div id="rmq-peek-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<div style="display:flex;gap:8px;margin-bottom:8px;">
|
||||||
|
<input type="text" id="rmq-peek-queue" placeholder="Queue name..."
|
||||||
|
style="flex:1;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<input type="number" id="rmq-peek-count" value="5" min="1" max="20"
|
||||||
|
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<button onclick="peekRmqMessages()"
|
||||||
|
style="padding:6px 14px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Peek</button>
|
||||||
|
</div>
|
||||||
|
<pre id="rmq-peek-data" style="max-height:300px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" style="grid-column:1 / -1;">
|
||||||
|
<div class="card-header">Publish Test Message</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">
|
||||||
|
Publish a test message to any exchange. <strong>Note:</strong> HTTP API sets user_id to dashboard_admin, which the game server may reject for RPC commands. Use the Erlang eval broadcast for in-game commands.
|
||||||
|
</p>
|
||||||
|
<div id="rmq-publish-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<div style="display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap;">
|
||||||
|
<select id="rmq-publish-side" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<option value="admin">Admin (30325)</option>
|
||||||
|
<option value="game">Game (32716)</option>
|
||||||
|
</select>
|
||||||
|
<input type="text" id="rmq-publish-exchange" placeholder="Exchange name..."
|
||||||
|
style="flex:1;min-width:150px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<input type="text" id="rmq-publish-routing" placeholder="Routing key..."
|
||||||
|
style="flex:1;min-width:150px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<button onclick="publishRmqMessage()"
|
||||||
|
style="padding:6px 14px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Publish</button>
|
||||||
|
</div>
|
||||||
|
<textarea id="rmq-publish-message" rows="4" placeholder='{"key": "value"}'
|
||||||
|
style="width:100%;padding:8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;font-family:monospace;resize:vertical;"></textarea>
|
||||||
|
<pre id="rmq-publish-data" style="max-height:200px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;margin-top:8px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">Journey & Specialization</div>
|
<div class="card-header">Journey & Specialization</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@@ -539,10 +654,28 @@
|
|||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.error-banner { padding: 10px 14px; border-radius: 4px; margin-bottom: 12px; font-size: 13px; }
|
.error-banner { padding: 10px 14px; border-radius: 4px; margin-bottom: 12px; font-size: 13px; }
|
||||||
.error-banner.success { background: #1a3a2a; border: 1px solid #2ecc71; color: #2ecc71; display: block; }
|
.error-banner.success { background: #1a3a2a; border: 1px solid #2ecc71; color: #2ecc71; display: block; }
|
||||||
.error-banner.error { background: #3a1a1a; border: 1px solid #e74c3c; color: #e74c3c; display: block; }
|
.error-banner.error { background: #3a1a1a; border: 1px solid #e74c3c; color: #e74c3c; display: block; }
|
||||||
|
.experimental-warning { background: rgba(220,38,38,0.12); border: 2px solid rgba(220,38,38,0.6); border-left: 6px solid #dc2626; border-radius: 8px; padding: 18px 22px; margin-bottom: 24px; }
|
||||||
|
.experimental-warning-title { font-size: 16px; font-weight: 700; color: #ef4444; margin-bottom: 12px; }
|
||||||
|
.experimental-warning-body p { margin: 0 0 10px; font-size: 13px; color: var(--text); line-height: 1.6; }
|
||||||
|
.experimental-warning-body ul { margin: 8px 0 0; padding-left: 20px; font-size: 13px; color: var(--text); line-height: 1.8; }
|
||||||
|
.experimental-warning-body li { margin-bottom: 4px; }
|
||||||
|
.exp-gate { position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 9999; display: flex; align-items: center; justify-content: center; }
|
||||||
|
.exp-gate-box { background: #1a1a1e; border: 2px solid #dc2626; border-radius: 12px; max-width: 560px; width: 90%; padding: 32px; text-align: center; color: #e0e0e0; }
|
||||||
|
.exp-gate-icon { font-size: 48px; color: #ef4444; margin-bottom: 16px; }
|
||||||
|
.exp-gate-box h2 { font-size: 18px; color: #ef4444; margin: 0 0 16px; }
|
||||||
|
.exp-gate-box p { font-size: 13px; line-height: 1.6; margin: 0 0 12px; color: #c0c0c0; }
|
||||||
|
.exp-gate-actions { display: flex; gap: 12px; margin-top: 20px; justify-content: center; flex-wrap: wrap; }
|
||||||
|
.exp-gate-btn { padding: 12px 24px; border: none; border-radius: 6px; font-size: 14px; font-weight: 600; cursor: pointer; }
|
||||||
|
.exp-gate-btn.accept { background: #dc2626; color: #fff; }
|
||||||
|
.exp-gate-btn.accept:hover { background: #b91c1c; }
|
||||||
|
.exp-gate-btn.deny { background: #374151; color: #d0d0d0; }
|
||||||
|
.exp-gate-btn.deny:hover { background: #4b5563; }
|
||||||
code { background: var(--bg-hover); padding: 1px 4px; border-radius: 3px; font-size: 12px; }
|
code { background: var(--bg-hover); padding: 1px 4px; border-radius: 3px; font-size: 12px; }
|
||||||
.result-table { width:100%; border-collapse:collapse; font-size:12px; margin-top:8px; }
|
.result-table { width:100%; border-collapse:collapse; font-size:12px; margin-top:8px; }
|
||||||
.result-table th { text-align:left; padding:6px 8px; background:var(--bg-hover); border-bottom:2px solid var(--border); }
|
.result-table th { text-align:left; padding:6px 8px; background:var(--bg-hover); border-bottom:2px solid var(--border); }
|
||||||
@@ -1272,11 +1405,131 @@ async function executeFunction(name, paramCount) {
|
|||||||
} catch(e) { resultDiv.innerHTML = `<div class="error-banner error" style="display:block;">${esc(e.message)}</div>`; }
|
} catch(e) { resultDiv.innerHTML = `<div class="error-banner error" style="display:block;">${esc(e.message)}</div>`; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── RMQ Explorer ─────────────────────────────────────────────────
|
||||||
|
async function loadRmqOverview() {
|
||||||
|
const status = document.getElementById('rmq-overview-status');
|
||||||
|
const output = document.getElementById('rmq-overview-data');
|
||||||
|
hideStatus(status); output.textContent = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/overview');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRmqQueues() {
|
||||||
|
const status = document.getElementById('rmq-queues-status');
|
||||||
|
const output = document.getElementById('rmq-queues-data');
|
||||||
|
hideStatus(status); output.innerHTML = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/queues');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.innerHTML = ''; return; }
|
||||||
|
const data = d.data || {};
|
||||||
|
let html = '';
|
||||||
|
for (const [side, queues] of Object.entries(data)) {
|
||||||
|
html += `<h4 style="margin:8px 0 4px;font-size:12px;color:var(--text)">RMQ ${side.toUpperCase()}</h4>`;
|
||||||
|
if (!queues || !queues.length) { html += '<p style="font-size:11px;color:var(--text-muted)">No queues or connection failed</p>'; continue; }
|
||||||
|
html += '<table class="result-table"><tr><th>Name</th><th>State</th><th>Ready</th><th>Consumers</th></tr>';
|
||||||
|
for (const q of queues) {
|
||||||
|
html += `<tr><td style="font-size:10px;word-break:break-all">${esc(q.name||'?')}</td>`;
|
||||||
|
html += `<td>${esc(String(q.state||''))}</td>`;
|
||||||
|
html += `<td>${q.messages_ready||0}</td><td>${q.consumers||0}</td></tr>`;
|
||||||
|
}
|
||||||
|
html += '</table>';
|
||||||
|
}
|
||||||
|
output.innerHTML = html;
|
||||||
|
} catch(e) { showError(status, e.message); output.innerHTML = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRmqExchanges() {
|
||||||
|
const status = document.getElementById('rmq-exchanges-status');
|
||||||
|
const output = document.getElementById('rmq-exchanges-data');
|
||||||
|
hideStatus(status); output.innerHTML = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/exchanges');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.innerHTML = ''; return; }
|
||||||
|
const data = d.data || {};
|
||||||
|
let html = '';
|
||||||
|
for (const [side, exchanges] of Object.entries(data)) {
|
||||||
|
html += `<h4 style="margin:8px 0 4px;font-size:12px;color:var(--text)">RMQ ${side.toUpperCase()}</h4>`;
|
||||||
|
if (!exchanges || !exchanges.length) { html += '<p style="font-size:11px;color:var(--text-muted)">No exchanges or connection failed</p>'; continue; }
|
||||||
|
html += '<table class="result-table"><tr><th>Name</th><th>Type</th><th>Durable</th><th>Msgs</th></tr>';
|
||||||
|
for (const x of exchanges) {
|
||||||
|
html += `<tr><td style="font-size:10px;word-break:break-all">${esc(x.name||'?')}</td>`;
|
||||||
|
html += `<td>${esc(x.type||'')}</td><td>${x.durable?'Yes':'No'}</td>`;
|
||||||
|
html += `<td>${x.message_stats?.publish_in||0}</td></tr>`;
|
||||||
|
}
|
||||||
|
html += '</table>';
|
||||||
|
}
|
||||||
|
output.innerHTML = html;
|
||||||
|
} catch(e) { showError(status, e.message); output.innerHTML = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function peekRmqMessages() {
|
||||||
|
const status = document.getElementById('rmq-peek-status');
|
||||||
|
const output = document.getElementById('rmq-peek-data');
|
||||||
|
const queue = document.getElementById('rmq-peek-queue').value.trim();
|
||||||
|
const count = parseInt(document.getElementById('rmq-peek-count').value) || 5;
|
||||||
|
if (!queue) { showError(status, 'Enter a queue name'); return; }
|
||||||
|
hideStatus(status); output.textContent = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/peek', {
|
||||||
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({queue, count})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishRmqMessage() {
|
||||||
|
const status = document.getElementById('rmq-publish-status');
|
||||||
|
const output = document.getElementById('rmq-publish-data');
|
||||||
|
const side = document.getElementById('rmq-publish-side').value;
|
||||||
|
const exchange = document.getElementById('rmq-publish-exchange').value.trim();
|
||||||
|
const routing_key = document.getElementById('rmq-publish-routing').value.trim();
|
||||||
|
const messageStr = document.getElementById('rmq-publish-message').value.trim();
|
||||||
|
if (!exchange) { showError(status, 'Enter an exchange name'); return; }
|
||||||
|
hideStatus(status); output.textContent = 'Publishing...';
|
||||||
|
let message = messageStr;
|
||||||
|
try { message = JSON.parse(messageStr); } catch(_) {}
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/publish', {
|
||||||
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({exchange, routing_key, message, side})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helpers ─────────────────────────────────────────────────────────
|
// ── Helpers ─────────────────────────────────────────────────────────
|
||||||
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||||
function showError(el, msg) { el.className = 'error-banner error'; el.textContent = msg; el.style.display = 'block'; }
|
function showError(el, msg) { el.className = 'error-banner error'; el.textContent = msg; el.style.display = 'block'; }
|
||||||
function showSuccess(el, msg) { el.className = 'error-banner success'; el.textContent = msg; el.style.display = 'block'; }
|
function showSuccess(el, msg) { el.className = 'error-banner success'; el.textContent = msg; el.style.display = 'block'; }
|
||||||
function hideStatus(el) { el.style.display = 'none'; }
|
function hideStatus(el) { el.style.display = 'none'; }
|
||||||
|
|
||||||
|
function acceptExperimental() {
|
||||||
|
document.getElementById('exp-gate').style.display = 'none';
|
||||||
|
document.getElementById('exp-content').style.display = 'block';
|
||||||
|
localStorage.setItem('exp-warning-accepted', '1');
|
||||||
|
}
|
||||||
|
|
||||||
|
function denyExperimental() {
|
||||||
|
localStorage.removeItem('exp-warning-accepted');
|
||||||
|
window.location.href = '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
if (localStorage.getItem('exp-warning-accepted') === '1') {
|
||||||
|
acceptExperimental();
|
||||||
|
}
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
+75
-132
@@ -7,15 +7,9 @@
|
|||||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
||||||
|
{% block head_extra %}{% endblock %}
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="update-banner" class="update-banner" style="display:none;">
|
|
||||||
<span>🔄 Update available for Dune Dashboard</span>
|
|
||||||
<div class="update-actions">
|
|
||||||
<button onclick="applyUpdate()" class="update-btn primary">Update Now</button>
|
|
||||||
<button onclick="dismissUpdate()" class="update-btn">Later</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<nav>
|
<nav>
|
||||||
<div class="brand">DUNE DASHBOARD</div>
|
<div class="brand">DUNE DASHBOARD</div>
|
||||||
{% for href, label in nav_pages %}
|
{% for href, label in nav_pages %}
|
||||||
@@ -25,47 +19,77 @@
|
|||||||
<div class="theme-dropdown">
|
<div class="theme-dropdown">
|
||||||
<button class="theme-btn" title="Theme">🎨</button>
|
<button class="theme-btn" title="Theme">🎨</button>
|
||||||
<div class="theme-dropdown-content">
|
<div class="theme-dropdown-content">
|
||||||
<div class="theme-option active" data-theme="default" onclick="setTheme('default')">
|
<div class="theme-grid">
|
||||||
<span class="theme-swatch default"></span> Classic Dune
|
<div class="theme-row" data-family="default">
|
||||||
</div>
|
<span class="theme-row-label">Classic Dune</span>
|
||||||
<div class="theme-option" data-theme="atreides" onclick="setTheme('atreides')">
|
<span class="theme-swatch default" data-theme="default" onclick="setTheme('default')" title="Classic Dune Light"></span>
|
||||||
<span class="theme-swatch atrides"></span> House Atreides
|
<span class="theme-swatch default-dark active-theme" data-theme="default-dark" onclick="setTheme('default-dark')" title="Classic Dune Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="harkonnen" onclick="setTheme('harkonnen')">
|
<div class="theme-row" data-family="atreides">
|
||||||
<span class="theme-swatch harkonnen"></span> House Harkonnen
|
<span class="theme-row-label">House Atreides</span>
|
||||||
</div>
|
<span class="theme-swatch atreides" data-theme="atreides" onclick="setTheme('atreides')" title="House Atreides Light"></span>
|
||||||
<div class="theme-option" data-theme="fremen" onclick="setTheme('fremen')">
|
<span class="theme-swatch atreides-dark" data-theme="atreides-dark" onclick="setTheme('atreides-dark')" title="House Atreides Dark"></span>
|
||||||
<span class="theme-swatch fremen"></span> Fremen
|
</div>
|
||||||
</div>
|
<div class="theme-row" data-family="harkonnen">
|
||||||
<div class="theme-option" data-theme="bene-gesserit" onclick="setTheme('bene-gesserit')">
|
<span class="theme-row-label">House Harkonnen</span>
|
||||||
<span class="theme-swatch bene-gesserit"></span> Bene Gesserit
|
<span class="theme-swatch harkonnen-light" data-theme="harkonnen-light" onclick="setTheme('harkonnen-light')" title="House Harkonnen Light"></span>
|
||||||
</div>
|
<span class="theme-swatch harkonnen" data-theme="harkonnen" onclick="setTheme('harkonnen')" title="House Harkonnen Dark"></span>
|
||||||
<div class="theme-option" data-theme="spacing-guild" onclick="setTheme('spacing-guild')">
|
</div>
|
||||||
<span class="theme-swatch spacing-guild"></span> Spacing Guild
|
<div class="theme-row" data-family="fremen">
|
||||||
</div>
|
<span class="theme-row-label">Fremen</span>
|
||||||
<div class="theme-option" data-theme="emperor" onclick="setTheme('emperor')">
|
<span class="theme-swatch fremen" data-theme="fremen" onclick="setTheme('fremen')" title="Fremen Light"></span>
|
||||||
<span class="theme-swatch emperor"></span> Emperor
|
<span class="theme-swatch fremen-dark" data-theme="fremen-dark" onclick="setTheme('fremen-dark')" title="Fremen Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="corrino" onclick="setTheme('corrino')">
|
<div class="theme-row" data-family="bene-gesserit">
|
||||||
<span class="theme-swatch corrino"></span> House Corrino
|
<span class="theme-row-label">Bene Gesserit</span>
|
||||||
</div>
|
<span class="theme-swatch bene-gesserit" data-theme="bene-gesserit" onclick="setTheme('bene-gesserit')" title="Bene Gesserit Light"></span>
|
||||||
<div class="theme-option" data-theme="mentat" onclick="setTheme('mentat')">
|
<span class="theme-swatch bene-gesserit-dark" data-theme="bene-gesserit-dark" onclick="setTheme('bene-gesserit-dark')" title="Bene Gesserit Dark"></span>
|
||||||
<span class="theme-swatch mentat"></span> Mentat
|
</div>
|
||||||
</div>
|
<div class="theme-row" data-family="spacing-guild">
|
||||||
<div class="theme-option" data-theme="sardaukar" onclick="setTheme('sardaukar')">
|
<span class="theme-row-label">Spacing Guild</span>
|
||||||
<span class="theme-swatch sardaukar"></span> Sardaukar
|
<span class="theme-swatch spacing-guild-light" data-theme="spacing-guild-light" onclick="setTheme('spacing-guild-light')" title="Spacing Guild Light"></span>
|
||||||
</div>
|
<span class="theme-swatch spacing-guild" data-theme="spacing-guild" onclick="setTheme('spacing-guild')" title="Spacing Guild Dark"></span>
|
||||||
<div class="theme-option" data-theme="tleilax" onclick="setTheme('tleilax')">
|
</div>
|
||||||
<span class="theme-swatch tleilax"></span> Bene Tleilax
|
<div class="theme-row" data-family="emperor">
|
||||||
</div>
|
<span class="theme-row-label">Emperor</span>
|
||||||
<div class="theme-option" data-theme="ordos" onclick="setTheme('ordos')">
|
<span class="theme-swatch emperor-light" data-theme="emperor-light" onclick="setTheme('emperor-light')" title="Emperor Light"></span>
|
||||||
<span class="theme-swatch ordos"></span> House Ordos
|
<span class="theme-swatch emperor" data-theme="emperor" onclick="setTheme('emperor')" title="Emperor Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="ix" onclick="setTheme('ix')">
|
<div class="theme-row" data-family="corrino">
|
||||||
<span class="theme-swatch ix"></span> Ix
|
<span class="theme-row-label">House Corrino</span>
|
||||||
</div>
|
<span class="theme-swatch corrino" data-theme="corrino" onclick="setTheme('corrino')" title="House Corrino Light"></span>
|
||||||
<div class="theme-option" data-theme="choam" onclick="setTheme('choam')">
|
<span class="theme-swatch corrino-dark" data-theme="corrino-dark" onclick="setTheme('corrino-dark')" title="House Corrino Dark"></span>
|
||||||
<span class="theme-swatch choam"></span> CHOAM
|
</div>
|
||||||
|
<div class="theme-row" data-family="mentat">
|
||||||
|
<span class="theme-row-label">Mentat</span>
|
||||||
|
<span class="theme-swatch mentat" data-theme="mentat" onclick="setTheme('mentat')" title="Mentat Light"></span>
|
||||||
|
<span class="theme-swatch mentat-dark" data-theme="mentat-dark" onclick="setTheme('mentat-dark')" title="Mentat Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="sardaukar">
|
||||||
|
<span class="theme-row-label">Sardaukar</span>
|
||||||
|
<span class="theme-swatch sardaukar" data-theme="sardaukar" onclick="setTheme('sardaukar')" title="Sardaukar Light"></span>
|
||||||
|
<span class="theme-swatch sardaukar-dark" data-theme="sardaukar-dark" onclick="setTheme('sardaukar-dark')" title="Sardaukar Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="tleilax">
|
||||||
|
<span class="theme-row-label">Bene Tleilax</span>
|
||||||
|
<span class="theme-swatch tleilax-light" data-theme="tleilax-light" onclick="setTheme('tleilax-light')" title="Bene Tleilax Light"></span>
|
||||||
|
<span class="theme-swatch tleilax" data-theme="tleilax" onclick="setTheme('tleilax')" title="Bene Tleilax Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="ordos">
|
||||||
|
<span class="theme-row-label">House Ordos</span>
|
||||||
|
<span class="theme-swatch ordos" data-theme="ordos" onclick="setTheme('ordos')" title="House Ordos Light"></span>
|
||||||
|
<span class="theme-swatch ordos-dark" data-theme="ordos-dark" onclick="setTheme('ordos-dark')" title="House Ordos Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="ix">
|
||||||
|
<span class="theme-row-label">Ix</span>
|
||||||
|
<span class="theme-swatch ix" data-theme="ix" onclick="setTheme('ix')" title="Ix Light"></span>
|
||||||
|
<span class="theme-swatch ix-dark" data-theme="ix-dark" onclick="setTheme('ix-dark')" title="Ix Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="choam">
|
||||||
|
<span class="theme-row-label">CHOAM</span>
|
||||||
|
<span class="theme-swatch choam" data-theme="choam" onclick="setTheme('choam')" title="CHOAM Light"></span>
|
||||||
|
<span class="theme-swatch choam-dark" data-theme="choam-dark" onclick="setTheme('choam-dark')" title="CHOAM Dark"></span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -73,7 +97,6 @@
|
|||||||
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
||||||
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
||||||
</span>
|
</span>
|
||||||
<button id="check-update-btn" onclick="manualCheckUpdate()" style="font-size:12px;color:var(--nav-text);background:none;border:none;cursor:pointer;padding:4px 8px;" title="Check for updates">🔄 Check Updates</button>
|
|
||||||
{% if current_user and current_user.is_authenticated %}
|
{% if current_user and current_user.is_authenticated %}
|
||||||
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
|
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -84,13 +107,6 @@
|
|||||||
<footer class="site-footer">
|
<footer class="site-footer">
|
||||||
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
||||||
</footer>
|
</footer>
|
||||||
<div id="update-progress" class="update-progress" style="display:none;">
|
|
||||||
<div class="update-progress-inner">
|
|
||||||
<h3>Updating Dashboard...</h3>
|
|
||||||
<p id="update-status-text">Checking for updates...</p>
|
|
||||||
<div class="update-spinner"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script>
|
<script>
|
||||||
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
||||||
|
|
||||||
@@ -100,66 +116,6 @@
|
|||||||
return fetch(url, options);
|
return fetch(url, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
let updateDismissed = false;
|
|
||||||
async function checkForUpdate() {
|
|
||||||
if (updateDismissed) return;
|
|
||||||
try {
|
|
||||||
const resp = await fetch('/api/update/status');
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.available) {
|
|
||||||
document.getElementById('update-banner').style.display = 'flex';
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
}
|
|
||||||
async function manualCheckUpdate() {
|
|
||||||
const btn = document.getElementById('check-update-btn');
|
|
||||||
btn.textContent = 'Checking...';
|
|
||||||
btn.disabled = true;
|
|
||||||
try {
|
|
||||||
const resp = await csrfFetch('/api/update/check', { method: 'POST' });
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.available) {
|
|
||||||
document.getElementById('update-banner').style.display = 'flex';
|
|
||||||
btn.textContent = 'Update Available!';
|
|
||||||
} else {
|
|
||||||
btn.textContent = 'Up to Date ✓';
|
|
||||||
setTimeout(() => { btn.textContent = '🔄 Check Updates'; }, 3000);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
btn.textContent = 'Check Failed';
|
|
||||||
setTimeout(() => { btn.textContent = '🔄 Check Updates'; }, 3000);
|
|
||||||
}
|
|
||||||
btn.disabled = false;
|
|
||||||
}
|
|
||||||
function dismissUpdate() {
|
|
||||||
updateDismissed = true;
|
|
||||||
document.getElementById('update-banner').style.display = 'none';
|
|
||||||
}
|
|
||||||
async function applyUpdate() {
|
|
||||||
const banner = document.getElementById('update-banner');
|
|
||||||
const progress = document.getElementById('update-progress');
|
|
||||||
const statusText = document.getElementById('update-status-text');
|
|
||||||
banner.style.display = 'none';
|
|
||||||
progress.style.display = 'flex';
|
|
||||||
try {
|
|
||||||
const resp = await csrfFetch('/api/update/apply', { method: 'POST' });
|
|
||||||
const data = await resp.json();
|
|
||||||
statusText.textContent = data.message || 'Applying update...';
|
|
||||||
if (data.success) {
|
|
||||||
statusText.textContent = 'Update complete! Restarting...';
|
|
||||||
setTimeout(() => { location.reload(); }, 5000);
|
|
||||||
} else {
|
|
||||||
statusText.textContent = 'Update failed: ' + (data.message || 'Unknown error');
|
|
||||||
setTimeout(() => { progress.style.display = 'none'; }, 5000);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
statusText.textContent = 'Update failed: ' + e.message;
|
|
||||||
setTimeout(() => { progress.style.display = 'none'; }, 5000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setInterval(checkForUpdate, 60000);
|
|
||||||
checkForUpdate();
|
|
||||||
|
|
||||||
// Theme System
|
// Theme System
|
||||||
function setTheme(themeName) {
|
function setTheme(themeName) {
|
||||||
document.documentElement.setAttribute('data-theme', themeName);
|
document.documentElement.setAttribute('data-theme', themeName);
|
||||||
@@ -168,16 +124,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateThemeUI(themeName) {
|
function updateThemeUI(themeName) {
|
||||||
document.querySelectorAll('.theme-option').forEach(opt => {
|
document.querySelectorAll('.theme-row .theme-swatch').forEach(sw => {
|
||||||
opt.classList.remove('active');
|
sw.classList.toggle('active-theme', sw.getAttribute('data-theme') === themeName);
|
||||||
if (opt.getAttribute('data-theme') === themeName) {
|
|
||||||
opt.classList.add('active');
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function initTheme() {
|
function initTheme() {
|
||||||
const savedTheme = localStorage.getItem('dune-theme') || 'default';
|
const savedTheme = localStorage.getItem('dune-theme') || 'default-dark';
|
||||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||||
updateThemeUI(savedTheme);
|
updateThemeUI(savedTheme);
|
||||||
}
|
}
|
||||||
@@ -186,16 +139,6 @@
|
|||||||
</script>
|
</script>
|
||||||
{% block scripts %}{% endblock %}
|
{% block scripts %}{% endblock %}
|
||||||
<style>
|
<style>
|
||||||
.update-banner { background: var(--hover); border-bottom: 2px solid var(--accent); padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--text); }
|
|
||||||
.update-actions { display: flex; gap: 8px; }
|
|
||||||
.update-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 12px; }
|
|
||||||
.update-btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
|
|
||||||
.update-progress { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 9999; }
|
|
||||||
.update-progress-inner { background: var(--bg-card); padding: 30px 40px; border-radius: 8px; text-align: center; color: var(--text); max-width: 400px; }
|
|
||||||
.update-progress-inner h3 { margin: 0 0 10px; }
|
|
||||||
.update-progress-inner p { margin: 0 0 15px; color: var(--text-muted); font-size: 13px; }
|
|
||||||
.update-spinner { width: 30px; height: 30px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto; }
|
|
||||||
@keyframes spin { to { transform: rotate(360deg); } }
|
|
||||||
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
|
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
|
||||||
</style>
|
</style>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+110
-19
@@ -185,6 +185,7 @@
|
|||||||
<script>
|
<script>
|
||||||
let bgData = null;
|
let bgData = null;
|
||||||
let charTransferData = null;
|
let charTransferData = null;
|
||||||
|
let scaleData = {};
|
||||||
|
|
||||||
async function loadDirector() {
|
async function loadDirector() {
|
||||||
const banner = document.getElementById('loading-banner');
|
const banner = document.getElementById('loading-banner');
|
||||||
@@ -214,6 +215,7 @@ async function loadDirector() {
|
|||||||
if (ctResp.ok) {
|
if (ctResp.ok) {
|
||||||
charTransferData = await ctResp.json();
|
charTransferData = await ctResp.json();
|
||||||
}
|
}
|
||||||
|
await loadScaleData(bgData);
|
||||||
if (document.getElementById('maps-container').children.length === 0) {
|
if (document.getElementById('maps-container').children.length === 0) {
|
||||||
renderStats();
|
renderStats();
|
||||||
renderMaps();
|
renderMaps();
|
||||||
@@ -238,6 +240,21 @@ document.getElementById('btn-retry-director')?.addEventListener('click', () => {
|
|||||||
loadDirector();
|
loadDirector();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
async function loadScaleData(bg) {
|
||||||
|
const maps = [];
|
||||||
|
const addMaps = (obj) => { if (obj) Object.keys(obj).forEach(k => maps.push(k)); };
|
||||||
|
addMaps(bg.dimensionMaps);
|
||||||
|
addMaps(bg.instancedMaps);
|
||||||
|
addMaps(bg.singleServerMaps);
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
maps.map(m => fetch(`/api/director/server_set_scale/${encodeURIComponent(m)}`).then(r => r.json()))
|
||||||
|
);
|
||||||
|
maps.forEach((m, i) => {
|
||||||
|
const r = results[i];
|
||||||
|
scaleData[m] = (r.status === 'fulfilled') ? r.value : { replicas: 0, partitions: [] };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function updateStats() {
|
function updateStats() {
|
||||||
const t = calcTotals();
|
const t = calcTotals();
|
||||||
document.getElementById('stat-players').textContent = t.total;
|
document.getElementById('stat-players').textContent = t.total;
|
||||||
@@ -301,6 +318,13 @@ function updateMapCards() {
|
|||||||
const nameSpan = summaryParts[i].querySelector('.name');
|
const nameSpan = summaryParts[i].querySelector('.name');
|
||||||
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
|
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const repInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||||
|
if (repInput) {
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
|
repInput.value = sc.replicas;
|
||||||
|
repInput.max = sc.partitions.length || 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,7 +405,7 @@ function renderMaps() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildMapCard(mapName, mapData, type) {
|
function buildMapCard(mapName, mapData, type) {
|
||||||
const cfg = mapData.cfg || {};
|
const cfg = { ...(mapData.cfg || {}), ...(mapData.webOverrideCfg || {}) };
|
||||||
let serversHtml = '';
|
let serversHtml = '';
|
||||||
let configHtml = '';
|
let configHtml = '';
|
||||||
let summaryHtml = '';
|
let summaryHtml = '';
|
||||||
@@ -505,6 +529,7 @@ function buildDimensionConfig(mapName, cfg) {
|
|||||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||||
const phCap = cfg.playerHardCap ?? '';
|
const phCap = cfg.playerHardCap ?? '';
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
return `
|
return `
|
||||||
<div class="config-row">
|
<div class="config-row">
|
||||||
<div class="config-field">
|
<div class="config-field">
|
||||||
@@ -527,6 +552,10 @@ function buildDimensionConfig(mapName, cfg) {
|
|||||||
<label>Scale Throttle (s)</label>
|
<label>Scale Throttle (s)</label>
|
||||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="config-field">
|
||||||
|
<label>Replicas</label>
|
||||||
|
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||||
|
</div>
|
||||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
|
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
|
||||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -539,6 +568,7 @@ function buildInstancedConfig(mapName, cfg) {
|
|||||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||||
const phCap = cfg.playerHardCap ?? '';
|
const phCap = cfg.playerHardCap ?? '';
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
return `
|
return `
|
||||||
<div class="config-row">
|
<div class="config-row">
|
||||||
<div class="config-field">
|
<div class="config-field">
|
||||||
@@ -561,6 +591,10 @@ function buildInstancedConfig(mapName, cfg) {
|
|||||||
<label>Scale Throttle (s)</label>
|
<label>Scale Throttle (s)</label>
|
||||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="config-field">
|
||||||
|
<label>Replicas</label>
|
||||||
|
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||||
|
</div>
|
||||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
|
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
|
||||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -625,23 +659,45 @@ async function applyConfig(mapName, type, btn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/update_config', {
|
const resp = await csrfFetch('/api/director/update_config', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
btn.classList.remove('applying');
|
btn.classList.remove('applying');
|
||||||
btn.classList.add('applied');
|
btn.classList.add('applied');
|
||||||
btn.textContent = 'Applied!';
|
btn.textContent = 'Applied!';
|
||||||
setTimeout(() => {
|
btn.disabled = false;
|
||||||
btn.classList.remove('applied');
|
|
||||||
btn.textContent = 'Apply';
|
const replicasInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||||
btn.disabled = false;
|
if (replicasInput && type !== 'single') {
|
||||||
}, 2000);
|
const sc = scaleData[mapName] || { partitions: [], replicas: 1 };
|
||||||
|
const newReplicas = parseInt(replicasInput.value) || 1;
|
||||||
|
if (newReplicas !== sc.replicas) {
|
||||||
|
const partInput = document.getElementById(`cfg-${mapName}-partitions`);
|
||||||
|
let partitions = sc.partitions;
|
||||||
|
if (partInput) {
|
||||||
|
try { partitions = JSON.parse('[' + partInput.value + ']'); } catch(_){}
|
||||||
|
}
|
||||||
|
csrfFetch(`/api/director/server_set_scale/${encodeURIComponent(mapName)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ replicas: newReplicas, partitions: partitions })
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => { btn.textContent = 'Apply'; btn.classList.remove('applied'); loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
btn.classList.remove('applying');
|
btn.classList.remove('applying');
|
||||||
btn.textContent = 'Failed';
|
btn.textContent = 'Failed';
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Config apply error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
|
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -650,15 +706,23 @@ async function clearConfig(mapName, btn) {
|
|||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
btn.textContent = 'Clearing...';
|
btn.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/clear_config', {
|
const resp = await csrfFetch('/api/director/clear_config', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'text/plain' },
|
||||||
body: mapName
|
body: mapName
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
btn.textContent = 'Cleared!';
|
btn.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
btn.disabled = false;
|
||||||
|
setTimeout(() => { btn.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
btn.textContent = 'Failed';
|
btn.textContent = 'Failed';
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Config clear error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
|
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -671,17 +735,24 @@ document.getElementById('btn-apply-world')?.addEventListener('click', async func
|
|||||||
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
|
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/character_transfer', {
|
const resp = await csrfFetch('/api/director/character_transfer', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
|
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
|
||||||
this.textContent = 'Applied!';
|
this.textContent = 'Applied!';
|
||||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Apply'; }, 2000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Apply'; this.disabled = false;
|
this.textContent = 'Apply'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -691,12 +762,19 @@ document.getElementById('btn-clear-world')?.addEventListener('click', async func
|
|||||||
this.textContent = 'Clearing...';
|
this.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
|
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
|
||||||
this.textContent = 'Cleared!';
|
this.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Clear'; this.disabled = false;
|
this.textContent = 'Clear'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -716,12 +794,18 @@ document.getElementById('btn-apply-transfer')?.addEventListener('click', async f
|
|||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
|
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
|
||||||
this.textContent = 'Applied!';
|
this.textContent = 'Applied!';
|
||||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Apply'; this.disabled = false;
|
this.textContent = 'Apply'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -731,12 +815,19 @@ document.getElementById('btn-clear-transfer')?.addEventListener('click', async f
|
|||||||
this.textContent = 'Clearing...';
|
this.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
|
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
|
||||||
this.textContent = 'Cleared!';
|
this.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Clear'; this.disabled = false;
|
this.textContent = 'Clear'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,9 @@
|
|||||||
<span id="view-mode-badge" class="badge">View Mode</span>
|
<span id="view-mode-badge" class="badge">View Mode</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="view-actions">
|
<div class="view-actions">
|
||||||
|
<button id="dl-btn" class="view-btn" onclick="downloadFile()">Download</button>
|
||||||
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
|
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
|
||||||
|
<button id="delete-btn" class="view-btn danger" onclick="deleteViewFile()">Delete</button>
|
||||||
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</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>
|
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -106,6 +108,53 @@ function cancelEdit() {
|
|||||||
badge.classList.remove('edit');
|
badge.classList.remove('edit');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function deleteViewFile() {
|
||||||
|
const name = filePath.split('/').pop();
|
||||||
|
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('path', filePath);
|
||||||
|
const resp = await csrfFetch('/api/files/delete', { method: 'POST', body: form });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.success) {
|
||||||
|
window.close();
|
||||||
|
} else {
|
||||||
|
document.getElementById('view-error').textContent = 'Delete failed: ' + (data.error || 'Unknown');
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('view-error').textContent = 'Delete failed: ' + e.message;
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile() {
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('path', filePath);
|
||||||
|
const resp = await csrfFetch('/api/files/download', { method: 'POST', body: form });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (!data.success) {
|
||||||
|
document.getElementById('view-error').textContent = 'Error: ' + (data.error || 'Download failed');
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const byteChars = atob(data.content);
|
||||||
|
const bytes = new Uint8Array(byteChars.length);
|
||||||
|
for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i);
|
||||||
|
const blob = new Blob([bytes]);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url; a.download = data.filename;
|
||||||
|
document.body.appendChild(a); a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('view-error').textContent = 'Request failed: ' + e.message;
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveFile() {
|
async function saveFile() {
|
||||||
const saveBtn = document.getElementById('save-btn');
|
const saveBtn = document.getElementById('save-btn');
|
||||||
const success = document.getElementById('view-success');
|
const success = document.getElementById('view-success');
|
||||||
|
|||||||
+267
-129
@@ -3,49 +3,79 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>File Browser</h1>
|
<h1>File Manager</h1>
|
||||||
<p>Browse server files via SSH</p>
|
<p>Browse, edit, upload, and download server files</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="fm-layout">
|
||||||
<div class="card-body">
|
<div class="fm-panel">
|
||||||
<div class="fb-toolbar">
|
<div class="fm-toolbar">
|
||||||
<div class="fb-breadcrumb" id="fb-breadcrumb"></div>
|
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
||||||
<div class="fb-actions">
|
<option value="">Loading...</option>
|
||||||
<button id="fb-refresh-btn" class="fb-btn">Refresh</button>
|
</select>
|
||||||
</div>
|
<span style="flex:1;"></span>
|
||||||
|
<input type="file" id="fm-upload-input" style="display:none;" onchange="uploadFile()">
|
||||||
|
<button class="fm-btn" onclick="document.getElementById('fm-upload-input').click()">⇪ Upload</button>
|
||||||
|
<button class="fm-btn" onclick="loadFiles(currentPath)">↻ Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="fb-error" class="error-banner danger" style="display:none;"></div>
|
<div class="fm-breadcrumb" id="fm-breadcrumb"></div>
|
||||||
<div id="fb-file-list" class="fb-file-list"></div>
|
<div id="fm-error" class="error-banner danger" style="display:none;"></div>
|
||||||
|
<div id="fm-file-list" class="fm-file-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="fm-viewer" id="fm-viewer">
|
||||||
|
<div id="fm-viewer-empty" class="fm-viewer-empty">Select a file to view or edit</div>
|
||||||
|
<div id="fm-viewer-toolbar" class="fm-viewer-toolbar" style="display:none;">
|
||||||
|
<span id="fm-viewer-name" style="font-size:13px;color:var(--text);"></span>
|
||||||
|
<span style="flex:1;"></span>
|
||||||
|
<button class="fm-btn" onclick="toggleEdit()" id="fm-edit-btn">✎ Edit</button>
|
||||||
|
<button class="fm-btn" onclick="saveFile()" id="fm-save-btn" style="display:none;">💾 Save</button>
|
||||||
|
<button class="fm-btn" onclick="cancelEdit()" id="fm-cancel-btn" style="display:none;">Cancel</button>
|
||||||
|
<button class="fm-btn" onclick="downloadCurrent()">📥 Download</button>
|
||||||
|
<button class="fm-btn danger" onclick="deleteCurrent()">🗑 Delete</button>
|
||||||
|
</div>
|
||||||
|
<pre id="fm-viewer-content" class="fm-viewer-content" style="display:none;"></pre>
|
||||||
|
<textarea id="fm-editor-content" class="fm-editor-content" style="display:none;" spellcheck="false"></textarea>
|
||||||
|
<div id="fm-viewer-status" class="error-banner success" style="display:none;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.fb-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 6px; margin-bottom: 12px; }
|
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
|
||||||
.fb-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
|
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
|
||||||
.fb-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; font-size: 13px; }
|
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
|
||||||
.fb-breadcrumb span:hover { text-decoration: underline; }
|
.fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
||||||
.fb-breadcrumb .sep { color: var(--text-muted); cursor: default; font-size: 11px; }
|
.fm-btn:hover { background: var(--bg-hover); }
|
||||||
.fb-breadcrumb .sep:hover { text-decoration: none; }
|
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
|
||||||
.fb-breadcrumb .current { color: var(--text); cursor: default; }
|
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
|
||||||
.fb-breadcrumb .current:hover { text-decoration: none; }
|
.fm-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; }
|
||||||
.fb-actions { display: flex; gap: 8px; }
|
.fm-breadcrumb span:hover { text-decoration: underline; }
|
||||||
.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; }
|
.fm-breadcrumb .sep { color: var(--text-muted); cursor: default; }
|
||||||
.fb-btn:hover { background: var(--bg-hover); }
|
.fm-breadcrumb .sep:hover { text-decoration: none; }
|
||||||
.fb-file-list { }
|
.fm-breadcrumb .current { color: var(--text); cursor: default; }
|
||||||
.fb-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; }
|
.fm-breadcrumb .current:hover { text-decoration: none; }
|
||||||
.fb-item:hover { background: var(--bg-hover); }
|
.fm-file-list { flex: 1; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; }
|
||||||
.fb-item:last-child { border-bottom: none; }
|
.fm-item { display: flex; align-items: center; padding: 6px 10px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 12px; }
|
||||||
.fb-icon { width: 24px; text-align: center; margin-right: 8px; font-size: 16px; }
|
.fm-item:hover { background: var(--bg-hover); }
|
||||||
.fb-icon.dir { color: var(--accent); }
|
.fm-item.selected { background: var(--bg-hover); border-left: 3px solid var(--primary); }
|
||||||
.fb-name { flex: 1; font-size: 13px; }
|
.fm-item:last-child { border-bottom: none; }
|
||||||
.fb-name.dir { color: var(--accent); font-weight: 500; cursor: pointer; }
|
.fm-icon { width: 20px; text-align: center; margin-right: 6px; font-size: 14px; flex-shrink: 0; }
|
||||||
.fb-name.file { cursor: pointer; }
|
.fm-icon.dir { color: var(--accent); }
|
||||||
.fb-name:hover { text-decoration: underline; }
|
.fm-fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.fb-size { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 70px; text-align: right; }
|
.fm-fname.dir { color: var(--accent); font-weight: 500; }
|
||||||
.fb-date { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 130px; }
|
.fm-fsize { color: var(--text-muted); font-size: 11px; margin-left: 8px; flex-shrink: 0; }
|
||||||
.fb-perms { color: var(--text-muted); font-size: 11px; font-family: monospace; margin-right: 12px; min-width: 80px; }
|
.fm-delete-btn { padding: 2px 6px; background: none; border: none; color: var(--danger); cursor: pointer; font-size: 13px; flex-shrink: 0; }
|
||||||
.fb-empty { padding: 20px; text-align: center; color: var(--text-muted); }
|
.fm-delete-btn:hover { background: var(--bg-hover); border-radius: 3px; }
|
||||||
|
.fm-empty { padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px; }
|
||||||
|
.fm-viewer { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 6px; min-height: 0; }
|
||||||
|
.fm-viewer-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--border); background: var(--bg-hover); border-radius: 6px 6px 0 0; }
|
||||||
|
.fm-viewer-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 14px; }
|
||||||
|
.fm-viewer-content { flex: 1; margin: 0; padding: 12px; overflow: auto; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-all; background: var(--bg); color: var(--text); border: none; border-radius: 0 0 6px 6px; }
|
||||||
|
.fm-editor-content { flex: 1; padding: 12px; background: var(--bg); color: var(--text); border: none; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; resize: none; outline: none; border-radius: 0 0 6px 6px; }
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.fm-layout { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
|
||||||
|
.fm-viewer { min-height: 300px; }
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -53,118 +83,226 @@
|
|||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script>
|
<script>
|
||||||
let currentPath = '/srv';
|
let currentPath = '/srv';
|
||||||
|
let currentFile = null;
|
||||||
|
let currentPod = '';
|
||||||
|
let originalContent = '';
|
||||||
|
|
||||||
function formatSize(sizeStr) {
|
async function loadPods() {
|
||||||
if (!sizeStr || sizeStr === '-') return '';
|
const sel = document.getElementById('fm-pod-select');
|
||||||
const bytes = parseInt(sizeStr);
|
try {
|
||||||
if (isNaN(bytes)) return sizeStr;
|
const r = await csrfFetch('/api/files/pods');
|
||||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
const d = await r.json();
|
||||||
let i = 0;
|
sel.innerHTML = '';
|
||||||
let size = bytes;
|
if (d.success && d.pods) {
|
||||||
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
|
d.pods.forEach(p => { const o = document.createElement('option'); o.value = p; o.textContent = p; sel.appendChild(o); });
|
||||||
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
|
}
|
||||||
|
// Default to fb-deploy pod if available
|
||||||
|
const fbOpt = Array.from(sel.options).find(o => o.value.includes('fb-deploy'));
|
||||||
|
if (fbOpt) { fbOpt.selected = true; currentPod = fbOpt.value; }
|
||||||
|
else if (sel.options.length) { sel.options[0].selected = true; currentPod = sel.options[0].value; }
|
||||||
|
} catch(e) { sel.innerHTML = '<option>Error loading pods</option>'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectPod() {
|
||||||
|
currentPod = document.getElementById('fm-pod-select').value;
|
||||||
|
currentFile = null;
|
||||||
|
hideViewer();
|
||||||
|
loadFiles(currentPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildForm(path) {
|
||||||
|
const f = new FormData();
|
||||||
|
f.append('path', path);
|
||||||
|
if (currentPod) f.append('pod', currentPod);
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(s) {
|
||||||
|
if (!s || s === '-') return '';
|
||||||
|
const b = parseInt(s); if (isNaN(b)) return s;
|
||||||
|
const u = ['B','KB','MB','GB','TB']; let i = 0, sz = b;
|
||||||
|
while (sz >= 1024 && i < u.length-1) { sz /= 1024; i++; }
|
||||||
|
return sz.toFixed(i===0?0:1) + ' ' + u[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderBreadcrumb(path) {
|
function renderBreadcrumb(path) {
|
||||||
const parts = path.split('/').filter(Boolean);
|
const p = path.split('/').filter(Boolean);
|
||||||
let html = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
let h = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
||||||
let buildPath = '';
|
let b = '';
|
||||||
for (let i = 0; i < parts.length; i++) {
|
for (let i=0;i<p.length;i++) {
|
||||||
buildPath += '/' + parts[i];
|
b += '/'+p[i];
|
||||||
const isLast = i === parts.length - 1;
|
h += i===p.length-1
|
||||||
if (isLast) {
|
? '<span class="sep">/</span><span class="current">'+p[i]+'</span>'
|
||||||
html += `<span class="sep">/</span><span class="current">${parts[i]}</span>`;
|
: '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
|
||||||
} else {
|
|
||||||
html += `<span class="sep">/</span><span onclick="loadFiles('${buildPath.replace(/'/g, "\\'")}')">${parts[i]}</span>`;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return html;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function selectFile(path) { currentFile = path; }
|
||||||
|
|
||||||
async function loadFiles(path) {
|
async function loadFiles(path) {
|
||||||
currentPath = path;
|
currentPath = path; currentFile = null;
|
||||||
const list = document.getElementById('fb-file-list');
|
document.getElementById('fm-error').style.display = 'none';
|
||||||
const error = document.getElementById('fb-error');
|
document.getElementById('fm-breadcrumb').innerHTML = renderBreadcrumb(path);
|
||||||
const breadcrumb = document.getElementById('fb-breadcrumb');
|
const list = document.getElementById('fm-file-list');
|
||||||
error.style.display = 'none';
|
list.innerHTML = '<div class="fm-empty">Loading...</div>';
|
||||||
list.innerHTML = '<div class="fb-empty">Loading...</div>';
|
|
||||||
breadcrumb.innerHTML = renderBreadcrumb(path);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const form = new FormData();
|
const f = buildForm(path);
|
||||||
form.append('path', path);
|
const r = await csrfFetch('/api/files/list',{method:'POST',body:f});
|
||||||
const resp = await csrfFetch('/api/files/list', { method: 'POST', body: form });
|
const d = await r.json();
|
||||||
const data = await resp.json();
|
if (!d.success) { list.innerHTML = ''; showErr(d.error); return; }
|
||||||
if (!data.success) {
|
const files = (d.files||[]).sort((a,b)=>a.is_dir!==b.is_dir?a.is_dir?-1:1:a.name.localeCompare(b.name));
|
||||||
list.innerHTML = '';
|
if (!files.length) { list.innerHTML = '<div class="fm-empty">Empty directory</div>'; return; }
|
||||||
error.textContent = 'Error: ' + (data.error || 'Failed to list directory');
|
let h = '';
|
||||||
error.style.display = 'block';
|
for (const x of files) {
|
||||||
return;
|
const fp = (path==='/'?'':path)+'/'+x.name;
|
||||||
}
|
const sp = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
const files = data.files || [];
|
const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
if (files.length === 0) {
|
const icon = x.is_dir ? '📁' : getIcon(x.name);
|
||||||
list.innerHTML = '<div class="fb-empty">Empty directory</div>';
|
const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
|
||||||
return;
|
h += `<div class="fm-item" onclick="${action}">
|
||||||
}
|
<span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
|
||||||
const sorted = files.sort((a, b) => {
|
<span class="fm-fname ${x.is_dir?'dir':''}">${x.name}</span>
|
||||||
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
|
<span class="fm-fsize">${formatSize(x.size)}</span>
|
||||||
return a.name.localeCompare(b.name);
|
<button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">🗑</button>
|
||||||
});
|
|
||||||
let html = '';
|
|
||||||
for (const f of sorted) {
|
|
||||||
const icon = f.is_dir ? '📁' : 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>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
list.innerHTML = html;
|
list.innerHTML = h;
|
||||||
} catch (e) {
|
} catch(e) { list.innerHTML = ''; showErr(e.message); }
|
||||||
list.innerHTML = '';
|
|
||||||
error.textContent = 'Request failed: ' + e.message;
|
|
||||||
error.style.display = 'block';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getFileIcon(name) {
|
function getIcon(name) {
|
||||||
|
const icons = {log:'📝',txt:'📄',ini:'⚙',cfg:'⚙',json:'𞇤',xml:'📄',yaml:'📄',yml:'📄',sh:'⚙',ps1:'⚙',bat:'⚙',cmd:'⚙',zip:'📦',gz:'📦',tar:'📦',sql:'🗃',db:'🗃',png:'🌄',jpg:'🌄',jpeg:'🌄',gif:'🌄',svg:'🌄',pdf:'📖',md:'📖',html:'🌐',css:'🎨',js:'📜',py:'📜'};
|
||||||
|
return icons[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'];
|
||||||
|
|
||||||
|
function openFile(path, name) {
|
||||||
|
currentFile = path;
|
||||||
const ext = name.split('.').pop().toLowerCase();
|
const ext = name.split('.').pop().toLowerCase();
|
||||||
const icons = {
|
if (!textExts.includes(ext)) { downloadFile(path); return; }
|
||||||
log: '📝', txt: '📄', ini: '⚙', cfg: '⚙',
|
|
||||||
json: '𞇤', xml: '📄', yaml: '📄', yml: '📄',
|
document.getElementById('fm-viewer-empty').style.display = 'none';
|
||||||
sh: '⚙', ps1: '⚙', bat: '⚙', cmd: '⚙',
|
document.getElementById('fm-viewer-status').style.display = 'none';
|
||||||
zip: '📦', gz: '📦', tar: '📦',
|
document.getElementById('fm-viewer-content').style.display = 'block';
|
||||||
sql: '🗃', db: '🗃', sqlite: '🗃',
|
document.getElementById('fm-editor-content').style.display = 'none';
|
||||||
png: '🌄', jpg: '🌄', jpeg: '🌄', gif: '🌄', svg: '🌄',
|
document.getElementById('fm-edit-btn').style.display = 'inline-block';
|
||||||
pdf: '📖',
|
document.getElementById('fm-save-btn').style.display = 'none';
|
||||||
md: '📖', html: '🌐', css: '🎨', js: '📜',
|
document.getElementById('fm-cancel-btn').style.display = 'none';
|
||||||
py: '📜',
|
document.getElementById('fm-viewer-toolbar').style.display = 'flex';
|
||||||
};
|
document.getElementById('fm-viewer-name').textContent = name;
|
||||||
return icons[ext] || '📄';
|
|
||||||
|
const content = document.getElementById('fm-viewer-content');
|
||||||
|
content.textContent = 'Loading...';
|
||||||
|
fetch('/api/files/view?path=' + encodeURIComponent(path) + '&pod=' + encodeURIComponent(currentPod))
|
||||||
|
.then(r=>r.json()).then(d=>{
|
||||||
|
if(!d.success){content.textContent='Error: '+(d.error||'Load failed');return;}
|
||||||
|
originalContent = d.content;
|
||||||
|
content.textContent = d.content;
|
||||||
|
}).catch(e=>{content.textContent='Error: '+e.message;});
|
||||||
|
|
||||||
|
// Highlight selected file
|
||||||
|
document.querySelectorAll('.fm-item').forEach(el=>el.classList.remove('selected'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function viewFile(path, name) {
|
function toggleEdit() {
|
||||||
const ext = name.split('.').pop().toLowerCase();
|
document.getElementById('fm-viewer-content').style.display = 'none';
|
||||||
const textExts = ['log', 'txt', 'ini', 'cfg', 'json', 'xml', 'yaml', 'yml', 'sh', 'ps1', 'bat', 'cmd', 'md', 'html', 'css', 'js', 'py', 'conf', 'env'];
|
document.getElementById('fm-editor-content').style.display = 'block';
|
||||||
if (textExts.includes(ext)) {
|
document.getElementById('fm-editor-content').value = originalContent;
|
||||||
window.open(`/files/view?path=${encodeURIComponent(path)}`, '_blank');
|
document.getElementById('fm-editor-content').focus();
|
||||||
} else {
|
document.getElementById('fm-edit-btn').style.display = 'none';
|
||||||
alert('File preview is only available for text files. Download via SSH to view this file.');
|
document.getElementById('fm-save-btn').style.display = 'inline-block';
|
||||||
}
|
document.getElementById('fm-cancel-btn').style.display = 'inline-block';
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('fb-refresh-btn')?.addEventListener('click', () => loadFiles(currentPath));
|
function cancelEdit() {
|
||||||
|
document.getElementById('fm-editor-content').style.display = 'none';
|
||||||
|
document.getElementById('fm-viewer-content').style.display = 'block';
|
||||||
|
document.getElementById('fm-edit-btn').style.display = 'inline-block';
|
||||||
|
document.getElementById('fm-save-btn').style.display = 'none';
|
||||||
|
document.getElementById('fm-cancel-btn').style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveFile() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
const content = document.getElementById('fm-editor-content').value;
|
||||||
|
const btn = document.getElementById('fm-save-btn');
|
||||||
|
btn.textContent = 'Saving...'; btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const f = buildForm(currentFile); f.append('content', content);
|
||||||
|
const r = await csrfFetch('/api/files/save',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(!d.success){showErr(d.error);return;}
|
||||||
|
originalContent = content;
|
||||||
|
document.getElementById('fm-viewer-content').textContent = content;
|
||||||
|
cancelEdit();
|
||||||
|
document.getElementById('fm-viewer-status').textContent = 'Saved'; document.getElementById('fm-viewer-status').style.display='block';
|
||||||
|
setTimeout(()=>document.getElementById('fm-viewer-status').style.display='none',2000);
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
btn.textContent = '💾 Save'; btn.disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadCurrent() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
downloadFile(currentFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCurrent() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
const name = currentFile.split('/').pop();
|
||||||
|
if (!confirm('Delete "'+name+'"? This cannot be undone.')) return;
|
||||||
|
try {
|
||||||
|
const f = buildForm(currentFile);
|
||||||
|
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';loadFiles(currentPath);}
|
||||||
|
else showErr(d.error||'Delete failed');
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadFile() {
|
||||||
|
const input = document.getElementById('fm-upload-input');
|
||||||
|
const file = input.files[0]; if(!file)return;
|
||||||
|
const f = buildForm(currentPath); f.append('file',file);
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/files/upload',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){input.value='';loadFiles(currentPath);}
|
||||||
|
else showErr('Upload: '+(d.error||'Unknown'));
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile(path) {
|
||||||
|
try {
|
||||||
|
const f = buildForm(path);
|
||||||
|
const r = await csrfFetch('/api/files/download',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(!d.success){alert('Download failed: '+(d.error||'Unknown'));return;}
|
||||||
|
const chars=atob(d.content); const bytes=new Uint8Array(chars.length);
|
||||||
|
for(let i=0;i<chars.length;i++)bytes[i]=chars.charCodeAt(i);
|
||||||
|
const blob=new Blob([bytes]),url=URL.createObjectURL(blob);
|
||||||
|
const a=document.createElement('a');a.href=url;a.download=d.filename;
|
||||||
|
document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);
|
||||||
|
} catch(e) { alert('Download failed: '+e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteFile(path,name) {
|
||||||
|
if(!confirm('Delete "'+name+'"? This cannot be undone.'))return;
|
||||||
|
try {
|
||||||
|
const f = buildForm(path);
|
||||||
|
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){ if(currentFile===path){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';} loadFiles(currentPath); }
|
||||||
|
else showErr(d.error||'Delete failed');
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showErr(msg) { const e=document.getElementById('fm-error');e.textContent='Error: '+msg;e.style.display='block'; }
|
||||||
|
function hideErr() { document.getElementById('fm-error').style.display='none'; }
|
||||||
|
function hideViewer() { document.getElementById('fm-viewer-toolbar').style.display='none'; document.getElementById('fm-viewer-content').style.display='none'; document.getElementById('fm-editor-content').style.display='none'; document.getElementById('fm-viewer-empty').style.display='flex'; }
|
||||||
|
|
||||||
|
loadPods();
|
||||||
loadFiles('/srv');
|
loadFiles('/srv');
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
+275
-658
File diff suppressed because it is too large.
Load diff
+93
-40
@@ -85,14 +85,28 @@
|
|||||||
<div class="card-header">Active Server IDs</div>
|
<div class="card-header">Active Server IDs</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
{% if active_servers %}
|
{% if active_servers %}
|
||||||
<ul style="list-style:none;">
|
<div class="table-wrap">
|
||||||
{% for s in active_servers %}
|
<table>
|
||||||
<li style="padding:4px 0;font-family:monospace;font-size:12px;">
|
<thead><tr><th>Server ID</th><th>Map</th><th>Actions</th></tr></thead>
|
||||||
<span style="font-weight:600;">{{ s.server_id }}</span>
|
<tbody>
|
||||||
{% if s.map %} — <span style="color:var(--primary);">{{ s.map }}</span>{% endif %}
|
{% for s in active_servers %}
|
||||||
</li>
|
<tr>
|
||||||
{% endfor %}
|
<td style="font-family:monospace;font-size:12px;font-weight:600;">{{ s.server_id }}</td>
|
||||||
</ul>
|
<td style="color:var(--primary);">{{ s.map or '' }}</td>
|
||||||
|
<td>
|
||||||
|
{% if s.deployment %}
|
||||||
|
<button class="partition-btn" data-deploy="{{ s.deployment }}" data-map="{{ s.server_id }}" title="Restart this server's deployment. Players on this map will disconnect briefly." style="padding:4px 12px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Restart</button>
|
||||||
|
{% elif not deployments %}
|
||||||
|
<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>
|
||||||
|
{% else %}
|
||||||
|
<span style="color:var(--text-muted);font-size:11px;">No deploy</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<div class="empty">No active servers</div>
|
<div class="empty">No active servers</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -116,7 +130,7 @@
|
|||||||
<td>{{ p.dimension_index }}</td>
|
<td>{{ p.dimension_index }}</td>
|
||||||
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
|
<td>{{ 'Yes' if p.blocked else 'No' }}</td>
|
||||||
<td>{{ p.label or '' }}</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 %}—{% endif %}</td>
|
<td>{% if p.deployment %}<div style="display:flex;gap:4px;flex-wrap:wrap;"><button class="partition-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Restart this partition's deployment. Players on this map will disconnect." style="padding:4px 10px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Restart</button><button class="partition-status-btn" data-deploy="{{ p.deployment }}" data-map="{{ p.map }}" title="Show rollout status for this partition's deployment." style="padding:4px 10px;background:#3498db;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:11px;">Status</button></div>{% elif not deployments %}<span style="color:var(--text-muted);font-size:11px;">K8s offline</span>{% else %}<span style="color:var(--text-muted);font-size:11px;">No deploy</span>{% endif %}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan="7" class="empty">No partitions found</td></tr>
|
<tr><td colspan="7" class="empty">No partitions found</td></tr>
|
||||||
@@ -137,6 +151,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
{% if deploys_ok %}
|
{% if deploys_ok %}
|
||||||
|
<div style="margin-bottom:10px;padding:10px;background:var(--bg);border-radius:6px;font-size:12px;line-height:1.5;color:var(--text-light);">
|
||||||
|
<strong>Button Guide:</strong>
|
||||||
|
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e67e22;">Restart</span> — rolling restart of pods</span>
|
||||||
|
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#3498db;">Status</span> — rollout status</span>
|
||||||
|
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#e74c3c;">Scale to 0</span> — stop all pods</span>
|
||||||
|
<span style="display:inline-block;margin:0 10px 0 4px;"><span style="color:#27ae60;">Scale to 1</span> — start a pod</span>
|
||||||
|
</div>
|
||||||
<div class="table-wrap">
|
<div class="table-wrap">
|
||||||
<table>
|
<table>
|
||||||
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
|
<thead><tr><th>Deployment</th><th>Actions</th></tr></thead>
|
||||||
@@ -145,10 +166,10 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
|
<td style="font-family:monospace;font-size:13px;">{{ d.replace('deployment.apps/','') }}</td>
|
||||||
<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="restart" title="Performs a rolling restart of this deployment's pods. Players will disconnect briefly." 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="status" title="Show rollout status: whether the deployment is successfully rolled out, pending, or failed." 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_0" title="Scale to 0 replicas. Stops all pods for this deployment. Use to shut down a server." 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>
|
<button class="btn-action" data-deploy="{{ d }}" data-action="scale_1" title="Scale to 1 replica. Starts a single pod. Use to bring a stopped server back online." style="padding:4px 12px;background:#27ae60;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Scale to 1</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -161,12 +182,12 @@
|
|||||||
<code>$env:TEMP\dune-awakening-server-sshKey</code> and the VM is reachable.
|
<code>$env:TEMP\dune-awakening-server-sshKey</code> and the VM is reachable.
|
||||||
</p>
|
</p>
|
||||||
{% if ssh_error %}
|
{% if ssh_error %}
|
||||||
<pre style="background:#1a1a2e;color:#e74c3c;padding:12px;border-radius:6px;font-size:12px;margin-top:8px;">{{ ssh_error }}</pre>
|
<pre style="background:var(--bg);color:var(--danger);padding:12px;border-radius:6px;font-size:12px;margin-top:8px;">{{ ssh_error }}</pre>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div id="action-output" style="margin-top:16px;display:none;">
|
<div id="action-output" style="margin-top:16px;display:none;">
|
||||||
<div class="card-header">Command Output</div>
|
<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>
|
<pre id="action-output-text" style="background:var(--bg);color:var(--text);padding:16px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;margin-top:8px;"></pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -185,7 +206,7 @@
|
|||||||
<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>
|
<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>
|
||||||
<div id="bg-status-output">
|
<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>
|
<pre id="bg-status-text" style="background:var(--bg);color:var(--text);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>
|
||||||
</div>
|
</div>
|
||||||
@@ -195,7 +216,7 @@
|
|||||||
<div class="card-body">
|
<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>
|
<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;">
|
<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>
|
<pre id="pods-text" style="background:var(--bg);color:var(--text);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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -206,8 +227,8 @@
|
|||||||
<span id="debug-status" style="font-size:12px;color:var(--text-muted);">Loading...</span>
|
<span id="debug-status" style="font-size:12px;color:var(--text-muted);">Loading...</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body" id="debug-section">
|
<div class="card-body" id="debug-section">
|
||||||
<div style="margin-bottom:12px;padding:12px;background:#1a1a2e;border-radius:6px;font-size:13px;line-height:1.6;color:#e0d5c7;">
|
<div style="margin-bottom:12px;padding:12px;background:var(--bg);border-radius:6px;font-size:13px;line-height:1.6;color:var(--text);">
|
||||||
<strong style="color:#9b59b6;">📝 Verbose Logging:</strong> Enable to log detailed information about SSH commands, API requests, database queries, and service connections.
|
<strong style="color:var(--primary);">📝 Verbose Logging:</strong> Enable to log detailed information about SSH commands, API requests, database queries, and service connections.
|
||||||
Logs are written to <code>logs/debug.log</code>. Sanitizes sensitive data (passwords, tokens) automatically.
|
Logs are written to <code>logs/debug.log</code>. Sanitizes sensitive data (passwords, tokens) automatically.
|
||||||
</div>
|
</div>
|
||||||
<div style="display:flex;align-items:center;gap:16px;">
|
<div style="display:flex;align-items:center;gap:16px;">
|
||||||
@@ -227,16 +248,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="card-body" id="audit-section">
|
<div class="card-body" id="audit-section">
|
||||||
<div style="margin-bottom:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
|
<div style="margin-bottom:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
|
||||||
<input type="text" id="audit-search" placeholder="Filter by action..." style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;width:180px;">
|
<input type="text" id="audit-search" placeholder="Filter by action..." style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;width:180px;">
|
||||||
<input type="text" id="audit-user" placeholder="Filter by user..." style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;width:140px;">
|
<input type="text" id="audit-user" placeholder="Filter by user..." style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;width:140px;">
|
||||||
<select id="audit-severity" style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;">
|
<select id="audit-severity" style="padding:8px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;">
|
||||||
<option value="">All Severities</option>
|
<option value="">All Severities</option>
|
||||||
<option value="info">Info</option>
|
<option value="info">Info</option>
|
||||||
<option value="warning">Warning</option>
|
<option value="warning">Warning</option>
|
||||||
<option value="error">Error</option>
|
<option value="error">Error</option>
|
||||||
</select>
|
</select>
|
||||||
<button onclick="loadAuditLogs()" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
|
<button onclick="loadAuditLogs()" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
|
||||||
<button onclick="refreshAuditLogs()" style="padding:8px 16px;background:#333;color:#e0d5c7;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh</button>
|
<button onclick="refreshAuditLogs()" style="padding:8px 16px;background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;cursor:pointer;font-size:13px;">Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
<div style="margin-bottom:12px;display:flex;gap:16px;font-size:12px;color:var(--text-muted);">
|
<div style="margin-bottom:12px;display:flex;gap:16px;font-size:12px;color:var(--text-muted);">
|
||||||
<span>Total: <strong id="audit-total">0</strong></span>
|
<span>Total: <strong id="audit-total">0</strong></span>
|
||||||
@@ -246,13 +267,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<div id="audit-logs-container" style="max-height:300px;overflow-y:auto;">
|
<div id="audit-logs-container" style="max-height:300px;overflow-y:auto;">
|
||||||
<table style="width:100%;border-collapse:collapse;font-size:12px;">
|
<table style="width:100%;border-collapse:collapse;font-size:12px;">
|
||||||
<thead style="position:sticky;top:0;background:#2a2a3e;">
|
<thead style="position:sticky;top:0;background:var(--table-header);">
|
||||||
<tr style="text-align:left;color:var(--text-muted);">
|
<tr style="text-align:left;color:var(--text-muted);">
|
||||||
<th style="padding:8px;border-bottom:1px solid #333;">Time</th>
|
<th style="padding:8px;border-bottom:1px solid var(--border);">Time</th>
|
||||||
<th style="padding:8px;border-bottom:1px solid #333;">Action</th>
|
<th style="padding:8px;border-bottom:1px solid var(--border);">Action</th>
|
||||||
<th style="padding:8px;border-bottom:1px solid #333;">User</th>
|
<th style="padding:8px;border-bottom:1px solid var(--border);">User</th>
|
||||||
<th style="padding:8px;border-bottom:1px solid #333;">Severity</th>
|
<th style="padding:8px;border-bottom:1px solid var(--border);">Severity</th>
|
||||||
<th style="padding:8px;border-bottom:1px solid #333;">Details</th>
|
<th style="padding:8px;border-bottom:1px solid var(--border);">Details</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="audit-logs-body">
|
<tbody id="audit-logs-body">
|
||||||
@@ -269,14 +290,14 @@
|
|||||||
<span id="fw-status-indicator" style="font-size:12px;color:var(--text-muted);">Loading...</span>
|
<span id="fw-status-indicator" style="font-size:12px;color:var(--text-muted);">Loading...</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div style="margin-bottom:12px;padding:12px;background:#1a1a2e;border-radius:6px;font-size:13px;line-height:1.6;">
|
<div style="margin-bottom:12px;padding:12px;background:var(--bg);border-radius:6px;font-size:13px;line-height:1.6;">
|
||||||
<strong style="color:#e74c3c;">Security Recommendation:</strong> The following services are exposed to the internet without authentication.
|
<strong style="color:#e74c3c;">Security Recommendation:</strong> The following services are exposed to the internet without authentication.
|
||||||
Block them so only localhost (the dashboard via SSH tunnel) can reach them.
|
Block them so only localhost (the dashboard via SSH tunnel) can reach them.
|
||||||
</div>
|
</div>
|
||||||
<div id="fw-ports-list" style="margin-bottom:16px;"></div>
|
<div id="fw-ports-list" style="margin-bottom:16px;"></div>
|
||||||
<button id="fw-btn-refresh" style="padding:8px 20px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh Status</button>
|
<button id="fw-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 id="fw-action-output" style="margin-top:12px;display:none;">
|
<div id="fw-action-output" style="margin-top:12px;display:none;">
|
||||||
<pre id="fw-action-text" style="background:#1a1a2e;color:#e0d5c7;padding:12px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;"></pre>
|
<pre id="fw-action-text" style="background:var(--bg);color:var(--text);padding:12px;border-radius:8px;font-size:12px;overflow-x:auto;white-space:pre-wrap;"></pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -339,7 +360,7 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
|
|||||||
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
|
if (!confirm(`Restart "${map}" partition (${deploy})?`)) return;
|
||||||
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
|
if (!confirm('Are you sure? Players on this map will be disconnected.')) return;
|
||||||
this.disabled = true;
|
this.disabled = true;
|
||||||
this.textContent = 'Restarting...';
|
this.textContent = 'Working...';
|
||||||
const output = document.getElementById('action-output');
|
const output = document.getElementById('action-output');
|
||||||
const outputText = document.getElementById('action-output-text');
|
const outputText = document.getElementById('action-output-text');
|
||||||
output.style.display = 'block';
|
output.style.display = 'block';
|
||||||
@@ -359,10 +380,36 @@ document.querySelectorAll('.partition-btn').forEach(btn => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('refresh-pods')?.addEventListener('click', async function() {
|
document.querySelectorAll('.partition-status-btn').forEach(btn => {
|
||||||
this.disabled = true;
|
btn.addEventListener('click', async function() {
|
||||||
this.textContent = 'Loading...';
|
const deploy = this.dataset.deploy;
|
||||||
|
const map = this.dataset.map;
|
||||||
|
const label = this.textContent.trim();
|
||||||
|
this.disabled = true;
|
||||||
|
this.textContent = 'Loading...';
|
||||||
|
const output = document.getElementById('action-output');
|
||||||
|
const outputText = document.getElementById('action-output-text');
|
||||||
|
output.style.display = 'block';
|
||||||
|
outputText.textContent = `Fetching status for ${deploy}...`;
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('deployment', deploy);
|
||||||
|
form.append('action', 'status');
|
||||||
|
const resp = await csrfFetch('/server/action', { method: 'POST', body: form });
|
||||||
|
const data = await resp.json();
|
||||||
|
outputText.textContent = data.output || (data.success ? 'No status output' : 'Failed');
|
||||||
|
} catch (e) {
|
||||||
|
outputText.textContent = 'Error: ' + e.message;
|
||||||
|
}
|
||||||
|
this.disabled = false;
|
||||||
|
this.textContent = label;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
async function refreshPods() {
|
||||||
|
const btn = document.getElementById('refresh-pods');
|
||||||
const pre = document.getElementById('pods-text');
|
const pre = document.getElementById('pods-text');
|
||||||
|
if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
|
||||||
pre.textContent = 'Fetching pod list...';
|
pre.textContent = 'Fetching pod list...';
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/server/pods');
|
const resp = await fetch('/server/pods');
|
||||||
@@ -371,9 +418,10 @@ document.getElementById('refresh-pods')?.addEventListener('click', async functio
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
pre.textContent = 'Error: ' + e.message;
|
pre.textContent = 'Error: ' + e.message;
|
||||||
}
|
}
|
||||||
this.disabled = false;
|
if (btn) { btn.disabled = false; btn.textContent = 'Refresh Pods'; }
|
||||||
this.textContent = 'Refresh Pods';
|
}
|
||||||
});
|
|
||||||
|
document.getElementById('refresh-pods')?.addEventListener('click', refreshPods);
|
||||||
|
|
||||||
async function bgAction(action, btn) {
|
async function bgAction(action, btn) {
|
||||||
const confirmMsgs = {
|
const confirmMsgs = {
|
||||||
@@ -552,7 +600,7 @@ async function loadAuditLogs(action = '', user = '', severity = '', limit = 100,
|
|||||||
const details = log.details ? JSON.stringify(log.details) : '-';
|
const details = log.details ? JSON.stringify(log.details) : '-';
|
||||||
const severityColor = log.severity === 'error' ? 'color:#e74c3c;' : (log.severity === 'warning' ? 'color:#f39c12;' : 'color:#3498db;');
|
const severityColor = log.severity === 'error' ? 'color:#e74c3c;' : (log.severity === 'warning' ? 'color:#f39c12;' : 'color:#3498db;');
|
||||||
const timestamp = log.timestamp ? log.timestamp.replace('T', ' ').substring(0, 19) : '-';
|
const timestamp = log.timestamp ? log.timestamp.replace('T', ' ').substring(0, 19) : '-';
|
||||||
return '<tr style="border-bottom:1px solid #333;">' +
|
return '<tr style="border-bottom:1px solid var(--border);">' +
|
||||||
'<td style="padding:8px;color:var(--text-muted);">' + timestamp + '</td>' +
|
'<td style="padding:8px;color:var(--text-muted);">' + timestamp + '</td>' +
|
||||||
'<td style="padding:8px;font-weight:600;">' + (log.action || '-') + '</td>' +
|
'<td style="padding:8px;font-weight:600;">' + (log.action || '-') + '</td>' +
|
||||||
'<td style="padding:8px;">' + (log.user || '-') + '</td>' +
|
'<td style="padding:8px;">' + (log.user || '-') + '</td>' +
|
||||||
@@ -603,7 +651,8 @@ debugToggle.addEventListener('change', async function() {
|
|||||||
try {
|
try {
|
||||||
const resp = await csrfFetch('/api/settings/debug', {
|
const resp = await csrfFetch('/api/settings/debug', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: { enabled: enabled }
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ enabled: enabled })
|
||||||
});
|
});
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
@@ -628,5 +677,9 @@ debugToggle.addEventListener('change', async function() {
|
|||||||
|
|
||||||
// Load debug status on page load
|
// Load debug status on page load
|
||||||
loadDebugStatus();
|
loadDebugStatus();
|
||||||
|
|
||||||
|
// Auto-load battlegroup and pods once on page load, then require manual refresh
|
||||||
|
bgRefreshStatus();
|
||||||
|
refreshPods();
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
Reference in new issue
Block a user