"""FastAPI application. Run with `python -m stemdeck` (always binds 127.0.0.1); the public cloud site serves the same app (STEMDECK_PUBLIC=1, see deploy/modal_app.py).""" from __future__ import annotations import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.trustedhost import TrustedHostMiddleware from fastapi.responses import FileResponse, JSONResponse from stemdeck import youtube from stemdeck.api import jobs, mixes, songs, system, youtube_signin from stemdeck.db import get_engine from stemdeck.device import probe_in_background from stemdeck.housekeeping import housekeeper from stemdeck.jobrunner import runner from stemdeck.logging_setup import setup_logging from stemdeck.settings import PROJECT_ROOT, details_hint, get_settings from stemdeck.visitors import VisitorMiddleware log = logging.getLogger("stemdeck") FRONTEND_DIST = PROJECT_ROOT / "frontend" / "dist" # Only requests addressed to this machine by name (locally): a DNS-rebinding page (evil.example resolving to # 127.0.0.1) sends its own host name and is turned away. The public site lists its own host names instead. ALLOWED_HOSTS = get_settings().allowed_host_list @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: setup_logging("server.log") get_engine() settings = get_settings() youtube.sweep_cookie_copies(settings) runner.start() if settings.public: housekeeper.start() probe_in_background() log.info("StemDeck backend ready%s", " (public site)" if settings.public else "") yield housekeeper.stop() runner.stop() app = FastAPI(title="StemDeck", version="0.1.0", lifespan=lifespan) app.add_middleware(VisitorMiddleware) # public site only; passes everything through locally app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS) # outermost: checked first for module in (system, songs, jobs, mixes, youtube_signin): app.include_router(module.router, prefix="/api") @app.exception_handler(Exception) async def unexpected_error(_request: Request, exc: Exception) -> JSONResponse: log.exception("unhandled error", exc_info=exc) return JSONResponse(status_code=500, content={"detail": f"Unexpected server error. {details_hint('server.log')}"}) @app.get("/{full_path:path}", include_in_schema=False) def spa(full_path: str) -> FileResponse: """Serve the built frontend (frontend/dist) when present; the dev setup uses Vite instead.""" if full_path.startswith("api/") or not FRONTEND_DIST.exists(): raise HTTPException(404, "Not found.") candidate = (FRONTEND_DIST / full_path).resolve() if full_path and candidate.is_file() and FRONTEND_DIST.resolve() in candidate.parents: return FileResponse(candidate) return FileResponse(FRONTEND_DIST / "index.html")