Files
musicmouse/python-backend/musicmouse/services/web/api.py
Martin Bauer a55cc4f67f Clock: a "Delphin Uhr" overlay with the school bus and a parents' timer
Einfg on the kiosk keyboard, or Guide (KEY_EPG) on the IR remote, shows a big
analog watch over whatever page is open, built from the Delphin Uhr mockup
without its swimming dolphin. The overlay stays mounted and is only hidden, so it
appears at once. Beside the watch, only while they run:

- The bus: on school days, a silent countdown to `general.clock.bus_time` (07:25)
  that starts `bus_lead_minutes` (60) before. School days skip weekends and the
  school and public holidays of `general.clock.subdivision` (DE-BY), fetched daily
  from openholidaysapi.org and cached under the library cache. A badge on the
  clock says whether there is school today, and why not.
- The dolphin timer, set in parent mode (5/10/15/30 minutes, or until a time).
  It lives in the backend, so a parent's phone can start it for the kiosk. When it
  runs out the kiosk opens the clock at 00:00 and a soft bell chimes on the
  device; it clears after a minute, or at the next key, tap or remote press.

Parent mode is now a way in rather than a page: `?parentMode=1` adds a 🔧 button
next to the ⌨ one, or an "Eltern" tab in the phone's dock, so the URL can stay
bookmarked. The timer comes first there, the device settings below it.

Unmapped IR buttons are logged at debug level, to find out what irserver calls a
new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:45:45 +02:00

421 lines
16 KiB
Python

"""The HTTP surface.
Commands are REST and state is a one-way websocket. That split keeps every control path
testable with ``curl`` and means a command needs no new machinery: it emits the same
intent the MQTT service and the buttons emit, and lands in the same reaction.
Search is not here on purpose. The whole index goes to the browser once and filtering
happens there, which is what makes the design's type-to-search feel instant.
"""
from __future__ import annotations
import asyncio
import logging
from datetime import datetime
from pathlib import Path
from typing import Any
import httpx2
from fastapi import APIRouter, HTTPException, Response, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse
from musicmouse.app import App
from musicmouse.config import Digit, HaConfig, RemoteSlotConfig
from musicmouse.events import (
CancelTimerRequested,
IntentEvent,
NextTrackRequested,
PauseRequested,
PlayAlbumRequested,
PlayRemoteSlotRequested,
PlayRequested,
PreviousTrackRequested,
SeekRequested,
SetTimerRequested,
SetVolumeRequested,
ToggleScreenRequested,
UserActivity,
VolumeChangeRequested,
)
from musicmouse.services.timers import timer_end
from musicmouse.services.web.hub import StateHub
from musicmouse.services.web.remote_settings import read_mapping, write_mapping
from musicmouse.services.web.schemas import (
AlbumOut,
HaConfigOut,
HaDeviceOut,
LibraryOut,
LircConfigOut,
PlayerStateOut,
PlayIn,
RemoteMappingIn,
RemoteMappingOut,
SeekIn,
SettingsIn,
SettingsOut,
TimerIn,
TippenCurriculumOut,
TippenProgressOut,
TippenRunIn,
TippenRunOut,
TippenSettingsIn,
TippenSettingsOut,
TrackCurvesOut,
TrackDetailOut,
VolumeIn,
)
from musicmouse.services.web.settings import (
read_settings,
to_device_volume,
to_percent,
write_settings,
)
from musicmouse.services.web.state import snapshot
from musicmouse.services.web.tippen_api import curriculum_out, progress_out, record_tippen_run
from musicmouse.tippen.rewards import compute_lock_state
from musicmouse.tippen.runtime import TippenRuntime
_log = logging.getLogger(__name__)
__all__ = ["build_router"]
def build_router(
app: App, hub: StateHub, config_path: Path, ha_client: httpx2.AsyncClient
) -> APIRouter:
router = APIRouter(prefix="/api")
def emit(intent: IntentEvent) -> Response:
app.bus.emit(intent)
return Response(status_code=204)
# ------------------------------------------------------------------- library
@router.get("/library")
def get_library() -> LibraryOut:
lock_state = (
compute_lock_state(app.tippen.curriculum, app.library, app.tippen.progress)
if app.tippen is not None
else None
)
return LibraryOut(
albums=[
AlbumOut.of(album, lock_state.get(album.id) if lock_state else None)
for album in app.library.albums
]
)
@router.get("/albums/{album_id}/cover")
def get_cover(album_id: str, size: str = "full", v: str | None = None) -> FileResponse:
album = app.library.get(album_id)
if album is None or album.cover is None:
# Not an error: the client paints the album's own colours instead.
raise HTTPException(status_code=404, detail="no cover")
path = album.cover
if size == "thumb":
thumb = path.with_name(f"{path.stem}.thumb.jpg")
if thumb.is_file():
path = thumb
return FileResponse(
path,
# A URL carrying `v` (the file's mtime, from `AlbumOut.cover_v`) names one
# exact set of bytes: reprocessing the art changes the library payload, so
# the client asks for a new URL. Those can be cached forever, and the
# browser then never asks again - no conditional request per card.
#
# Without `v` the id alone is not enough (the bytes behind it change whenever
# the art is reprocessed - when `MAX_COVER_PX` arrived, browsers went on
# decoding old 3000px files out of their cache), so `no-cache` makes the
# browser revalidate: it keeps the file and usually gets a 304.
headers={
"Cache-Control": (
"public, max-age=31536000, immutable" if v else "no-cache"
)
},
)
@router.get("/tracks/{album_id}/{index}/analysis")
def get_track_analysis(album_id: str, index: int) -> TrackDetailOut:
grid = app.library.beats(album_id, index)
curve = app.library.curve(album_id, index)
if grid is None and curve is None:
raise HTTPException(status_code=404, detail="not analyzed")
return TrackDetailOut(
times=list(grid.times) if grid else [],
strengths=list(grid.strengths) if grid else [],
curve=TrackCurvesOut(**curve.to_json()) if curve else None,
)
@router.post("/library/refresh", status_code=202)
async def refresh_library() -> Response:
# Returns immediately: a cold rescan reads tags from every file.
asyncio.create_task(app.rescan_library(broadcast=hub.broadcast_library)) # noqa: RUF006
return Response(status_code=202)
# --------------------------------------------------------------------- state
@router.get("/state")
def get_state() -> PlayerStateOut:
return snapshot(app)
@router.websocket("/ws")
async def websocket(socket: WebSocket) -> None:
await hub.connect(socket)
try:
while True:
# Push-only. Reading is how we notice the tab closed.
await socket.receive_text()
except WebSocketDisconnect:
pass
finally:
hub.disconnect(socket)
# ------------------------------------------------------------------ commands
@router.post("/play", status_code=204)
def play_album(body: PlayIn) -> Response:
if app.library.get(body.album_id) is None:
raise HTTPException(status_code=404, detail="no such album")
return emit(
PlayAlbumRequested(
album_id=body.album_id, track_index=body.track_index, source="web"
)
)
@router.post("/resume", status_code=204)
def resume() -> Response:
return emit(PlayRequested(source="web"))
@router.post("/pause", status_code=204)
def pause() -> Response:
return emit(PauseRequested(source="web"))
@router.post("/next", status_code=204)
def next_track() -> Response:
return emit(NextTrackRequested(source="web"))
@router.post("/previous", status_code=204)
def previous_track() -> Response:
return emit(PreviousTrackRequested(source="web"))
@router.post("/screen/toggle", status_code=204)
def toggle_screen() -> Response:
# The device's own monitor - only the kiosk page on the device calls this (its
# Del key). Without a screen section in the config nothing listens and it is a
# no-op, like the remote's power key.
return emit(ToggleScreenRequested(source="web"))
@router.post("/screen/activity", status_code=204)
def screen_activity() -> Response:
# The kiosk page on the device reports key presses and taps here, so the
# screen's idle auto-off does not blank it under a child who is browsing.
return emit(UserActivity(source="web"))
@router.post("/timer", status_code=204)
def set_timer(body: TimerIn) -> Response:
# The parents' countdown. The new state, ringing and all, arrives over the
# websocket like everything else.
end = timer_end(datetime.now(), minutes=body.minutes, until=body.until)
return emit(SetTimerRequested(ends_at=end.timestamp(), source="web"))
@router.delete("/timer", status_code=204)
def cancel_timer() -> Response:
return emit(CancelTimerRequested(source="web"))
@router.post("/seek", status_code=204)
def seek(body: SeekIn) -> Response:
return emit(SeekRequested(position=body.position, source="web"))
@router.post("/volume", status_code=204)
def set_volume(body: VolumeIn) -> Response:
general = app.config.general
if body.steps is not None:
# The IR remote's own step, in device units - see LircService._handle.
return emit(
VolumeChangeRequested(delta=general.volume_increment * body.steps, source="web")
)
if body.percent is not None:
target = body.percent
elif body.delta_percent is not None:
target = to_percent(app.player.volume, general) + body.delta_percent
else:
raise HTTPException(
status_code=422, detail="percent, delta_percent or steps required"
)
return emit(
SetVolumeRequested(
volume=to_device_volume(max(0, min(100, target)), general), source="web"
)
)
# ------------------------------------------------------------- parent mode
@router.get("/settings")
def get_settings() -> SettingsOut:
return read_settings(app.config.general)
@router.put("/settings")
async def put_settings(body: SettingsIn) -> SettingsOut:
if body.min_volume > body.max_volume:
raise HTTPException(
status_code=422, detail="min_volume must not exceed max_volume"
)
if not body.min_volume <= body.initial_volume <= body.max_volume:
raise HTTPException(
status_code=422, detail="initial_volume must lie between min and max"
)
general = app.config.general
# Applied live as well as saved: a parent lowering the ceiling expects the next
# song to be quieter, not the next boot.
values = body.model_dump()
auto_off = values.pop("screen_auto_off_minutes")
for key, value in values.items():
setattr(general, key, value)
if auto_off is not None and general.screen is not None:
# The same object ScreenService reads on every tick.
general.screen.auto_off_minutes = auto_off
app.player.set_volume_limits(general.min_volume, general.max_volume)
await asyncio.to_thread(write_settings, config_path, body)
await hub.broadcast_state()
return read_settings(general)
# ----------------------------------------------------------------- tippen
def _require_tippen() -> TippenRuntime:
if app.tippen is None:
raise HTTPException(status_code=404, detail="tippen not configured")
return app.tippen
@router.get("/tippen/curriculum")
def get_tippen_curriculum() -> TippenCurriculumOut:
runtime = _require_tippen()
return curriculum_out(runtime.curriculum, app.library)
@router.get("/tippen/progress")
def get_tippen_progress() -> TippenProgressOut:
return progress_out(_require_tippen().progress)
@router.put("/tippen/settings")
async def put_tippen_settings(body: TippenSettingsIn) -> TippenSettingsOut:
runtime = _require_tippen()
runtime.progress = runtime.progress.model_copy(
update={"settings": runtime.progress.settings.model_copy(update=body.model_dump())}
)
await asyncio.to_thread(runtime.save)
return TippenSettingsOut(
sound=runtime.progress.settings.sound,
keyboard_hint=runtime.progress.settings.keyboard_hint,
)
@router.post("/tippen/runs")
async def post_tippen_run(body: TippenRunIn) -> TippenRunOut:
runtime = _require_tippen()
if runtime.curriculum.lessons and not any(
lesson.id == body.lesson_id for lesson in runtime.curriculum.lessons
):
raise HTTPException(status_code=422, detail=f"no such lesson {body.lesson_id!r}")
result = await asyncio.to_thread(record_tippen_run, app, body)
await hub.broadcast_library()
return result
# -------------------------------------------------------------- IR remote
@router.get("/lirc")
def get_lirc_config() -> LircConfigOut:
if app.config.general.lirc is None:
raise HTTPException(status_code=404, detail="lirc not configured")
return LircConfigOut(connected=app.state.lirc_connected)
@router.post("/remote/press/{digit}", status_code=204)
def press_remote(digit: Digit) -> Response:
# A keyboard's number keys, doing what the IR remote's do. An unassigned key
# is not an error - the remote's own press of it is silent too.
return emit(PlayRemoteSlotRequested(digit=digit, source="web"))
@router.get("/remote/mapping")
def get_remote_mapping() -> RemoteMappingOut:
return read_mapping(app.config.remote, app.library)
@router.put("/remote/mapping")
async def put_remote_mapping(body: RemoteMappingIn) -> RemoteMappingOut:
resolved: dict[Digit, RemoteSlotConfig] = {}
for digit, slot in body.slots.items():
found = (
app.library.get(slot.target)
if slot.target_kind == "album"
else app.library.latest_episode(slot.target)
)
if found is None:
raise HTTPException(
status_code=422,
detail=f"key {digit}: no such {slot.target_kind} {slot.target!r}",
)
if slot.target_kind == "series" and slot.track_index:
raise HTTPException(
status_code=422,
detail=f"key {digit}: a podcast show has no fixed song to start at",
)
if slot.track_index >= len(found.tracks):
raise HTTPException(
status_code=422,
detail=f"key {digit}: {slot.target!r} has no track {slot.track_index}",
)
resolved[digit] = RemoteSlotConfig(
target_kind=slot.target_kind, target=slot.target, track_index=slot.track_index
)
app.config.remote = resolved
await asyncio.to_thread(write_mapping, config_path, resolved)
return read_mapping(app.config.remote, app.library)
# --------------------------------------------------------------- room control
#
# The browser never sees the Home Assistant token: it stays server-side, attached
# to every proxied request below. The browser only gets to know entity ids and
# display names (get_ha_config) and can ask this backend to relay a states read or
# a service call - the same shape of access the token itself grants, just without
# ever leaving the LAN device. Entity ids are not restricted to the configured
# list; that would only stop someone who already has enough access to open this
# unauthenticated API from asking Home Assistant about a different entity, which
# matches the rest of this API's "trusted LAN device" threat model.
def _require_ha() -> HaConfig:
ha = app.config.general.ha
if ha is None:
raise HTTPException(status_code=404, detail="ha not configured")
return ha
async def _proxy(method: str, path: str, ha: HaConfig, **kwargs: Any) -> Response:
try:
upstream = await ha_client.request(
method, f"{ha.url}{path}", headers={"Authorization": f"Bearer {ha.token}"}, **kwargs
)
except httpx2.HTTPError as exc:
raise HTTPException(
status_code=502, detail=f"Home Assistant unreachable: {exc}"
) from exc
return Response(
content=upstream.content,
status_code=upstream.status_code,
media_type=upstream.headers.get("content-type", "application/json"),
)
@router.get("/ha")
def get_ha_config() -> HaConfigOut:
ha = _require_ha()
return HaConfigOut(
devices=[HaDeviceOut(entity_id=d.entity_id, name=d.name) for d in ha.devices],
scenes=[HaDeviceOut(entity_id=d.entity_id, name=d.name) for d in ha.scenes],
)
@router.get("/ha/states/{entity_id}")
async def get_ha_state(entity_id: str) -> Response:
return await _proxy("GET", f"/api/states/{entity_id}", _require_ha())
@router.post("/ha/services/{domain}/{service}")
async def call_ha_service(domain: str, service: str, body: dict[str, Any]) -> Response:
return await _proxy("POST", f"/api/services/{domain}/{service}", _require_ha(), json=body)
return router