libra/__init__.py
Padreug 9a1893c546 Fix startup: load Fava settings from DB instead of hardcoded defaults
castle_start() was using CastleSettings() defaults (slug=castle-ledger)
instead of reading the saved settings from the database. This caused all
Fava queries to 404 on instances where the ledger slug differs from the
default (e.g. demo-ledger).

Now loads settings from extension_settings table at startup, falling
back to defaults only if no saved settings exist.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 19:08:13 +02:00

84 lines
2.7 KiB
Python

import asyncio
from fastapi import APIRouter
from loguru import logger
from .crud import db
from .tasks import wait_for_paid_invoices
from .views import castle_generic_router
from .views_api import castle_api_router
castle_ext: APIRouter = APIRouter(prefix="/castle", tags=["Castle"])
castle_ext.include_router(castle_generic_router)
castle_ext.include_router(castle_api_router)
castle_static_files = [
{
"path": "/castle/static",
"name": "castle_static",
}
]
scheduled_tasks: list[asyncio.Task] = []
def castle_stop():
"""Clean up background tasks on extension shutdown"""
for task in scheduled_tasks:
try:
task.cancel()
except Exception as ex:
logger.warning(ex)
def castle_start():
"""Initialize Castle extension background tasks"""
from lnbits.tasks import create_permanent_unique_task
from .fava_client import init_fava_client
from .models import CastleSettings
from .tasks import wait_for_account_sync
async def _init_fava():
"""Load saved settings from DB, fall back to defaults."""
from .crud import db as castle_db
settings = None
try:
row = await castle_db.fetchone(
"SELECT * FROM extension_settings LIMIT 1",
model=CastleSettings,
)
if row:
settings = row
logger.info(f"Loaded Castle settings from DB: {settings.fava_url}/{settings.fava_ledger_slug}")
except Exception as e:
logger.warning(f"Could not load settings from DB: {e}")
if not settings:
settings = CastleSettings()
logger.info(f"Using default Castle settings: {settings.fava_url}/{settings.fava_ledger_slug}")
init_fava_client(
fava_url=settings.fava_url,
ledger_slug=settings.fava_ledger_slug,
timeout=settings.fava_timeout
)
logger.info(f"Fava client initialized: {settings.fava_url}/{settings.fava_ledger_slug}")
try:
asyncio.get_event_loop().create_task(_init_fava())
except Exception as e:
logger.error(f"Failed to initialize Fava client: {e}")
logger.warning("Castle will not function without Fava. Please configure Fava settings.")
# Start background tasks
task = create_permanent_unique_task("ext_castle", wait_for_paid_invoices)
scheduled_tasks.append(task)
# Start account sync task (runs hourly)
sync_task = create_permanent_unique_task("ext_castle_account_sync", wait_for_account_sync)
scheduled_tasks.append(sync_task)
logger.info("Castle account sync task started (runs hourly)")
__all__ = ["castle_ext", "castle_static_files", "db", "castle_start", "castle_stop"]