# fabledscryer/settings/routes.py from __future__ import annotations import json import logging from pathlib import Path from quart import Blueprint, current_app, render_template, request, redirect, url_for from fabledscryer.auth.middleware import require_role from fabledscryer.models.users import UserRole from fabledscryer.core.settings import ( DEFAULTS, get_all_settings, set_setting, to_smtp_cfg, to_webhook_cfg, to_ansible_cfg, to_plugins_cfg, ) settings_bp = Blueprint("settings", __name__, url_prefix="/settings") logger = logging.getLogger(__name__) def _discover_plugins() -> list[dict]: """Scan PLUGIN_DIR for plugin.yaml files.""" import yaml plugin_dir = Path(current_app.config.get("PLUGIN_DIR", "plugins")).resolve() plugins = [] if not plugin_dir.exists(): return plugins for entry in sorted(plugin_dir.iterdir()): yaml_path = entry / "plugin.yaml" if entry.is_dir() and yaml_path.exists(): try: with yaml_path.open() as f: meta = yaml.safe_load(f) or {} meta["_dir"] = entry.name plugins.append(meta) except Exception: logger.warning("Could not read %s", yaml_path) return plugins def _merge_plugin_config(discovered: list[dict], plugins_cfg: dict) -> None: """Merge stored settings into discovered plugin dicts in-place.""" for plugin in discovered: name = plugin["_dir"] stored = plugins_cfg.get(name, {}) plugin["_enabled"] = stored.get("enabled", False) defaults = plugin.get("config", {}) plugin["_config"] = {**defaults, **{k: v for k, v in stored.items() if k != "enabled"}} async def _reload_app_config() -> None: """Reload app.config from DB so settings take effect without restart.""" async with current_app.db_sessionmaker() as db: fresh = await get_all_settings(db) current_app.config.update( SESSION_LIFETIME_HOURS=fresh.get("session.lifetime_hours", 8), DATA_RETENTION_DAYS=fresh.get("data.retention_days", 90), MONITORS_POLL_INTERVAL=fresh.get("monitors.poll_interval_seconds", 60), SMTP=to_smtp_cfg(fresh), WEBHOOK=to_webhook_cfg(fresh), ANSIBLE=to_ansible_cfg(fresh), PLUGINS=to_plugins_cfg(fresh), ) # ── Redirect root to general tab ────────────────────────────────────────────── @settings_bp.get("/") @require_role(UserRole.admin) async def index(): return redirect(url_for("settings.general")) # ── General ─────────────────────────────────────────────────────────────────── @settings_bp.get("/general/") @require_role(UserRole.admin) async def general(): async with current_app.db_sessionmaker() as db: settings = await get_all_settings(db) return await render_template("settings/general.html", settings=settings) @settings_bp.post("/general/") @require_role(UserRole.admin) async def save_general(): form = await request.form async with current_app.db_sessionmaker() as db: async with db.begin(): await set_setting(db, "session.lifetime_hours", int(form.get("session.lifetime_hours", 8))) await set_setting(db, "data.retention_days", int(form.get("data.retention_days", 90))) await set_setting(db, "monitors.poll_interval_seconds", int(form.get("monitors.poll_interval_seconds", 60))) await _reload_app_config() return redirect(url_for("settings.general")) # ── Notifications (SMTP + Webhook) ──────────────────────────────────────────── @settings_bp.get("/notifications/") @require_role(UserRole.admin) async def notifications(): async with current_app.db_sessionmaker() as db: settings = await get_all_settings(db) return await render_template("settings/notifications.html", settings=settings) @settings_bp.post("/notifications/") @require_role(UserRole.admin) async def save_notifications(): form = await request.form async with current_app.db_sessionmaker() as db: async with db.begin(): recipients_raw = form.get("smtp.recipients", "") recipients = [r.strip() for r in recipients_raw.split(",") if r.strip()] await set_setting(db, "smtp.host", form.get("smtp.host", "")) await set_setting(db, "smtp.port", int(form.get("smtp.port", 587))) await set_setting(db, "smtp.tls", "smtp.tls" in form) await set_setting(db, "smtp.username", form.get("smtp.username", "")) if form.get("smtp.password"): await set_setting(db, "smtp.password", form.get("smtp.password")) await set_setting(db, "smtp.recipients", recipients) await set_setting(db, "webhook.url", form.get("webhook.url", "")) await set_setting(db, "webhook.template", form.get("webhook.template", "")) await _reload_app_config() return redirect(url_for("settings.notifications")) # ── Ansible Sources ─────────────────────────────────────────────────────────── @settings_bp.get("/ansible/") @require_role(UserRole.admin) async def ansible(): async with current_app.db_sessionmaker() as db: settings = await get_all_settings(db) return await render_template("settings/ansible.html", settings=settings) @settings_bp.post("/ansible/") @require_role(UserRole.admin) async def save_ansible(): form = await request.form sources_raw = form.get("ansible.sources", "[]") try: sources = json.loads(sources_raw) if not isinstance(sources, list): sources = [] except json.JSONDecodeError: sources = [] async with current_app.db_sessionmaker() as db: async with db.begin(): await set_setting(db, "ansible.sources", sources) await _reload_app_config() return redirect(url_for("settings.ansible")) # ── Plugins ─────────────────────────────────────────────────────────────────── @settings_bp.get("/plugins/") @require_role(UserRole.admin) async def plugins(): async with current_app.db_sessionmaker() as db: settings = await get_all_settings(db) discovered = _discover_plugins() _merge_plugin_config(discovered, to_plugins_cfg(settings)) return await render_template( "settings/plugins.html", discovered_plugins=discovered, settings=settings, ) @settings_bp.post("/plugins/") @require_role(UserRole.admin) async def save_plugins(): form = await request.form discovered = _discover_plugins() async with current_app.db_sessionmaker() as db: async with db.begin(): # Save plugin index URL if provided index_url = form.get("plugins.index_url", "").strip() await set_setting(db, "plugins.index_url", index_url) for plugin in discovered: name = plugin["_dir"] enabled = f"plugin.{name}.enabled" in form plugin_cfg: dict = {"enabled": enabled} for cfg_key in plugin.get("config", {}).keys(): field_name = f"plugin.{name}.{cfg_key}" default_val = plugin["config"][cfg_key] if isinstance(default_val, dict): sub_dict = {} for sub_key, sub_default in default_val.items(): sub_field = f"plugin.{name}.{cfg_key}.{sub_key}" if isinstance(sub_default, bool): sub_dict[sub_key] = sub_field in form elif sub_field in form: raw_sub = form[sub_field] if isinstance(sub_default, int): try: sub_dict[sub_key] = int(raw_sub) except ValueError: sub_dict[sub_key] = sub_default else: sub_dict[sub_key] = raw_sub else: sub_dict[sub_key] = sub_default plugin_cfg[cfg_key] = sub_dict elif field_name in form: raw_val = form[field_name] if isinstance(default_val, bool): plugin_cfg[cfg_key] = raw_val.lower() in ("1", "true", "yes", "on") elif isinstance(default_val, int): try: plugin_cfg[cfg_key] = int(raw_val) except ValueError: plugin_cfg[cfg_key] = default_val else: plugin_cfg[cfg_key] = raw_val await set_setting(db, f"plugin.{name}", plugin_cfg) await _reload_app_config() from fabledscryer.core.plugin_index import clear_catalog_cache clear_catalog_cache() return redirect(url_for("settings.plugins")) # ── Plugin catalog (HTMX partial) ───────────────────────────────────────────── @settings_bp.get("/plugins/catalog/") @require_role(UserRole.admin) async def plugins_catalog(): """HTMX partial: list plugins available in the remote catalog.""" async with current_app.db_sessionmaker() as db: settings = await get_all_settings(db) index_url = settings.get("plugins.index_url", "").strip() if not index_url: return await render_template( "settings/_catalog_partial.html", catalog=[], installed_names=set(), loaded_names=set(), error="No plugin index URL configured.", ) from fabledscryer.core.plugin_index import fetch_catalog from fabledscryer.core.plugin_manager import _LOADED_PLUGINS force = request.args.get("refresh") == "1" try: catalog = await fetch_catalog(index_url, force=force) error = None if catalog else "Catalog is empty or could not be fetched." except Exception as exc: catalog = [] error = str(exc) discovered = _discover_plugins() installed_names = {p["_dir"] for p in discovered} installed_versions = {p["_dir"]: p.get("version", "0.0.0") for p in discovered} return await render_template( "settings/_catalog_partial.html", catalog=catalog, installed_names=installed_names, installed_versions=installed_versions, loaded_names=_LOADED_PLUGINS, error=error, ) # ── Plugin install ───────────────────────────────────────────────────────────── @settings_bp.post("/plugins/install/") @require_role(UserRole.admin) async def install_plugin(name: str): """Download and install a plugin from the catalog, then hot-reload it.""" form = await request.form download_url = form.get("download_url", "").strip() checksum = form.get("checksum_sha256", "").strip() if not download_url: return await render_template( "settings/_install_result.html", name=name, success=False, message="No download URL provided.", ) from fabledscryer.core.plugin_manager import download_and_install_plugin, hot_reload_plugin ok, msg = await download_and_install_plugin( current_app._get_current_object(), name, download_url, checksum ) if not ok: return await render_template( "settings/_install_result.html", name=name, success=False, message=msg, ) # Attempt hot-reload ok2, msg2 = hot_reload_plugin(current_app._get_current_object(), name) if ok2: return await render_template( "settings/_install_result.html", name=name, success=True, message=f"Installed and activated. {msg2}", ) else: return await render_template( "settings/_install_result.html", name=name, success=True, message=f"Installed. {msg2}", restart_required=True, ) # ── Plugin hot-reload ────────────────────────────────────────────────────────── @settings_bp.post("/plugins/reload/") @require_role(UserRole.admin) async def reload_plugin(name: str): """Hot-reload a plugin that was installed but not yet active.""" from fabledscryer.core.plugin_manager import hot_reload_plugin ok, msg = hot_reload_plugin(current_app._get_current_object(), name) return await render_template( "settings/_install_result.html", name=name, success=ok, message=msg, restart_required=(not ok and "restart" in msg.lower()), ) # ── App restart ─────────────────────────────────────────────────────────────── @settings_bp.post("/plugins/restart/") @require_role(UserRole.admin) async def restart_app_route(): """Trigger an in-app restart (replaces the process via os.execv).""" import asyncio from fabledscryer.core.plugin_manager import restart_app # Schedule the restart slightly after we return the response async def _delayed_restart(): await asyncio.sleep(0.5) restart_app() asyncio.create_task(_delayed_restart()) return await render_template("settings/_restart_pending.html")