Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b0bffe464 | ||
|
|
901c485c65 |
No files matched your search
+2
-2
@@ -103,8 +103,8 @@ find_*.py
|
|||||||
AI_DOCS/
|
AI_DOCS/
|
||||||
AI_FULL_PROJECT_ANALYSIS_MODE/
|
AI_FULL_PROJECT_ANALYSIS_MODE/
|
||||||
|
|
||||||
# VERSION is committed: it is the dashboard's version source of truth
|
# Version file (generated dynamically)
|
||||||
# (e.g. 0.7.5-experimental). The updater reads it, never ignores it.
|
VERSION
|
||||||
|
|
||||||
# Security scripts (contain VM-specific configs)
|
# Security scripts (contain VM-specific configs)
|
||||||
scripts/
|
scripts/
|
||||||
|
|||||||
+2
-2
@@ -335,8 +335,8 @@ def create_app(settings_path=None):
|
|||||||
register_api_routes(app, services, settings)
|
register_api_routes(app, services, settings)
|
||||||
register_websocket_handlers(socketio, settings)
|
register_websocket_handlers(socketio, settings)
|
||||||
|
|
||||||
# Background update check (channel-aware releases; installing is manual only)
|
# 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):
|
||||||
|
|||||||
+22
-64
@@ -1506,16 +1506,17 @@ def register_api_routes(app, services, settings):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({'success': False, 'error': str(e)}), 500
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
# Update management (channel-aware, releases-based, never downgrades)
|
# Update management
|
||||||
@app.route('/api/update/status')
|
@app.route('/api/update/status')
|
||||||
@auth_req
|
@auth_req
|
||||||
def api_update_status():
|
def api_update_status():
|
||||||
updater = services.get('updater')
|
updater = services.get('updater')
|
||||||
if not updater:
|
if not updater:
|
||||||
return jsonify({'available': False})
|
return jsonify({'available': False})
|
||||||
status = updater.status()
|
return jsonify({
|
||||||
status['success'] = True
|
'available': updater.update_available,
|
||||||
return jsonify(status)
|
'status': updater.update_status,
|
||||||
|
})
|
||||||
|
|
||||||
@app.route('/api/update/apply', methods=['POST'])
|
@app.route('/api/update/apply', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@@ -1523,14 +1524,19 @@ def register_api_routes(app, services, settings):
|
|||||||
updater = services.get('updater')
|
updater = services.get('updater')
|
||||||
if not updater:
|
if not updater:
|
||||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||||
data = request.get_json() or {}
|
success, message = updater.apply_update()
|
||||||
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})
|
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'])
|
@app.route('/api/update/check', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
def api_update_check():
|
def api_update_check():
|
||||||
@@ -1539,60 +1545,12 @@ def register_api_routes(app, services, settings):
|
|||||||
if not updater:
|
if not updater:
|
||||||
return jsonify({'success': False, 'error': 'Updater not available'})
|
return jsonify({'success': False, 'error': 'Updater not available'})
|
||||||
updater.check_for_updates()
|
updater.check_for_updates()
|
||||||
status = updater.status()
|
return jsonify({
|
||||||
status['success'] = True
|
'available': updater.update_available,
|
||||||
return jsonify(status)
|
'status': updater.update_status,
|
||||||
|
'local_version': updater._current_sha,
|
||||||
@app.route('/api/update/preview', methods=['POST'])
|
'remote_version': updater._latest_sha,
|
||||||
@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
|
# Audit logs
|
||||||
from app.services.audit import AuditService
|
from app.services.audit import AuditService
|
||||||
|
|||||||
+43
-51
@@ -19,26 +19,22 @@ class DatabaseService:
|
|||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
if self.pool is None:
|
if self.pool is None:
|
||||||
# Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
|
# Retry up to 10 times with 2s delays (20s total) to handle startup race conditions
|
||||||
try:
|
for attempt in range(10):
|
||||||
for attempt in range(10):
|
try:
|
||||||
try:
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
minconn=self.min_conn,
|
||||||
minconn=self.min_conn,
|
maxconn=self.max_conn,
|
||||||
maxconn=self.max_conn,
|
**self.db_config
|
||||||
**self.db_config
|
)
|
||||||
)
|
logger.info("Database connection pool initialized")
|
||||||
logger.info("Database connection pool initialized")
|
return self.pool
|
||||||
return self.pool
|
except Exception as e:
|
||||||
except Exception as e:
|
if attempt < 9:
|
||||||
if attempt < 9:
|
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
time.sleep(2)
|
||||||
time.sleep(2)
|
else:
|
||||||
else:
|
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
||||||
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
self.pool = None
|
||||||
self.pool = None
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\n Stopped during database startup.")
|
|
||||||
raise SystemExit(0)
|
|
||||||
return self.pool
|
return self.pool
|
||||||
|
|
||||||
def get_connection(self):
|
def get_connection(self):
|
||||||
@@ -159,37 +155,33 @@ class DashboardDatabaseService:
|
|||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
if self.pool is not None:
|
if self.pool is not None:
|
||||||
return self.pool
|
return self.pool
|
||||||
try:
|
for attempt in range(10):
|
||||||
for attempt in range(10):
|
try:
|
||||||
try:
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
minconn=self.min_conn,
|
||||||
minconn=self.min_conn,
|
maxconn=self.max_conn,
|
||||||
maxconn=self.max_conn,
|
**self.db_config
|
||||||
**self.db_config
|
)
|
||||||
)
|
logger.info("Dashboard database pool initialized")
|
||||||
logger.info("Dashboard database pool initialized")
|
return self.pool
|
||||||
return self.pool
|
except psycopg2.OperationalError as e:
|
||||||
except psycopg2.OperationalError as e:
|
if 'does not exist' in str(e) and attempt == 0:
|
||||||
if 'does not exist' in str(e) and attempt == 0:
|
logger.info("Dashboard database does not exist, creating...")
|
||||||
logger.info("Dashboard database does not exist, creating...")
|
self._ensure_database()
|
||||||
self._ensure_database()
|
continue
|
||||||
continue
|
if attempt < 9:
|
||||||
if attempt < 9:
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
time.sleep(2)
|
||||||
time.sleep(2)
|
else:
|
||||||
else:
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
self.pool = None
|
||||||
self.pool = None
|
except Exception as e:
|
||||||
except Exception as e:
|
if attempt < 9:
|
||||||
if attempt < 9:
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
time.sleep(2)
|
||||||
time.sleep(2)
|
else:
|
||||||
else:
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
self.pool = None
|
||||||
self.pool = None
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\n Stopped during database startup.")
|
|
||||||
raise SystemExit(0)
|
|
||||||
return self.pool
|
return self.pool
|
||||||
|
|
||||||
def _ensure_database(self):
|
def _ensure_database(self):
|
||||||
|
|||||||
+91
-332
@@ -1,18 +1,6 @@
|
|||||||
"""Update service - channel-aware self updates from GitHub Releases.
|
"""Update service - checks GitHub for new releases and applies updates"""
|
||||||
|
|
||||||
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 os
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
@@ -23,7 +11,7 @@ import urllib.request
|
|||||||
import zipfile
|
import zipfile
|
||||||
import tempfile
|
import tempfile
|
||||||
import subprocess
|
import subprocess
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -40,155 +28,40 @@ PROTECTED_PATHS = {
|
|||||||
'.env',
|
'.env',
|
||||||
}
|
}
|
||||||
|
|
||||||
_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$")
|
# File extensions that are always safe to overwrite
|
||||||
_STABLE_RE = re.compile(r"^v\d+\.\d+\.\d+$", re.IGNORECASE)
|
SAFE_EXTENSIONS = {'.py', '.html', '.css', '.js', '.sh', '.ps1', '.md', '.txt', '.yaml', '.yml', '.json', '.ini', '.cfg'}
|
||||||
_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:
|
class UpdateService:
|
||||||
def __init__(self, project_root):
|
def __init__(self, project_root):
|
||||||
self.project_root = project_root
|
self.project_root = project_root
|
||||||
self._current_version = self._read_local_version()
|
self._update_available = False
|
||||||
self._channel = channel_of(self._current_version)
|
self._latest_sha = None
|
||||||
self._latest = None # {'version', 'tag', 'notes', 'zipball_url'}
|
self._current_sha = None
|
||||||
self._other_latest = None
|
|
||||||
self._releases = {'experimental': [], 'stable': []} # per-channel lists, newest first
|
|
||||||
self._last_check = 0
|
self._last_check = 0
|
||||||
self._check_interval = 1800 # 30 minutes
|
self._check_interval = 1800 # 30 minutes
|
||||||
self._update_in_progress = False
|
self._update_in_progress = False
|
||||||
self._update_status = None
|
self._update_status = None
|
||||||
self._preview = None # {'version', 'notes'} - in-memory test helper
|
self._current_branch = self._detect_branch()
|
||||||
|
|
||||||
# ── version / channel ────────────────────────────────────────────
|
def _detect_branch(self):
|
||||||
|
"""Detect the current git branch or ZIP branch from folder name."""
|
||||||
def _read_local_version(self):
|
|
||||||
try:
|
try:
|
||||||
with open(os.path.join(self.project_root, 'VERSION')) as f:
|
branch = subprocess.check_output(
|
||||||
version = f.read().strip().replace('\r', '').replace('\n', '')
|
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
|
||||||
if parse_version(version):
|
cwd=self.project_root, stderr=subprocess.DEVNULL
|
||||||
return version
|
).decode().strip()
|
||||||
|
if branch:
|
||||||
|
return branch
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return '0.0.0'
|
|
||||||
|
|
||||||
@property
|
folder_name = os.path.basename(self.project_root).lower()
|
||||||
def current_version(self):
|
if 'nightly' in folder_name:
|
||||||
return self._current_version
|
return 'nightly'
|
||||||
|
if 'beta' in folder_name:
|
||||||
@property
|
return 'beta'
|
||||||
def channel(self):
|
return 'main'
|
||||||
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):
|
def start_checker(self):
|
||||||
"""Start background update checker thread."""
|
"""Start background update checker thread."""
|
||||||
@@ -205,219 +78,107 @@ class UpdateService:
|
|||||||
logger.debug(f"Update check failed: {e}")
|
logger.debug(f"Update check failed: {e}")
|
||||||
time.sleep(self._check_interval)
|
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 _collect_channel(releases, channel):
|
|
||||||
"""All releases for a channel, newest first.
|
|
||||||
|
|
||||||
Each entry is {'version', 'tag', 'notes', 'zipball_url'}.
|
|
||||||
Drafts, non-matching tags and unparsable versions are skipped.
|
|
||||||
"""
|
|
||||||
found = []
|
|
||||||
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
|
|
||||||
found.append({
|
|
||||||
'version': version,
|
|
||||||
'tag': tag,
|
|
||||||
'notes': str(release.get('body') or ''),
|
|
||||||
'zipball_url': str(release.get('zipball_url') or ''),
|
|
||||||
})
|
|
||||||
found.sort(key=lambda e: parse_version(e['version'])[0], reverse=True)
|
|
||||||
return found
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _pick_latest(releases, channel):
|
|
||||||
"""Newest release for a channel. Returns entry dict or None."""
|
|
||||||
collected = UpdateService._collect_channel(releases, channel)
|
|
||||||
return collected[0] if collected else None
|
|
||||||
|
|
||||||
def check_for_updates(self):
|
def check_for_updates(self):
|
||||||
"""Refresh latest-version info for our channel (and the other one)."""
|
"""Check GitHub for new commits."""
|
||||||
try:
|
try:
|
||||||
releases = self._fetch_releases()
|
branch = self._current_branch
|
||||||
other = 'stable' if self._channel == 'experimental' else 'experimental'
|
git_dir = os.path.join(self.project_root, '.git')
|
||||||
self._releases = {
|
if os.path.isdir(git_dir):
|
||||||
'experimental': self._collect_channel(releases, 'experimental'),
|
# Git clone: compare local HEAD to origin/<branch>
|
||||||
'stable': self._collect_channel(releases, 'stable'),
|
subprocess.run(
|
||||||
}
|
['git', 'fetch', 'origin', branch, '--quiet'],
|
||||||
self._latest = (self._releases[self._channel][0]
|
cwd=self.project_root, stderr=subprocess.DEVNULL, timeout=15
|
||||||
if self._releases[self._channel] else None)
|
)
|
||||||
self._other_latest = (self._releases[other][0]
|
local_sha = subprocess.check_output(
|
||||||
if self._releases[other] else None)
|
['git', 'rev-parse', 'HEAD'],
|
||||||
self._last_check = time.time()
|
cwd=self.project_root, stderr=subprocess.DEVNULL
|
||||||
if self._latest:
|
).decode().strip()[:7]
|
||||||
logger.info(
|
remote_sha = subprocess.check_output(
|
||||||
f"Update check ({self._channel}): latest={self._latest['version']} "
|
['git', 'rev-parse', f'origin/{branch}'],
|
||||||
f"current={self._current_version}")
|
cwd=self.project_root, stderr=subprocess.DEVNULL
|
||||||
|
).decode().strip()[:7]
|
||||||
else:
|
else:
|
||||||
logger.info(f"Update check ({self._channel}): no releases found")
|
# 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 != ""
|
||||||
|
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})")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug(f"Update check error: {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']))
|
|
||||||
# Per-channel release lists for the version picker (newest first).
|
|
||||||
# zipball URLs stay server-side; the panel only needs version/notes.
|
|
||||||
lists = {}
|
|
||||||
for channel, entries in (self._releases or {}).items():
|
|
||||||
lists[channel] = [
|
|
||||||
{'version': e['version'], 'tag': e['tag'],
|
|
||||||
'notes': e['notes']}
|
|
||||||
for e in entries
|
|
||||||
]
|
|
||||||
return {
|
|
||||||
'current_version': self._current_version,
|
|
||||||
'channel': self._channel,
|
|
||||||
'available': available,
|
|
||||||
'latest': latest,
|
|
||||||
'releases': lists,
|
|
||||||
'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
|
@property
|
||||||
def update_available(self):
|
def update_available(self):
|
||||||
status = self.status()
|
return self._update_available
|
||||||
return status['available'] or status['preview'] is not None
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def update_status(self):
|
def update_status(self):
|
||||||
return self._update_status
|
return self._update_status
|
||||||
|
|
||||||
# ── apply ────────────────────────────────────────────────────────
|
def apply_update(self):
|
||||||
|
"""Download and apply the latest update."""
|
||||||
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
|
|
||||||
for entries in (self._releases or {}).values():
|
|
||||||
for entry in entries:
|
|
||||||
if 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:
|
if self._update_in_progress:
|
||||||
return False, "Update already 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_in_progress = True
|
||||||
self._update_status = f"Downloading {target}..."
|
self._update_status = "Downloading update..."
|
||||||
|
|
||||||
try:
|
try:
|
||||||
req = urllib.request.Request(entry['zipball_url'])
|
# Download latest zip from the detected branch
|
||||||
req.add_header('Accept', 'application/vnd.github.v3+json')
|
branch = self._current_branch
|
||||||
|
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip"
|
||||||
|
req = urllib.request.Request(zip_url)
|
||||||
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
|
||||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||||
zip_data = resp.read()
|
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..."
|
self._update_status = "Extracting update..."
|
||||||
|
|
||||||
|
# Extract to temp directory
|
||||||
temp_dir = tempfile.mkdtemp(prefix='dune_update_')
|
temp_dir = tempfile.mkdtemp(prefix='dune_update_')
|
||||||
zip_path = os.path.join(temp_dir, 'update.zip')
|
zip_path = os.path.join(temp_dir, 'update.zip')
|
||||||
with open(zip_path, 'wb') as f:
|
with open(zip_path, 'wb') as f:
|
||||||
f.write(zip_data)
|
f.write(zip_data)
|
||||||
|
|
||||||
with zipfile.ZipFile(zip_path, 'r') as zf:
|
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)
|
zf.extractall(temp_dir)
|
||||||
|
|
||||||
extracted = [d for d in os.listdir(temp_dir)
|
# Find the extracted folder (e.g., dune-dashboard-main)
|
||||||
if os.path.isdir(os.path.join(temp_dir, d))
|
extracted = [d for d in os.listdir(temp_dir) if os.path.isdir(os.path.join(temp_dir, d)) and d != '__MACOSX']
|
||||||
and d != '__MACOSX']
|
|
||||||
if not extracted:
|
if not extracted:
|
||||||
return False, "Failed to extract update"
|
return False, "Failed to extract update"
|
||||||
|
|
||||||
source_dir = os.path.join(temp_dir, extracted[0])
|
source_dir = os.path.join(temp_dir, extracted[0])
|
||||||
|
|
||||||
backup_dir = os.path.join(
|
# Create backup
|
||||||
self.project_root, 'backups',
|
backup_dir = os.path.join(self.project_root, 'backups', f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
||||||
f'update_{datetime.now().strftime("%Y%m%d_%H%M%S")}')
|
|
||||||
os.makedirs(backup_dir, exist_ok=True)
|
os.makedirs(backup_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Copy files, skipping protected paths
|
||||||
self._update_status = "Applying files..."
|
self._update_status = "Applying files..."
|
||||||
files_updated = 0
|
files_updated = 0
|
||||||
for root, dirs, files in os.walk(source_dir):
|
for root, dirs, files in os.walk(source_dir):
|
||||||
rel_root = os.path.relpath(root, source_dir)
|
rel_root = os.path.relpath(root, source_dir)
|
||||||
target_root = os.path.join(self.project_root, rel_root)
|
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)):
|
if any(p in PROTECTED_PATHS for p in rel_root.split(os.sep)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -429,9 +190,11 @@ class UpdateService:
|
|||||||
src_file = os.path.join(root, file)
|
src_file = os.path.join(root, file)
|
||||||
dst_file = os.path.join(target_root, file)
|
dst_file = os.path.join(target_root, file)
|
||||||
|
|
||||||
|
# Skip protected files
|
||||||
if file in PROTECTED_PATHS:
|
if file in PROTECTED_PATHS:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Backup existing file if it exists
|
||||||
if os.path.exists(dst_file):
|
if os.path.exists(dst_file):
|
||||||
backup_file = os.path.join(backup_dir, rel_root, file)
|
backup_file = os.path.join(backup_dir, rel_root, file)
|
||||||
os.makedirs(os.path.dirname(backup_file), exist_ok=True)
|
os.makedirs(os.path.dirname(backup_file), exist_ok=True)
|
||||||
@@ -440,15 +203,18 @@ class UpdateService:
|
|||||||
shutil.copy2(src_file, dst_file)
|
shutil.copy2(src_file, dst_file)
|
||||||
files_updated += 1
|
files_updated += 1
|
||||||
|
|
||||||
|
# Cleanup temp
|
||||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
with open(os.path.join(self.project_root, 'VERSION'), 'w') as f:
|
# Update VERSION file to match new version
|
||||||
f.write(target + '\n')
|
version_file = os.path.join(self.project_root, 'VERSION')
|
||||||
|
with open(version_file, 'w') as f:
|
||||||
|
f.write(self._latest_sha + '\n')
|
||||||
|
|
||||||
self._current_version = target
|
|
||||||
self._channel = channel_of(target)
|
|
||||||
self._update_status = f"Update applied! {files_updated} files updated. Restarting..."
|
self._update_status = f"Update applied! {files_updated} files updated. Restarting..."
|
||||||
|
self._update_available = False
|
||||||
|
|
||||||
|
# Restart the application
|
||||||
self._restart_app()
|
self._restart_app()
|
||||||
|
|
||||||
return True, f"Update applied successfully ({files_updated} files)"
|
return True, f"Update applied successfully ({files_updated} files)"
|
||||||
@@ -460,20 +226,13 @@ class UpdateService:
|
|||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
|
||||||
def _restart_app(self):
|
def _restart_app(self):
|
||||||
"""Restart the dashboard through the launcher in auto-start mode.
|
"""Restart the dashboard via the launcher script to preserve SSH/DB tunnels."""
|
||||||
|
|
||||||
The launcher re-establishes SSH tunnels and port-forwards, then goes
|
|
||||||
straight into the dashboard without stopping at the selection menu.
|
|
||||||
The old process exits below, so the port is free when the new one
|
|
||||||
binds.
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
if os.name == 'nt':
|
if os.name == 'nt':
|
||||||
launcher = os.path.join(self.project_root, 'launcher.ps1')
|
launcher = os.path.join(self.project_root, 'launcher.ps1')
|
||||||
if os.path.exists(launcher):
|
if os.path.exists(launcher):
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
|
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher],
|
||||||
'-File', launcher, '-AutoStart'],
|
|
||||||
creationflags=subprocess.CREATE_NEW_CONSOLE
|
creationflags=subprocess.CREATE_NEW_CONSOLE
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -481,7 +240,7 @@ class UpdateService:
|
|||||||
else:
|
else:
|
||||||
launcher = os.path.join(self.project_root, 'start.sh')
|
launcher = os.path.join(self.project_root, 'start.sh')
|
||||||
if os.path.exists(launcher):
|
if os.path.exists(launcher):
|
||||||
subprocess.Popen(['bash', launcher, '--auto-start'], start_new_session=True)
|
subprocess.Popen(['bash', launcher], start_new_session=True)
|
||||||
else:
|
else:
|
||||||
subprocess.Popen([sys.executable, os.path.join(self.project_root, 'run.py')], start_new_session=True)
|
subprocess.Popen([sys.executable, os.path.join(self.project_root, 'run.py')], start_new_session=True)
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
|
|||||||
@@ -2,10 +2,6 @@
|
|||||||
# This script handles both setup and starting the dashboard.
|
# This script handles both setup and starting the dashboard.
|
||||||
# Run this script and choose what you want to do.
|
# Run this script and choose what you want to do.
|
||||||
|
|
||||||
# -AutoStart skips the menu and starts the dashboard straight away
|
|
||||||
# (used after self-updates so the panel comes back up unattended).
|
|
||||||
param([switch]$AutoStart)
|
|
||||||
|
|
||||||
$ErrorActionPreference = "Continue"
|
$ErrorActionPreference = "Continue"
|
||||||
|
|
||||||
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
@@ -2823,11 +2819,6 @@ function Rotate-SSHKey {
|
|||||||
|
|
||||||
Show-Banner
|
Show-Banner
|
||||||
|
|
||||||
if ($AutoStart) {
|
|
||||||
Start-Dashboard
|
|
||||||
exit $LASTEXITCODE
|
|
||||||
}
|
|
||||||
|
|
||||||
while ($true) {
|
while ($true) {
|
||||||
Show-Menu
|
Show-Menu
|
||||||
$choice = Read-Host " Enter your choice"
|
$choice = Read-Host " Enter your choice"
|
||||||
|
|||||||
@@ -1040,13 +1040,6 @@ rotate_ssh_key() {
|
|||||||
|
|
||||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
# --auto-start skips the menu and starts the dashboard straight away
|
|
||||||
# (used after self-updates so the panel comes back up unattended).
|
|
||||||
if [ "$1" = "--auto-start" ] || [ "$1" = "--autostart" ]; then
|
|
||||||
start_dashboard
|
|
||||||
exit $?
|
|
||||||
fi
|
|
||||||
|
|
||||||
show_banner
|
show_banner
|
||||||
|
|
||||||
while true; do
|
while true; do
|
||||||
|
|||||||
@@ -1320,109 +1320,6 @@ body[data-nav-layout="vertical"] .site-footer {
|
|||||||
margin-left: 216px;
|
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) {
|
@media (max-width: 768px) {
|
||||||
body[data-nav-layout="vertical"] {
|
body[data-nav-layout="vertical"] {
|
||||||
padding-left: 0;
|
padding-left: 0;
|
||||||
|
|||||||
@@ -47,7 +47,6 @@
|
|||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
<div class="nav-tools">
|
|
||||||
<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">
|
||||||
@@ -125,8 +124,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="update-banner" id="update-banner" style="display:none;"></div>
|
|
||||||
</div>
|
|
||||||
<span class="nav-conn">
|
<span class="nav-conn">
|
||||||
<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' }}
|
||||||
@@ -196,299 +193,6 @@
|
|||||||
|
|
||||||
initTheme();
|
initTheme();
|
||||||
initNavLayout();
|
initNavLayout();
|
||||||
|
|
||||||
// Update banner (channel-aware self updates)
|
|
||||||
function escHtml(s) {
|
|
||||||
return String(s == null ? '' : s)
|
|
||||||
.replace(/&/g, '&').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 ubViewVersion = null; // version picked in the dropdown; null = newest
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// All known releases for a channel, newest first. Falls back to the
|
|
||||||
// single latest entry when the server payload predates release lists.
|
|
||||||
function ubChannelReleases(channel) {
|
|
||||||
if (!ubData) return [];
|
|
||||||
const lists = ubData.releases || {};
|
|
||||||
if (Array.isArray(lists[channel]) && lists[channel].length) {
|
|
||||||
return lists[channel];
|
|
||||||
}
|
|
||||||
const entry = ubChannelLatest(channel);
|
|
||||||
return entry ? [entry] : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Numeric version compare mirroring the server's compare_versions:
|
|
||||||
// compares the X.Y.Z numbers only, so stable and experimental versions
|
|
||||||
// are comparable across channels. Returns -1, 0 or 1.
|
|
||||||
function ubCmpVer(a, b) {
|
|
||||||
const parse = (v) => {
|
|
||||||
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$/.exec(String(v || '').trim());
|
|
||||||
return m ? [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)] : null;
|
|
||||||
};
|
|
||||||
const pa = parse(a), pb = parse(b);
|
|
||||||
if (!pa && !pb) return 0;
|
|
||||||
if (!pa) return -1;
|
|
||||||
if (!pb) return 1;
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
if (pa[i] < pb[i]) return -1;
|
|
||||||
if (pa[i] > pb[i]) return 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
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() ? '<span class="ub-dot"></span>' : '';
|
|
||||||
const bell = ubData.silence_all ? '🔕' : '🔔';
|
|
||||||
el.style.display = 'block';
|
|
||||||
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(true)">${bell}${dot}</button></span>`;
|
|
||||||
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);
|
|
||||||
|
|
||||||
// Per-version picker: every known release on the viewed channel,
|
|
||||||
// newest first. Older than the running version cannot be installed;
|
|
||||||
// same-numbered is a reinstall (works across channels); newer is
|
|
||||||
// an update. Settings and protected paths are preserved either way.
|
|
||||||
const releases = ubChannelReleases(viewing);
|
|
||||||
let picked = null;
|
|
||||||
if (releases.length) {
|
|
||||||
picked = releases.find(r => r.version === ubViewVersion) || releases[0];
|
|
||||||
if (!ubViewVersion || !releases.some(r => r.version === ubViewVersion)) {
|
|
||||||
ubViewVersion = picked.version;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const cmp = picked ? ubCmpVer(picked.version, data.current_version) : 0;
|
|
||||||
const pickedSilenced = !!(picked && silenced.includes(picked.version));
|
|
||||||
const pickedCanInstall = !!(picked && cmp >= 0 && !pickedSilenced);
|
|
||||||
|
|
||||||
let opts = '';
|
|
||||||
channels.forEach(ch => {
|
|
||||||
const label = ch === data.channel ? `${ch} (yours)` : ch;
|
|
||||||
opts += `<option value="${escHtml(ch)}"${ch === viewing ? ' selected' : ''}>${escHtml(label)}</option>`;
|
|
||||||
});
|
|
||||||
|
|
||||||
let body = `<div class="ub-sub">You are on ${escHtml(data.current_version)} (${escHtml(data.channel)})</div>`;
|
|
||||||
body += `<div class="ub-row"><label>Channel: <select id="ub-channel" onchange="ubViewChannel=this.value;ubViewVersion=null;renderUpdateBanner();">${opts}</select></label>` +
|
|
||||||
`<button onclick="checkUpdatesNow()">Check now</button></div>`;
|
|
||||||
|
|
||||||
if (releases.length) {
|
|
||||||
let vopts = '';
|
|
||||||
releases.forEach(r => {
|
|
||||||
const c = ubCmpVer(r.version, data.current_version);
|
|
||||||
const tag = c < 0 ? ' — Older' : (c === 0 ? ' — Current (reinstall)' : ' — Update available');
|
|
||||||
vopts += `<option value="${escHtml(r.version)}"${picked && r.version === picked.version ? ' selected' : ''}>${escHtml(r.version)}${escHtml(tag)}</option>`;
|
|
||||||
});
|
|
||||||
body += `<div class="ub-row"><label>Version: <select id="ub-version" onchange="ubViewVersion=this.value;renderUpdateBanner();">${vopts}</select></label></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.preview && ubSafeVer(data.preview.version)) {
|
|
||||||
ubNotesCache[data.preview.version] = data.preview.notes || '';
|
|
||||||
body += `<div class="ub-title">${escHtml(data.preview.version)} <span class="ub-preview-tag">preview</span></div>` +
|
|
||||||
`<div class="ub-actions"><button class="ub-ghost" onclick="openNotesOverlay('${data.preview.version}')">Patch notes</button>` +
|
|
||||||
`<button class="ub-ghost" onclick="clearPreview()">Clear preview</button></div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (picked && ubSafeVer(picked.version)) {
|
|
||||||
ubNotesCache[picked.version] = picked.notes || '';
|
|
||||||
const isCurrent = cmp === 0;
|
|
||||||
const stateLine = cmp < 0
|
|
||||||
? `<div class="ub-sub">${escHtml(picked.version)} is older than your current version — cannot install.</div>`
|
|
||||||
: (!pickedCanInstall && pickedSilenced)
|
|
||||||
? `<div class="ub-sub">${escHtml(picked.version)} silenced - a newer version will show again.</div>`
|
|
||||||
: isCurrent
|
|
||||||
? `<div class="ub-title">Reinstall: ${escHtml(picked.version)} (same as current)</div>`
|
|
||||||
: `<div class="ub-title">Update available: ${escHtml(picked.version)}</div>`;
|
|
||||||
body += stateLine;
|
|
||||||
body += '<div class="ub-actions">' +
|
|
||||||
(picked.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${picked.version}')">Patch notes</button>` : '') +
|
|
||||||
(pickedCanInstall ? (isCurrent
|
|
||||||
? `<button onclick="applyUpdate('${picked.version}')">Reinstall ${escHtml(picked.version)}</button>`
|
|
||||||
: `<button onclick="applyUpdate('${picked.version}')">Update to ${escHtml(picked.version)}</button>`) : '') +
|
|
||||||
(cmp > 0 && !pickedSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${picked.version}')">Silence this version</button>` : '') +
|
|
||||||
'</div>';
|
|
||||||
} else if (entry && ubSafeVer(entry.version)) {
|
|
||||||
ubNotesCache[entry.version] = entry.notes || '';
|
|
||||||
const stateLine = !entry.available
|
|
||||||
? `<div class="ub-sub">${escHtml(viewing)} is up to date at ${escHtml(entry.version)}.</div>`
|
|
||||||
: isSilenced
|
|
||||||
? `<div class="ub-sub">${escHtml(entry.version)} silenced - a newer version will show again.</div>`
|
|
||||||
: `<div class="ub-title">Update available: ${escHtml(entry.version)}</div>`;
|
|
||||||
body += stateLine;
|
|
||||||
body += '<div class="ub-actions">' +
|
|
||||||
(entry.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${entry.version}')">Patch notes</button>` : '') +
|
|
||||||
(canUpdate ? `<button onclick="applyUpdate('${entry.version}')">Update to ${escHtml(entry.version)}</button>` : '') +
|
|
||||||
(entry.available && !isSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${entry.version}')">Silence this version</button>` : '') +
|
|
||||||
'</div>';
|
|
||||||
} else if (!data.preview) {
|
|
||||||
body += `<div class="ub-sub">No ${escHtml(viewing)} releases found yet.</div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
body += `<label class="ub-mute"><input type="checkbox"${data.silence_all ? ' checked' : ''} onchange="setUpdateMute(this.checked)"> Don't remind me again</label>` +
|
|
||||||
'<div class="ub-status" id="ub-status"></div>';
|
|
||||||
el.style.display = 'block';
|
|
||||||
const bellIcon = data.silence_all ? '🔕' : '🔔';
|
|
||||||
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(false)">${bellIcon}</button></span>` +
|
|
||||||
`<div class="ub-panel"><div class="ub-panel-head">Updates</div>` + body + `</div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
|
||||||
const isReinstall = ubData && version === ubData.current_version;
|
|
||||||
const action = isReinstall ? 'Reinstall' : 'Update to';
|
|
||||||
if (!confirm(`${action} ${version}? Settings and protected files are preserved. 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);
|
|
||||||
</script>
|
</script>
|
||||||
{% block scripts %}{% endblock %}
|
{% block scripts %}{% endblock %}
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -1,196 +0,0 @@
|
|||||||
"""Tests for channel-aware self updates (no network - releases are stubbed)."""
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.services.updater import (
|
|
||||||
UpdateService,
|
|
||||||
channel_of,
|
|
||||||
compare_versions,
|
|
||||||
parse_version,
|
|
||||||
release_matches_channel,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def make_releases():
|
|
||||||
return [
|
|
||||||
{'tag_name': 'v0.7.5-experimental', 'body': 'exp notes',
|
|
||||||
'zipball_url': 'https://example.com/exp.zip'},
|
|
||||||
{'tag_name': 'v0.7.4', 'body': 'stable notes',
|
|
||||||
'zipball_url': 'https://example.com/stable.zip'},
|
|
||||||
{'tag_name': 'v0.7.3-Experimental', 'body': 'old exp',
|
|
||||||
'zipball_url': 'https://example.com/old.zip'},
|
|
||||||
{'tag_name': 'v0.7.3', 'draft': True, 'body': 'draft',
|
|
||||||
'zipball_url': 'https://example.com/draft.zip'},
|
|
||||||
{'tag_name': 'not-a-version', 'body': 'x',
|
|
||||||
'zipball_url': 'https://example.com/x.zip'},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def make_service(tmp_path, version='0.7.4-experimental'):
|
|
||||||
(tmp_path / 'VERSION').write_text(version + '\n')
|
|
||||||
return UpdateService(str(tmp_path))
|
|
||||||
|
|
||||||
|
|
||||||
class TestVersions:
|
|
||||||
def test_parse(self):
|
|
||||||
assert parse_version('v0.7.5-experimental') == ((0, 7, 5), 'experimental')
|
|
||||||
assert parse_version('0.7.3') == ((0, 7, 3), '')
|
|
||||||
assert parse_version(' v1.2.3 ') == ((1, 2, 3), '')
|
|
||||||
assert parse_version('garbage') is None
|
|
||||||
assert parse_version('') is None
|
|
||||||
assert parse_version(None) is None
|
|
||||||
assert parse_version('1.2') is None
|
|
||||||
|
|
||||||
def test_channel(self):
|
|
||||||
assert channel_of('0.7.5-experimental') == 'experimental'
|
|
||||||
assert channel_of('0.7.5-Experimental') == 'experimental'
|
|
||||||
assert channel_of('0.7.3') == 'stable'
|
|
||||||
assert channel_of('garbage') == 'stable'
|
|
||||||
|
|
||||||
def test_compare(self):
|
|
||||||
assert compare_versions('0.7.5-experimental', '0.7.4-experimental') > 0
|
|
||||||
assert compare_versions('0.7.4', '0.7.4') == 0
|
|
||||||
assert compare_versions('0.7.3', '0.7.4') < 0
|
|
||||||
assert compare_versions('0.7.10', '0.7.9') > 0
|
|
||||||
assert compare_versions('garbage', '0.7.4') < 0
|
|
||||||
|
|
||||||
def test_channel_match(self):
|
|
||||||
assert release_matches_channel('v0.7.5-experimental', 'experimental')
|
|
||||||
assert release_matches_channel('v0.7.3-Experimental', 'experimental')
|
|
||||||
assert not release_matches_channel('v0.7.4', 'experimental')
|
|
||||||
assert release_matches_channel('v0.7.4', 'stable')
|
|
||||||
assert not release_matches_channel('v0.7.5-experimental', 'stable')
|
|
||||||
|
|
||||||
|
|
||||||
class TestPickLatest:
|
|
||||||
def test_experimental_picks_max_experimental(self):
|
|
||||||
best = UpdateService._pick_latest(make_releases(), 'experimental')
|
|
||||||
assert best['version'] == '0.7.5-experimental'
|
|
||||||
|
|
||||||
def test_stable_ignores_drafts(self):
|
|
||||||
best = UpdateService._pick_latest(make_releases(), 'stable')
|
|
||||||
assert best['version'] == '0.7.4'
|
|
||||||
|
|
||||||
def test_nothing_matching(self):
|
|
||||||
assert UpdateService._pick_latest([], 'stable') is None
|
|
||||||
|
|
||||||
|
|
||||||
class TestReleaseLists:
|
|
||||||
def test_collect_channel_newest_first(self):
|
|
||||||
releases = UpdateService._collect_channel(make_releases(), 'experimental')
|
|
||||||
assert [e['version'] for e in releases] == [
|
|
||||||
'0.7.5-experimental', '0.7.3-Experimental']
|
|
||||||
|
|
||||||
def test_collect_skips_drafts_and_garbage(self):
|
|
||||||
releases = UpdateService._collect_channel(make_releases(), 'stable')
|
|
||||||
assert [e['version'] for e in releases] == ['0.7.4']
|
|
||||||
|
|
||||||
def test_status_includes_lists_and_find_searches_them(self, tmp_path, monkeypatch):
|
|
||||||
svc = make_service(tmp_path, '0.7.4-experimental')
|
|
||||||
monkeypatch.setattr(svc, '_fetch_releases', make_releases)
|
|
||||||
svc.check_for_updates()
|
|
||||||
status = svc.status()
|
|
||||||
assert [e['version'] for e in status['releases']['experimental']] == [
|
|
||||||
'0.7.5-experimental', '0.7.3-Experimental']
|
|
||||||
assert [e['version'] for e in status['releases']['stable']] == ['0.7.4']
|
|
||||||
# list payload stays lean (no download URLs for the panel)
|
|
||||||
assert 'zipball_url' not in status['releases']['experimental'][0]
|
|
||||||
# an older (non-latest) version is known but refused as a downgrade
|
|
||||||
assert svc._find_release('0.7.3-Experimental')['tag'] == 'v0.7.3-Experimental'
|
|
||||||
ok, msg = svc.apply_update('0.7.3-Experimental')
|
|
||||||
assert ok is False
|
|
||||||
assert 'owngrade' in msg or 'older' in msg
|
|
||||||
|
|
||||||
def test_cross_channel_same_number_is_reinstall(self, tmp_path, monkeypatch):
|
|
||||||
# Stable 0.7.4 installing experimental 0.7.4 is numeric-equal:
|
|
||||||
# allowed past validation (fails later only on download).
|
|
||||||
svc = make_service(tmp_path, '0.7.4')
|
|
||||||
monkeypatch.setattr(svc, '_fetch_releases', lambda: [
|
|
||||||
{'tag_name': 'v0.7.4-experimental', 'body': 'x',
|
|
||||||
'zipball_url': 'https://example.com/x.zip'},
|
|
||||||
])
|
|
||||||
svc.check_for_updates()
|
|
||||||
ok, msg = svc.apply_update('0.7.4-experimental')
|
|
||||||
assert ok is False
|
|
||||||
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
|
||||||
|
|
||||||
|
|
||||||
class TestApplyRules:
|
|
||||||
def test_refuses_downgrade_without_network(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
|
||||||
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
|
||||||
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
|
||||||
ok, msg = svc.apply_update('0.7.4-experimental')
|
|
||||||
assert ok is False
|
|
||||||
assert 'owngrade' in msg or 'older' in msg
|
|
||||||
assert svc._update_in_progress is False
|
|
||||||
|
|
||||||
def test_refuses_unknown_version(self, tmp_path, monkeypatch):
|
|
||||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
|
||||||
monkeypatch.setattr(svc, '_fetch_releases', lambda: [])
|
|
||||||
ok, msg = svc.apply_update('9.9.9')
|
|
||||||
assert ok is False
|
|
||||||
assert 'Unknown version' in msg
|
|
||||||
|
|
||||||
def test_refuses_garbage(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
|
||||||
ok, msg = svc.apply_update('not-a-version!!!')
|
|
||||||
assert ok is False
|
|
||||||
|
|
||||||
def test_same_version_allowed_to_proceed(self, tmp_path, monkeypatch):
|
|
||||||
# Same version = reinstall. Must get past validation (it will then
|
|
||||||
# fail downloading from example.com, which proves the rule passed).
|
|
||||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
|
||||||
svc._latest = {'version': '0.7.5-experimental', 'tag': 'v0.7.5-experimental',
|
|
||||||
'notes': '', 'zipball_url': 'https://example.com/x.zip'}
|
|
||||||
ok, msg = svc.apply_update('0.7.5-experimental')
|
|
||||||
assert ok is False
|
|
||||||
assert 'owngrade' not in msg and 'Unknown version' not in msg
|
|
||||||
|
|
||||||
|
|
||||||
class TestPreview:
|
|
||||||
def test_set_clear_and_reject_garbage(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path)
|
|
||||||
preview = svc.set_preview('0.7.6-experimental', 'notes here')
|
|
||||||
assert preview == {'version': '0.7.6-experimental', 'notes': 'notes here'}
|
|
||||||
assert svc.status()['preview'] == preview
|
|
||||||
svc.clear_preview()
|
|
||||||
assert svc.status()['preview'] is None
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
svc.set_preview('garbage!!!')
|
|
||||||
|
|
||||||
|
|
||||||
class TestSilence:
|
|
||||||
def test_round_trip(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path)
|
|
||||||
state = svc.silence_version('0.7.6-experimental')
|
|
||||||
assert state['silenced_versions'] == ['0.7.6-experimental']
|
|
||||||
assert svc.get_silence() == state
|
|
||||||
state = svc.unsilence_version('0.7.6-experimental')
|
|
||||||
assert state['silenced_versions'] == []
|
|
||||||
state = svc.set_silence_all(True)
|
|
||||||
assert state['silence_all'] is True
|
|
||||||
state = svc.clear_silence()
|
|
||||||
assert state == {'silenced_versions': [], 'silence_all': False}
|
|
||||||
|
|
||||||
def test_status_reports_available_and_silence(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path, '0.7.5-experimental')
|
|
||||||
svc._latest = {'version': '0.7.6-experimental', 'tag': 'v0.7.6-experimental',
|
|
||||||
'notes': 'n', 'zipball_url': 'u'}
|
|
||||||
svc._other_latest = None
|
|
||||||
status = svc.status()
|
|
||||||
assert status['available'] is True
|
|
||||||
assert status['latest']['version'] == '0.7.6-experimental'
|
|
||||||
assert status['current_version'] == '0.7.5-experimental'
|
|
||||||
assert status['channel'] == 'experimental'
|
|
||||||
|
|
||||||
|
|
||||||
class TestLocalVersion:
|
|
||||||
def test_reads_version_file(self, tmp_path):
|
|
||||||
svc = make_service(tmp_path, '0.7.3')
|
|
||||||
assert svc.current_version == '0.7.3'
|
|
||||||
assert svc.channel == 'stable'
|
|
||||||
|
|
||||||
def test_missing_file_falls_back(self, tmp_path):
|
|
||||||
svc = UpdateService(str(tmp_path))
|
|
||||||
assert svc.current_version == '0.0.0'
|
|
||||||
Reference in new issue
Block a user