File size: 3,006 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""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")