Files
hope-voice-api/web/token_server.py
T
snowspeeder 04c4a53594 feat: media player API, web player panel, and Hope music MCP
- web/media_server.py: FastAPI service owning the permanent library
  (library.json + ./media volume), yt-dlp YouTube Music search, queued
  download jobs with mp3 transcode (ffmpeg), per-room player desired
  state, and an HTTPS proxy for external live-stream URLs.
- agent/media_mcp.py: Hope tools — search_music, play_song,
  offer_song_choices, pause/resume/stop/skip/seek, now_playing,
  list_library, add_stream.
- agent/agent.py: media toolset wiring + conversation rule (music
  playing disables the agent mic; re-engaging pauses music).
- web UI: slide-out Music panel (search, suggestions, library, live
  stream add, play/pause, ±10s, seek, volume) with a reconciling poller
  and media_state data-channel reports.
- token server returns the minted room name; nginx serves /media/files
  as static (native Range) and proxies /media/api to the media server.
- supervisord runs media-server; compose mounts ./media and adds
  ffmpeg to the image.
2026-08-29 13:03:12 -04:00

123 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""Tiny token endpoint for the voice UI.
Serves POST /token -> { "token": "<signed JWT>" }
Signs a LiveKit access token with HS256 using the API key/secret from env.
The token carries a roomConfig claim requesting the voice-assistant agent, so
LiveKit dispatches the agent when the participant joins. Without this, the
auto-created room would get no agent at all.
Runs as a separate supervisord process; nginx proxies /token to it.
"""
import base64
import hashlib
import hmac
import json
import os
import time
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
API_KEY = os.environ.get("LIVEKIT_API_KEY", "devkey")
API_SECRET = os.environ.get("LIVEKIT_API_SECRET", "devsecret")
AGENT_NAME = os.environ.get("VOICE_AGENT_NAME", "voice-assistant")
USERS_FILE = os.environ.get("VOICE_USERS_FILE", "/etc/hope/users.json")
DEFAULT_USER = os.environ.get("VOICE_DEFAULT_USER", "shane")
def load_default_user() -> tuple[str, dict]:
with open(USERS_FILE, encoding="utf-8") as users_file:
registry = json.load(users_file)
profile = registry.get("users", {}).get(DEFAULT_USER)
if not isinstance(profile, dict):
raise ValueError(f"unknown default voice user: {DEFAULT_USER}")
return DEFAULT_USER, profile
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def make_token(room_name: str, identity: str) -> str:
now = int(time.time())
header = {"alg": "HS256", "typ": "JWT"}
payload = {
"iss": API_KEY,
"sub": identity,
"nbf": now - 5,
"exp": now + 3600,
"jti": str(uuid.uuid4()),
"identity": identity,
"video": {
"roomJoin": True,
"room": room_name,
"canPublish": True,
"canSubscribe": True,
"canPublishData": True,
},
"roomConfig": {
"agents": [{"agentName": AGENT_NAME, "jobType": "JT_ROOM"}],
},
}
h = b64url(json.dumps(header).encode())
p = b64url(json.dumps(payload).encode())
signing_input = f"{h}.{p}".encode()
sig = hmac.new(API_SECRET.encode(), signing_input, hashlib.sha256).digest()
return f"{h}.{p}.{b64url(sig)}"
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/token":
self.send_response(404)
self.end_headers()
return
length = int(self.headers.get("Content-Length", 0))
# Consume the body for protocol compatibility, but never trust a
# browser-supplied room or identity. This LAN bootstrap deployment is
# pinned to VOICE_DEFAULT_USER until the planned login flow is added.
self.rfile.read(length)
try:
user_id, profile = load_default_user()
except (OSError, ValueError, json.JSONDecodeError) as exc:
resp = json.dumps({"error": str(exc)}).encode()
self.send_response(503)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(resp)))
self.end_headers()
self.wfile.write(resp)
return
room_name = f"voice-{user_id}-{uuid.uuid4().hex[:8]}"
identity = profile.get("livekit_identity") or f"user:{user_id}"
token = make_token(room_name, identity)
resp = json.dumps(
{
"token": token,
# The room name scopes media-server player state; the UI sends
# it with every /media/api/ call.
"room": room_name,
"user": {
"id": user_id,
"display_name": profile.get("display_name") or user_id,
},
}
).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(resp)))
self.end_headers()
self.wfile.write(resp)
def log_message(self, format, *args):
pass # silence request logging
if __name__ == "__main__":
server = HTTPServer(("127.0.0.1", 8091), Handler)
print("token endpoint listening on 127.0.0.1:8091")
server.serve_forever()