From 9c61e198faab2cb53a3671584f957525b48de812 Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Tue, 22 Sep 2026 10:43:27 +0100 Subject: [PATCH 1/4] v0.7.6: channel-aware self-updates with banner, preview, silence controls --- .gitignore | 4 +- VERSION | 1 + app/factory.py | 4 +- app/routes/api.py | 86 ++++++--- app/services/updater.py | 380 ++++++++++++++++++++++++++++++---------- static/style.css | 103 +++++++++++ templates/base.html | 218 +++++++++++++++++++++++ tests/test_updater.py | 156 +++++++++++++++++ 8 files changed, 838 insertions(+), 114 deletions(-) create mode 100644 VERSION create mode 100644 tests/test_updater.py diff --git a/.gitignore b/.gitignore index 0ccea9e..20617b6 100644 --- a/.gitignore +++ b/.gitignore @@ -103,8 +103,8 @@ find_*.py AI_DOCS/ AI_FULL_PROJECT_ANALYSIS_MODE/ -# Version file (generated dynamically) -VERSION +# VERSION is committed: it is the dashboard's version source of truth +# (e.g. 0.7.5-experimental). The updater reads it, never ignores it. # Security scripts (contain VM-specific configs) scripts/ diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..dab6028 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.7.6-experimental diff --git a/app/factory.py b/app/factory.py index 357192d..496b773 100644 --- a/app/factory.py +++ b/app/factory.py @@ -335,8 +335,8 @@ def create_app(settings_path=None): register_api_routes(app, services, settings) register_websocket_handlers(socketio, settings) - # Start update checker (disabled — being reworked) - # updater_svc.start_checker() + # Background update check (channel-aware releases; installing is manual only) + updater_svc.start_checker() @app.teardown_appcontext def cleanup_db(exc): diff --git a/app/routes/api.py b/app/routes/api.py index 64dcc93..756df45 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -1506,17 +1506,16 @@ def register_api_routes(app, services, settings): except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 - # Update management + # Update management (channel-aware, releases-based, never downgrades) @app.route('/api/update/status') @auth_req def api_update_status(): updater = services.get('updater') if not updater: return jsonify({'available': False}) - return jsonify({ - 'available': updater.update_available, - 'status': updater.update_status, - }) + status = updater.status() + status['success'] = True + return jsonify(status) @app.route('/api/update/apply', methods=['POST']) @auth_req @@ -1524,19 +1523,14 @@ def register_api_routes(app, services, settings): updater = services.get('updater') if not updater: return jsonify({'success': False, 'error': 'Updater not available'}) - success, message = updater.apply_update() + data = request.get_json() or {} + success, message = updater.apply_update(data.get('version')) + if audit_svc and success: + audit_svc.log('dashboard_update', + {'version': data.get('version') or 'latest'}, + user='admin', severity='warning') return jsonify({'success': success, 'message': message}) - @app.route('/api/update/test', methods=['POST']) - @auth_req - def api_update_test(): - """Force show update banner for testing.""" - updater = services.get('updater') - if updater: - updater._update_available = True - return jsonify({'success': True, 'message': 'Update banner triggered'}) - return jsonify({'success': False, 'error': 'Updater not available'}) - @app.route('/api/update/check', methods=['POST']) @auth_req def api_update_check(): @@ -1545,12 +1539,60 @@ def register_api_routes(app, services, settings): if not updater: return jsonify({'success': False, 'error': 'Updater not available'}) updater.check_for_updates() - return jsonify({ - 'available': updater.update_available, - 'status': updater.update_status, - 'local_version': updater._current_sha, - 'remote_version': updater._latest_sha, - }) + status = updater.status() + status['success'] = True + return jsonify(status) + + @app.route('/api/update/preview', methods=['POST']) + @auth_req + def api_update_preview(): + """Set an in-memory preview version to test the banner (never installable).""" + updater = services.get('updater') + if not updater: + return jsonify({'success': False, 'error': 'Updater not available'}) + data = request.get_json() or {} + try: + preview = updater.set_preview(data.get('version'), data.get('notes')) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) + return jsonify({'success': True, 'preview': preview}) + + @app.route('/api/update/preview', methods=['DELETE']) + @auth_req + def api_update_preview_clear(): + updater = services.get('updater') + if not updater: + return jsonify({'success': False, 'error': 'Updater not available'}) + updater.clear_preview() + return jsonify({'success': True}) + + @app.route('/api/update/silence', methods=['POST']) + @auth_req + def api_update_silence(): + """Silence a version, toggle permanent mute, or clear all silence.""" + updater = services.get('updater') + if not updater: + return jsonify({'success': False, 'error': 'Updater not available'}) + data = request.get_json() or {} + action = str(data.get('action') or '').strip().lower() + try: + if action == 'silence': + state = updater.silence_version(data.get('version')) + elif action == 'unsilence': + state = updater.unsilence_version(data.get('version')) + elif action == 'mute': + state = updater.set_silence_all(True) + elif action == 'unmute': + state = updater.set_silence_all(False) + elif action == 'clear': + state = updater.clear_silence() + else: + return jsonify({'success': False, + 'error': 'Unknown action (silence/unsilence/mute/unmute/clear)'}) + except Exception as e: + logger.error(f'Update silence failed: {e}') + return jsonify({'success': False, 'error': 'Could not save silence setting'}) + return jsonify({'success': True, 'silence': state}) # Audit logs from app.services.audit import AuditService diff --git a/app/services/updater.py b/app/services/updater.py index 5a42e7a..0ea31d3 100644 --- a/app/services/updater.py +++ b/app/services/updater.py @@ -1,6 +1,18 @@ -"""Update service - checks GitHub for new releases and applies updates""" +"""Update service - channel-aware self updates from GitHub Releases. + +Version source of truth: the committed VERSION file (e.g. ``0.7.5`` for +stable, ``0.7.5-experimental`` for experimental). The channel is the suffix. + +Rules (all enforced server-side): +- experimental installs track ``vX.Y.Z-experimental`` releases (matched + case-insensitively); stable installs track exact ``vX.Y.Z`` releases. +- An update target must be newer than OR equal to the running version + (equal = reinstall/repair). Older versions are always refused. +- Checking is automatic (background thread); installing is always manual. +""" import os +import re import sys import json import time @@ -11,7 +23,7 @@ import urllib.request import zipfile import tempfile import subprocess -from datetime import datetime, timezone +from datetime import datetime logger = logging.getLogger(__name__) @@ -28,40 +40,154 @@ PROTECTED_PATHS = { '.env', } -# File extensions that are always safe to overwrite -SAFE_EXTENSIONS = {'.py', '.html', '.css', '.js', '.sh', '.ps1', '.md', '.txt', '.yaml', '.yml', '.json', '.ini', '.cfg'} +_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$") +_STABLE_RE = re.compile(r"^v\d+\.\d+\.\d+$", re.IGNORECASE) +_EXPERIMENTAL_RE = re.compile(r"^v\d+\.\d+\.\d+-experimental$", re.IGNORECASE) + + +def parse_version(value): + """Parse 'v0.7.5-experimental' -> ((0, 7, 5), 'experimental'). + + Returns None for anything that is not a plain dotted version with an + optional single suffix. Never raises. + """ + if not value: + return None + match = _VERSION_RE.fullmatch(str(value).strip()) + if not match: + return None + numbers = (int(match.group(1)), int(match.group(2)), int(match.group(3))) + return numbers, (match.group(4) or '') + + +def channel_of(version): + """'experimental' for *-experimental versions, else 'stable'.""" + parsed = parse_version(version) + if parsed and parsed[1].lower() == 'experimental': + return 'experimental' + return 'stable' + + +def compare_versions(a, b): + """Compare numeric parts only. Returns -1, 0 or 1. Unknowns sort last.""" + pa, pb = parse_version(a), parse_version(b) + if pa is None and pb is None: + return 0 + if pa is None: + return -1 + if pb is None: + return 1 + if pa[0] < pb[0]: + return -1 + if pa[0] > pb[0]: + return 1 + return 0 + + +def release_matches_channel(tag, channel): + """True when a release tag belongs to the channel (case-insensitive).""" + tag = str(tag or '') + if channel == 'experimental': + return bool(_EXPERIMENTAL_RE.fullmatch(tag)) + return bool(_STABLE_RE.fullmatch(tag)) class UpdateService: def __init__(self, project_root): self.project_root = project_root - self._update_available = False - self._latest_sha = None - self._current_sha = None + self._current_version = self._read_local_version() + self._channel = channel_of(self._current_version) + self._latest = None # {'version', 'tag', 'notes', 'zipball_url'} + self._other_latest = None self._last_check = 0 self._check_interval = 1800 # 30 minutes self._update_in_progress = False self._update_status = None - self._current_branch = self._detect_branch() + self._preview = None # {'version', 'notes'} - in-memory test helper - def _detect_branch(self): - """Detect the current git branch or ZIP branch from folder name.""" + # ── version / channel ──────────────────────────────────────────── + + def _read_local_version(self): try: - branch = subprocess.check_output( - ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], - cwd=self.project_root, stderr=subprocess.DEVNULL - ).decode().strip() - if branch: - return branch + with open(os.path.join(self.project_root, 'VERSION')) as f: + version = f.read().strip().replace('\r', '').replace('\n', '') + if parse_version(version): + return version except Exception: pass + return '0.0.0' - folder_name = os.path.basename(self.project_root).lower() - if 'nightly' in folder_name: - return 'nightly' - if 'beta' in folder_name: - return 'beta' - return 'main' + @property + def current_version(self): + return self._current_version + + @property + def channel(self): + return self._channel + + # ── silence state (backups/update-silence.json) ────────────────── + + def _silence_path(self): + return os.path.join(self.project_root, 'backups', 'update-silence.json') + + def get_silence(self): + try: + with open(self._silence_path()) as f: + stored = json.load(f) or {} + return { + 'silenced_versions': list(stored.get('silenced_versions', [])), + 'silence_all': bool(stored.get('silence_all', False)), + } + except (FileNotFoundError, ValueError, OSError): + return {'silenced_versions': [], 'silence_all': False} + + def _save_silence(self, state): + try: + os.makedirs(os.path.dirname(self._silence_path()), exist_ok=True) + with open(self._silence_path(), 'w') as f: + json.dump({ + 'silenced_versions': list(state.get('silenced_versions', [])), + 'silence_all': bool(state.get('silence_all', False)), + }, f, indent=2) + except OSError as e: + logger.warning(f'Update silence: could not save: {e}') + return self.get_silence() + + def silence_version(self, version): + state = self.get_silence() + version = str(version or '').strip() + if version and version not in state['silenced_versions']: + state['silenced_versions'].append(version) + return self._save_silence(state) + + def unsilence_version(self, version): + state = self.get_silence() + version = str(version or '').strip() + if version in state['silenced_versions']: + state['silenced_versions'].remove(version) + return self._save_silence(state) + + def set_silence_all(self, enabled): + state = self.get_silence() + state['silence_all'] = bool(enabled) + return self._save_silence(state) + + def clear_silence(self): + return self._save_silence({'silenced_versions': [], 'silence_all': False}) + + # ── preview helper (banner testing only, never installable) ───── + + def set_preview(self, version, notes=''): + version = str(version or '').strip() + if not parse_version(version): + raise ValueError('Preview version is not a valid version number.') + self._preview = {'version': version, 'notes': str(notes or '')} + return dict(self._preview) + + def clear_preview(self): + self._preview = None + + # ── background checker ─────────────────────────────────────────── def start_checker(self): """Start background update checker thread.""" @@ -78,107 +204,190 @@ class UpdateService: logger.debug(f"Update check failed: {e}") time.sleep(self._check_interval) + def _fetch_releases(self): + """All releases from GitHub (follows pagination).""" + releases = [] + url = f"{GITHUB_API}/releases?per_page=100" + while url: + req = urllib.request.Request(url) + req.add_header('Accept', 'application/vnd.github.v3+json') + req.add_header('User-Agent', 'DuneDashboard-UpdateChecker') + with urllib.request.urlopen(req, timeout=15) as resp: + releases.extend(json.loads(resp.read().decode())) + url = self._next_page(resp.headers.get('Link', '')) + return releases + + @staticmethod + def _next_page(link_header): + for part in (link_header or '').split(','): + segments = part.split(';') + if len(segments) == 2 and 'rel="next"' in segments[1]: + return segments[0].strip().strip('<>') + return '' + + @staticmethod + def _pick_latest(releases, channel): + """Newest release for a channel. Returns entry dict or None.""" + best = None + for release in releases: + if not isinstance(release, dict) or release.get('draft'): + continue + tag = str(release.get('tag_name') or '') + if not release_matches_channel(tag, channel): + continue + parsed = parse_version(tag) + if parsed is None: + continue + version = tag[1:] if tag.lower().startswith('v') else tag + entry = { + 'version': version, + 'tag': tag, + 'notes': str(release.get('body') or ''), + 'zipball_url': str(release.get('zipball_url') or ''), + } + if best is None or compare_versions(entry['version'], best['version']) > 0: + best = entry + return best + def check_for_updates(self): - """Check GitHub for new commits.""" + """Refresh latest-version info for our channel (and the other one).""" try: - branch = self._current_branch - git_dir = os.path.join(self.project_root, '.git') - if os.path.isdir(git_dir): - # Git clone: compare local HEAD to origin/ - subprocess.run( - ['git', 'fetch', 'origin', branch, '--quiet'], - cwd=self.project_root, stderr=subprocess.DEVNULL, timeout=15 - ) - local_sha = subprocess.check_output( - ['git', 'rev-parse', 'HEAD'], - cwd=self.project_root, stderr=subprocess.DEVNULL - ).decode().strip()[:7] - remote_sha = subprocess.check_output( - ['git', 'rev-parse', f'origin/{branch}'], - cwd=self.project_root, stderr=subprocess.DEVNULL - ).decode().strip()[:7] - else: - # ZIP download: compare VERSION file to GitHub API - req = urllib.request.Request(f"{GITHUB_API}/commits/{branch}") - req.add_header('Accept', 'application/vnd.github.v3+json') - req.add_header('User-Agent', 'DuneDashboard-UpdateChecker') - with urllib.request.urlopen(req, timeout=10) as resp: - data = json.loads(resp.read().decode()) - remote_sha = data['sha'][:7] - - version_file = os.path.join(self.project_root, 'VERSION') - if os.path.exists(version_file): - with open(version_file) as f: - local_sha = f.read().strip().replace('\r', '').replace('\n', '')[:7] - else: - # First run after ZIP download: record current version - local_sha = remote_sha - with open(version_file, 'w') as f: - f.write(remote_sha + '\n') - - self._latest_sha = remote_sha - self._current_sha = local_sha - self._update_available = remote_sha != local_sha and remote_sha != "" + releases = self._fetch_releases() + other = 'stable' if self._channel == 'experimental' else 'experimental' + self._latest = self._pick_latest(releases, self._channel) + self._other_latest = self._pick_latest(releases, other) self._last_check = time.time() - logger.info(f"Update check ({branch}): {'available' if self._update_available else 'up to date'} (local={local_sha}, remote={remote_sha})") + if self._latest: + logger.info( + f"Update check ({self._channel}): latest={self._latest['version']} " + f"current={self._current_version}") + else: + logger.info(f"Update check ({self._channel}): no releases found") except Exception as e: logger.debug(f"Update check error: {e}") + def _is_newer_or_same(self, version): + return compare_versions(version, self._current_version) >= 0 + + def status(self): + """Full status payload for the banner/API.""" + silence = self.get_silence() + latest = dict(self._latest) if self._latest else None + available = bool( + latest and self._is_newer_or_same(latest['version']) + and compare_versions(latest['version'], self._current_version) != 0) + other = dict(self._other_latest) if self._other_latest else None + show_other = bool( + other and other['version'] != (latest['version'] if latest else None) + and self._is_newer_or_same(other['version'])) + return { + 'current_version': self._current_version, + 'channel': self._channel, + 'available': available, + 'latest': latest, + 'other_channel': { + 'channel': 'stable' if self._channel == 'experimental' else 'experimental', + 'latest': other, + 'available': show_other, + }, + 'preview': dict(self._preview) if self._preview else None, + 'silenced_versions': silence['silenced_versions'], + 'silence_all': silence['silence_all'], + 'update_in_progress': self._update_in_progress, + 'update_status': self._update_status, + 'last_check': self._last_check, + } + @property def update_available(self): - return self._update_available + status = self.status() + return status['available'] or status['preview'] is not None @property def update_status(self): return self._update_status - def apply_update(self): - """Download and apply the latest update.""" + # ── apply ──────────────────────────────────────────────────────── + + def _find_release(self, version): + """Find a known release matching a version string exactly.""" + for entry in (self._latest, self._other_latest): + if entry and entry['version'] == version: + return entry + return None + + def apply_update(self, version=None): + """Download and apply a release. Version must be known and not older.""" if self._update_in_progress: return False, "Update already in progress" + target = str(version or '').strip() + if not target: + # Default: newest for our own channel. + if not self._latest: + return False, "No release found for this channel" + target = self._latest['version'] + + if parse_version(target) is None: + return False, "Invalid version number" + if not self._is_newer_or_same(target): + return False, ( + f"Refusing downgrade: {target} is older than " + f"the running {self._current_version}") + entry = self._find_release(target) + if entry is None: + # Refresh once in case a release landed since the last check. + self.check_for_updates() + entry = self._find_release(target) + if entry is None: + return False, f"Unknown version: {target} (not a published release)" + if not entry.get('zipball_url'): + return False, "Release has no downloadable archive" + self._update_in_progress = True - self._update_status = "Downloading update..." + self._update_status = f"Downloading {target}..." try: - # Download latest zip from the detected branch - branch = self._current_branch - zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip" - req = urllib.request.Request(zip_url) + req = urllib.request.Request(entry['zipball_url']) + req.add_header('Accept', 'application/vnd.github.v3+json') req.add_header('User-Agent', 'DuneDashboard-UpdateChecker') - with urllib.request.urlopen(req, timeout=60) as resp: + with urllib.request.urlopen(req, timeout=120) as resp: zip_data = resp.read() + if not zip_data.startswith(b'PK\x03\x04'): + raise ValueError("Downloaded file is not a zip archive") self._update_status = "Extracting update..." - - # Extract to temp directory temp_dir = tempfile.mkdtemp(prefix='dune_update_') zip_path = os.path.join(temp_dir, 'update.zip') with open(zip_path, 'wb') as f: f.write(zip_data) with zipfile.ZipFile(zip_path, 'r') as zf: + # Reject archives with absolute paths or parent escapes. + for member in zf.namelist(): + if member.startswith('/') or '..' in member.split('/'): + raise ValueError(f"Unsafe archive entry: {member!r}") zf.extractall(temp_dir) - # Find the extracted folder (e.g., dune-dashboard-main) - extracted = [d for d in os.listdir(temp_dir) if os.path.isdir(os.path.join(temp_dir, d)) and d != '__MACOSX'] + extracted = [d for d in os.listdir(temp_dir) + if os.path.isdir(os.path.join(temp_dir, d)) + and d != '__MACOSX'] if not extracted: return False, "Failed to extract update" source_dir = os.path.join(temp_dir, extracted[0]) - # Create backup - backup_dir = os.path.join(self.project_root, 'backups', f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}') + backup_dir = os.path.join( + self.project_root, 'backups', + f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}') os.makedirs(backup_dir, exist_ok=True) - # Copy files, skipping protected paths self._update_status = "Applying files..." files_updated = 0 for root, dirs, files in os.walk(source_dir): rel_root = os.path.relpath(root, source_dir) target_root = os.path.join(self.project_root, rel_root) - # Skip protected directories if any(p in PROTECTED_PATHS for p in rel_root.split(os.sep)): continue @@ -190,11 +399,9 @@ class UpdateService: src_file = os.path.join(root, file) dst_file = os.path.join(target_root, file) - # Skip protected files if file in PROTECTED_PATHS: continue - # Backup existing file if it exists if os.path.exists(dst_file): backup_file = os.path.join(backup_dir, rel_root, file) os.makedirs(os.path.dirname(backup_file), exist_ok=True) @@ -203,18 +410,15 @@ class UpdateService: shutil.copy2(src_file, dst_file) files_updated += 1 - # Cleanup temp shutil.rmtree(temp_dir, ignore_errors=True) - # Update VERSION file to match new version - version_file = os.path.join(self.project_root, 'VERSION') - with open(version_file, 'w') as f: - f.write(self._latest_sha + '\n') + with open(os.path.join(self.project_root, 'VERSION'), 'w') as f: + f.write(target + '\n') + self._current_version = target + self._channel = channel_of(target) self._update_status = f"Update applied! {files_updated} files updated. Restarting..." - self._update_available = False - # Restart the application self._restart_app() return True, f"Update applied successfully ({files_updated} files)" diff --git a/static/style.css b/static/style.css index 2f672de..4d8fd73 100644 --- a/static/style.css +++ b/static/style.css @@ -1320,6 +1320,109 @@ body[data-nav-layout="vertical"] .site-footer { margin-left: 216px; } +/* Update widget: lives in the nav next to the theme button, styled like + the theme dropdown (nav-bg surface, nav-text tones) in every theme. */ +.nav-tools { display: flex; align-items: center; gap: 2px; } +.update-banner { display: none; position: relative; } +.update-banner .ub-bellwrap { position: relative; display: inline-block; } +.update-banner .ub-dot { + position: absolute; top: 2px; right: 6px; width: 8px; height: 8px; + border-radius: 50%; background: var(--warn); +} +.update-banner .ub-panel { + position: absolute; + top: calc(100% + 8px); + right: 0; + width: 320px; + max-width: calc(100vw - 32px); + max-height: 70vh; + overflow-y: auto; + background: var(--nav-bg); + border: 1px solid rgba(255,255,255,0.1); + border-radius: 8px; + box-shadow: 0 4px 16px rgba(0,0,0,0.4); + z-index: 1000; + padding: 12px; + font-size: 12px; + line-height: 1.5; + color: var(--nav-text); +} +.update-banner .ub-title { font-weight: 700; margin-bottom: 2px; color: #fff; } +.update-banner .ub-sub { color: var(--nav-text); opacity: 0.75; font-size: 11px; margin-bottom: 6px; } +.update-banner .ub-preview-tag { + font-size: 10px; font-weight: 700; color: #fff; background: var(--warn); + border-radius: 8px; padding: 0 6px; margin-left: 4px; +} +.update-banner .ub-notes { margin: 4px 0 6px; } +.update-banner .ub-notes summary { cursor: pointer; font-size: 11px; color: var(--nav-text); opacity: 0.75; } +.update-banner .ub-notes pre { + white-space: pre-wrap; font-size: 11px; max-height: 160px; overflow-y: auto; + background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1); + border-radius: 6px; padding: 8px; margin-top: 4px; color: var(--nav-text); +} +.update-banner .ub-actions { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; } +.update-banner .ub-actions button { + padding: 4px 12px; font-size: 12px; cursor: pointer; + background: var(--primary); color: #fff; border: none; border-radius: 4px; +} +.update-banner .ub-actions button.ub-ghost { + background: transparent; color: var(--nav-text); + border: 1px solid rgba(255,255,255,0.25); +} +.update-banner .ub-mute { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--nav-text); opacity: 0.75; cursor: pointer; } +.update-banner .ub-status { font-size: 11px; color: var(--nav-text); opacity: 0.75; margin-top: 4px; } +.update-banner .ub-panel-head { font-weight: 700; margin-bottom: 6px; color: #fff; cursor: pointer; } +.update-banner .ub-row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-bottom: 6px; font-size: 12px; } +.update-banner .ub-row select { + padding: 4px 8px; font-size: 12px; color: var(--nav-text); + background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); border-radius: 4px; +} +.update-banner .ub-row button { + padding: 4px 12px; font-size: 12px; cursor: pointer; + background: transparent; color: var(--nav-text); + border: 1px solid rgba(255,255,255,0.25); border-radius: 4px; +} +#ub-overlay { + position: fixed; inset: 0; z-index: 2000; + background: rgba(0,0,0,0.6); + display: flex; align-items: center; justify-content: center; padding: 24px; +} +#ub-overlay .ub-overlay-box { + max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto; + background: var(--card-bg); color: var(--text); + border-radius: 12px; box-shadow: var(--shadow); padding: 16px 18px; +} +#ub-overlay .ub-overlay-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; } +#ub-overlay .ub-overlay-head button { + padding: 4px 14px; font-size: 12px; cursor: pointer; + background: var(--primary); color: #fff; border: none; border-radius: 4px; +} +#ub-overlay pre { white-space: pre-wrap; font-size: 12px; } + +/* Vertical sidebar: tools row sits with the theme button; panel pops upward + like the theme dropdown content does. */ +body[data-nav-layout="vertical"] .nav-tools { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 8px 16px; + border-top: 1px solid rgba(255,255,255,0.08); +} +body[data-nav-layout="vertical"] .nav-tools .theme-dropdown { + padding: 0; + border-top: none; +} +body[data-nav-layout="vertical"] .nav-tools .theme-btn { + width: auto; +} +body[data-nav-layout="vertical"] .update-banner .ub-panel { + top: auto; + bottom: calc(100% + 8px); + left: 0; + right: auto; +} + @media (max-width: 768px) { body[data-nav-layout="vertical"] { padding-left: 0; diff --git a/templates/base.html b/templates/base.html index 87d48fe..557326d 100644 --- a/templates/base.html +++ b/templates/base.html @@ -47,6 +47,7 @@ {% endfor %}
+ + + {{ 'Connected' if conn_ok else 'Disconnected' }} @@ -193,6 +196,221 @@ initTheme(); initNavLayout(); + + // Update banner (channel-aware self updates) + function escHtml(s) { + return String(s == null ? '' : s) + .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + .replace(/'/g, '''); + } + + // Update widget: always-visible bell. Expands into a panel with a + // channel dropdown, manual check, patch notes overlay, update and + // silence controls. Auto-expands only for a new, non-silenced update. + let ubData = null; + let ubViewChannel = null; // channel shown in the panel; null = own channel + let ubExpanded = false; + + function ubChannelLatest(channel) { + if (!ubData) return null; + if (channel === ubData.channel) { + return ubData.latest ? { ...ubData.latest, available: ubData.available } : null; + } + const other = ubData.other_channel; + if (other && other.channel === channel) { + return other.latest ? { ...other.latest, available: other.available } : null; + } + return null; + } + + function ubHasNews() { + if (!ubData || ubData.silence_all) return false; + if (ubData.preview) return true; + const silenced = ubData.silenced_versions || []; + const cur = ubChannelLatest(ubData.channel); + if (cur && cur.available && !silenced.includes(cur.version)) return true; + const other = ubData.other_channel; + if (other && other.available && other.latest && !silenced.includes(other.latest.version)) return true; + return false; + } + + async function refreshUpdateBanner(keepOpen) { + const el = document.getElementById('update-banner'); + if (!el) return; + try { + const resp = await fetch('/api/update/status'); + ubData = await resp.json(); + } catch (e) { return; } // leave whatever is shown + if (!ubData || !ubData.success) return; + if (!ubViewChannel) ubViewChannel = ubData.channel; + // Auto-expand for fresh news unless permanently muted. + if (!keepOpen && !ubExpanded && ubHasNews()) ubExpanded = true; + renderUpdateBanner(); + } + + // Notes cache keyed by version (versions are server-validated to + // digits/dots/dashes only, so they are safe inside onclick quotes). + let ubNotesCache = {}; + function ubSafeVer(v) { + return /^[0-9A-Za-z.\-]+$/.test(v || '') ? v : ''; + } + + function renderUpdateBanner() { + const el = document.getElementById('update-banner'); + if (!el || !ubData) return; + if (!ubExpanded) { + const dot = ubHasNews() ? '' : ''; + const bell = ubData.silence_all ? '🔕' : '🔔'; + el.style.display = 'block'; + el.innerHTML = ``; + return; + } + const data = ubData; + const channels = [data.channel]; + if (data.other_channel && data.other_channel.channel && + !channels.includes(data.other_channel.channel)) { + channels.push(data.other_channel.channel); + } + const viewing = ubViewChannel || data.channel; + const entry = ubChannelLatest(viewing); + const silenced = data.silenced_versions || []; + const isSilenced = !!(entry && silenced.includes(entry.version)); + const canUpdate = !!(entry && entry.available && !isSilenced); + + let opts = ''; + channels.forEach(ch => { + const label = ch === data.channel ? `${ch} (yours)` : ch; + opts += ``; + }); + + let body = `
You are on ${escHtml(data.current_version)} (${escHtml(data.channel)})
`; + body += `
` + + `
`; + + if (data.preview && ubSafeVer(data.preview.version)) { + ubNotesCache[data.preview.version] = data.preview.notes || ''; + body += `
${escHtml(data.preview.version)} preview
` + + `
` + + `
`; + } + + if (entry && ubSafeVer(entry.version)) { + ubNotesCache[entry.version] = entry.notes || ''; + const stateLine = !entry.available + ? `
${escHtml(viewing)} is up to date at ${escHtml(entry.version)}.
` + : isSilenced + ? `
${escHtml(entry.version)} silenced - a newer version will show again.
` + : `
Update available: ${escHtml(entry.version)}
`; + body += stateLine; + body += '
' + + (entry.notes ? `` : '') + + (canUpdate ? `` : '') + + (entry.available && !isSilenced ? `` : '') + + '
'; + } else if (!data.preview) { + body += `
No ${escHtml(viewing)} releases found yet.
`; + } + + body += `` + + '
'; + el.style.display = 'block'; + const bellIcon = data.silence_all ? '🔕' : '🔔'; + el.innerHTML = `` + + `
Updates
` + body + `
`; + } + + function toggleUpdatePanel(open) { + ubExpanded = open; + renderUpdateBanner(); + } + + async function checkUpdatesNow() { + const st = document.getElementById('ub-status'); + if (st) st.textContent = 'Checking...'; + try { + await csrfFetch('/api/update/check', { method: 'POST' }); + } catch (e) { /* status refresh below reports */ } + refreshUpdateBanner(true); + } + + function openNotesOverlay(version) { + closeNotesOverlay(); + const notes = ubNotesCache[version] || ''; + const ov = document.createElement('div'); + ov.id = 'ub-overlay'; + const box = document.createElement('div'); + box.className = 'ub-overlay-box'; + const head = document.createElement('div'); + head.className = 'ub-overlay-head'; + const title = document.createElement('strong'); + title.textContent = 'Patch notes - ' + version; + const close = document.createElement('button'); + close.textContent = 'Close'; + close.onclick = closeNotesOverlay; + head.appendChild(title); + head.appendChild(close); + const pre = document.createElement('pre'); + pre.textContent = notes || 'No notes for this version.'; + box.appendChild(head); + box.appendChild(pre); + ov.appendChild(box); + ov.onclick = function(e) { if (e.target === ov) closeNotesOverlay(); }; + document.body.appendChild(ov); + } + + function closeNotesOverlay() { + const ov = document.getElementById('ub-overlay'); + if (ov) ov.remove(); + } + + async function clearPreview() { + await csrfFetch('/api/update/preview', { method: 'DELETE' }); + refreshUpdateBanner(true); + } + + async function applyUpdate(version) { + if (!confirm(`Update to ${version}? The dashboard backs itself up, installs, then restarts. Players will be briefly disconnected from the panel (not the game).`)) return; + const st = document.getElementById('ub-status'); + if (st) st.textContent = 'Updating - the panel will restart...'; + try { + const resp = await csrfFetch('/api/update/apply', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ version }) + }); + const data = await resp.json(); + if (st) st.textContent = data.success ? (data.message || 'Updating...') : ('Error: ' + (data.message || data.error || 'unknown')); + } catch (e) { + if (st) st.textContent = 'Error: ' + e.message; + } + } + + async function silenceUpdateVersion(version) { + await csrfFetch('/api/update/silence', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action: 'silence', version }) + }); + refreshUpdateBanner(); + } + + async function setUpdateMute(on) { + await csrfFetch('/api/update/silence', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action: on ? 'mute' : 'unmute' }) + }); + refreshUpdateBanner(); + } + + async function unmuteUpdates() { + await csrfFetch('/api/update/silence', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action: 'unmute' }) + }); + refreshUpdateBanner(); + } + + refreshUpdateBanner(); + setInterval(refreshUpdateBanner, 10 * 60 * 1000); {% block scripts %}{% endblock %}