ui_preferences.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """``/api/ui-preferences``: the Webapp's door to this machine's UI preferences store (#145213).
  2. Thin HTTP over :mod:`hermes_cli.ui_preferences`. The store belongs to the machine serving the
  3. Webapp, so every browser and origin that opens it reads and writes the same document native
  4. Desktop on this machine uses (through its preload capability, not this route). Mounted only on
  5. surfaces whose policy names ``ui_preferences`` (404 elsewhere) and, like every ``/api/`` route,
  6. only past the session-token / sign-in gate.
  7. """
  8. from __future__ import annotations
  9. from typing import Optional
  10. from fastapi import APIRouter, HTTPException
  11. from pydantic import BaseModel, Field
  12. from hermes_cli import ui_preferences
  13. router = APIRouter()
  14. class PreferencesPatch(BaseModel):
  15. #: Per-key changes; ``null`` deletes the key (the renderer's "back to default").
  16. values: dict[str, Optional[str]] = Field(default_factory=dict)
  17. #: This browser's first contact with the store generation: adds only the keys the store
  18. #: lacks, never overwriting or deleting one.
  19. seed: bool = False
  20. @router.get("/api/ui-preferences")
  21. def get_ui_preferences() -> dict:
  22. try:
  23. return ui_preferences.read_preferences()
  24. except ui_preferences.PreferencesBusy as exc:
  25. raise HTTPException(status_code=503, detail=str(exc)) from exc
  26. @router.patch("/api/ui-preferences")
  27. def patch_ui_preferences(body: PreferencesPatch) -> dict:
  28. try:
  29. return ui_preferences.write_preferences(body.values, seed=body.seed)
  30. except ui_preferences.PreferencesError as exc:
  31. raise HTTPException(status_code=400, detail=str(exc)) from exc
  32. except ui_preferences.PreferencesBusy as exc:
  33. raise HTTPException(status_code=503, detail=str(exc)) from exc