diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 615db1727..3a4decd55 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -285,6 +285,8 @@ jobs: node --check portal/static/js/booth-reconnect.js node --check portal/static/js/mic-activity.js node --check portal/static/js/whep-listener.js + node --check portal/static/js/embed-player.js + node --check portal/static/js/audio-scheduler.js node --check portal/static/js/admin.js node --check portal/static/js/attendance.js node --check portal/static/js/booth-detail.js @@ -308,6 +310,7 @@ jobs: run: | node tests/test_audio_scheduler.js node tests/test_tts_parser.js + node tests/test_embed_player.js node --test tests/test_demo_modal.js node tests/test_listener_event.js node tests/test_whep_listener.js diff --git a/portal/auth.py b/portal/auth.py index f06e16914..53fb4c478 100644 --- a/portal/auth.py +++ b/portal/auth.py @@ -162,17 +162,19 @@ def create_listener_token(*, event_slug: str) -> str: return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256") -def create_embed_token(*, event_slug: str) -> str: +def create_embed_token(*, event_slug: str, room_id: int | None = None) -> str: """Create a short-lived JWT for embed iframe access. Identical claim shape to create_listener_token (kind='listener', event_slug) so it passes both the embed route's claim checks and the /ws/captions WebSocket auth's booth_id.startswith(event_slug + '-') check. + When ``room_id`` is provided, /embed, /ws/captions, and /ws/tts enforce + that the target channel belongs to that room. Uses a shorter expiry (embed_token_expiry_seconds, default 30 min) because the token is visible in the iframe src= attribute in the third party's HTML. """ now = datetime.now(timezone.utc) - payload = { + payload: dict[str, object] = { "sub": str(uuid.uuid4()), "kind": LISTENER_TOKEN_KIND, "purpose": "embed", @@ -180,6 +182,8 @@ def create_embed_token(*, event_slug: str) -> str: "iat": now, "exp": now + timedelta(seconds=settings.embed_token_expiry_seconds), } + if room_id is not None: + payload["room_id"] = room_id return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256") @@ -193,6 +197,12 @@ class WSAuthError(Exception): pass +class EmbedTokenExpiredError(WSAuthError): + """Raised when a short-lived embed WebSocket token has expired.""" + + pass + + def token_issued_at(payload: dict) -> datetime | None: issued_at = payload.get("iat") if isinstance(issued_at, bool) or not isinstance(issued_at, (int, float)): diff --git a/portal/routers/listener.py b/portal/routers/listener.py index d0991bcbd..6ff32e001 100644 --- a/portal/routers/listener.py +++ b/portal/routers/listener.py @@ -3,12 +3,14 @@ import asyncio import json import re +from dataclasses import dataclass from pathlib import Path from typing import Any, TypedDict import jwt from fastapi import APIRouter, HTTPException, Query, Request, status from fastapi.templating import Jinja2Templates +from sqlalchemy.ext.asyncio import AsyncSession from starlette.responses import JSONResponse, Response from portal.auth import ( @@ -30,6 +32,7 @@ ) from portal.globals import _JS_CACHE_BUST, asset_version_context from portal.join_code_limit import JoinCodeThrottled, verify_join_code +from portal.models import Event, Room from portal.overlay_channels import overlay_channels from portal.utils import _ensure_mediamtx_path @@ -37,7 +40,7 @@ _ALLOWED_THEMES = {"dark", "light"} _ALLOWED_FONTS = {"inter", "roboto", "outfit"} _PRIMARY_COLOR_RE = re.compile(r"^[0-9a-fA-F]{3,6}$") -_DEFAULT_PRIMARY = "3b82f6" # VoxBento blue +_DEFAULT_PRIMARY = "2563eb" # VoxBento primary blue (--vb-color-primary) _BASE_DIR = Path(__file__).resolve().parent.parent templates = Jinja2Templates(directory=str(_BASE_DIR / "templates"), context_processors=[asset_version_context]) @@ -250,7 +253,7 @@ async def subtitle_overlay( return response -def _verify_embed_token(token: str, event_slug: str) -> None: +def _verify_embed_token(token: str, event_slug: str) -> dict[str, Any]: """Validate the embed token and its listener/embed claims for ``event_slug``. Raises ``HTTPException(403)`` for a missing, expired, invalid, or mismatched token. @@ -272,10 +275,20 @@ def _verify_embed_token(token: str, event_slug: str) -> None: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token must be an embed token.") if payload.get("event_slug") != event_slug: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this event.") + return payload -async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tuple[int, int]: - """Resolve the target room id and its audio delay for an embed request.""" +@dataclass(frozen=True) +class EmbedChannel: + booth_id: str + channel_id: str + audio_mode: str = "whep" + tts_booth_id: str = "" + tts_language_code: str = "" + + +async def _resolve_embed_room(session: AsyncSession, ev: Event, room_id: int | None) -> tuple[Room, int]: + """Resolve the target room and its audio delay for an embed request.""" rooms = await list_rooms_for_event(session, ev.id, limit=None) if room_id is None: if not rooms: @@ -285,46 +298,63 @@ async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tup status_code=status.HTTP_400_BAD_REQUEST, detail="This event has multiple rooms. Please use the /embed/{event_slug}/{room_id}/{language_code} URL instead.", ) - return rooms[0].id, rooms[0].audio_delay_ms + return rooms[0], rooms[0].audio_delay_ms room = next((r for r in rooms if r.id == room_id), None) if not room: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Room not found.") - return room.id, room.audio_delay_ms + return room, room.audio_delay_ms async def _resolve_embed_channel( - session: Any, ev: Any, event_slug: str, room_id: int, language_code: str -) -> tuple[str, str]: - """Resolve the booth id and mediamtx channel id for the requested language.""" + session: AsyncSession, ev: Event, event_slug: str, room: Room, language_code: str +) -> EmbedChannel: + """Resolve the booth id, mediamtx channel id, and audio mode for the requested language.""" from portal.booth_identity import make_booth_id, make_mediamtx_path + norm_lang = language_code.lower() try: - booth_id = make_booth_id(ev.slug, room_id, language_code.lower()) - channel_id = make_mediamtx_path(ev.slug, room_id, language_code.lower()) + booth_id = make_booth_id(ev.slug, room.id, norm_lang) + channel_id = make_mediamtx_path(ev.slug, room.id, norm_lang) except ValueError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invalid language code.") - if language_code.lower() != "floor": - db_booths = await list_booths_for_event(session, ev.id, limit=None) - booth = next( - (b for b in db_booths if b.language_code.lower() == language_code.lower() and b.room_id == room_id), + if norm_lang == "floor": + return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep") + + db_booths = await list_booths_for_room(session, room.id) + booth = next((b for b in db_booths if b.language_code.lower() == norm_lang), None) + if booth is not None: + return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep") + + if room.floor_translation_enabled: + lang = next( + (item for item in room.translation_languages if item.enabled and item.language_code.lower() == norm_lang), None, ) - if booth is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"No booth for language '{language_code}' in event '{event_slug}'.", - ) - - return booth_id, channel_id + if lang is not None: + if room.floor_tts_enabled and lang.tts_enabled: + floor_booth_id = make_booth_id(ev.slug, room.id, "floor") + return EmbedChannel( + booth_id=booth_id, + channel_id="", + audio_mode="tts", + tts_booth_id=floor_booth_id, + tts_language_code=norm_lang, + ) + return EmbedChannel(booth_id=booth_id, channel_id="", audio_mode="none") + + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"No booth for language '{language_code}' in event '{event_slug}'.", + ) def _sanitize_embed_theme( theme: str, font: str, primary_color: str, custom_css_url: str | None ) -> tuple[str, str, str, str | None]: """Sanitize embed theming params: theme, font, and color are allowlisted; custom CSS is accepted from arbitrary HTTPS URLs.""" - safe_theme = theme if theme in _ALLOWED_THEMES else "dark" + safe_theme = theme if theme in _ALLOWED_THEMES else "light" safe_font = font if font in _ALLOWED_FONTS else "inter" safe_primary = primary_color if _PRIMARY_COLOR_RE.match(primary_color) else _DEFAULT_PRIMARY @@ -369,6 +399,8 @@ def _build_embed_context( postmessage_target_origin: str, allowed_origins_list: list[str], audio_delay_ms: int, + audio_mode: str = "whep", + tts_url: str = "", ) -> dict[str, Any]: """Assemble the Jinja2 context for the embed template.""" return { @@ -376,6 +408,8 @@ def _build_embed_context( "language_code": language_code, "whep_url": whep_url, "caption_url": caption_url, + "tts_url": tts_url, + "audio_mode": audio_mode, "token": token, "theme": safe_theme, "primary_color": safe_primary, @@ -406,7 +440,7 @@ async def _embed_listener_impl( target_lang: str | None, ): # Authentication - _verify_embed_token(token, event_slug) + token_payload = _verify_embed_token(token, event_slug) # Resolve booth async with get_session() as session: @@ -414,12 +448,21 @@ async def _embed_listener_impl( if not ev: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found.") - resolved_room_id, audio_delay_ms = await _resolve_embed_room(session, ev, room_id) - booth_id, channel_id = await _resolve_embed_channel(session, ev, event_slug, resolved_room_id, language_code) + room, audio_delay_ms = await _resolve_embed_room(session, ev, room_id) + token_room = token_payload.get("room_id") + if token_room is not None and str(token_room) != str(room.id): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this room.") + channel = await _resolve_embed_channel(session, ev, event_slug, room, language_code) - whep_url = f"{settings.mediamtx_whip_base}/{channel_id}/whep" + whep_url = f"{settings.mediamtx_whip_base}/{channel.channel_id}/whep" if channel.audio_mode == "whep" else "" host = settings.public_base_url.replace("https://", "").replace("http://", "") - caption_url = f"wss://{host}/ws/captions/{booth_id}" + caption_url = f"wss://{host}/ws/captions/{channel.booth_id}" + tts_url = ( + f"wss://{host}/ws/tts/{room.id}/{channel.tts_language_code}/{channel.tts_booth_id}" + if channel.audio_mode == "tts" + else "" + ) + captions_effective = captions or channel.audio_mode == "none" # Sanitize theming params safe_theme, safe_font, safe_primary, safe_custom_css = _sanitize_embed_theme( @@ -443,13 +486,15 @@ async def _embed_listener_impl( safe_theme=safe_theme, safe_primary=safe_primary, safe_font=safe_font, - captions=captions, + captions=captions_effective, safe_custom_css=safe_custom_css, target_lang=target_lang, headless=headless, postmessage_target_origin=postmessage_target_origin, allowed_origins_list=allowed_origins_list, audio_delay_ms=audio_delay_ms, + audio_mode=channel.audio_mode, + tts_url=tts_url, ) return templates.TemplateResponse(request=request, name="embed.html", context=context, headers=response_headers) @@ -461,7 +506,7 @@ async def embed_listener_legacy( event_slug: str, language_code: str, token: str = Query(""), - theme: str = Query("dark"), + theme: str = Query("light"), primary_color: str = Query(_DEFAULT_PRIMARY, alias="primaryColor"), font: str = Query("inter"), captions: bool = Query(False), @@ -493,7 +538,7 @@ async def embed_listener_scoped( room_id: int, language_code: str, token: str = Query(""), - theme: str = Query("dark"), + theme: str = Query("light"), primary_color: str = Query(_DEFAULT_PRIMARY, alias="primaryColor"), font: str = Query("inter"), captions: bool = Query(False), diff --git a/portal/static/css/embed.css b/portal/static/css/embed.css index cc38706c8..e7b225766 100644 --- a/portal/static/css/embed.css +++ b/portal/static/css/embed.css @@ -24,8 +24,9 @@ body { width: 100%; max-width: 480px; background: var(--surface); - border: 1.5px solid var(--border); - border-radius: 12px; + border: 1px solid var(--border); + border-radius: var(--vb-radius-md); + box-shadow: var(--vb-shadow-sm); padding: 20px 24px; display: flex; flex-direction: column; @@ -60,8 +61,9 @@ body { flex-shrink: 0; transition: background 0.3s; } -.status-dot.live { background: #22c55e; box-shadow: 0 0 6px #22c55e88; } -.status-dot.error { background: #ef4444; } +.status-dot.live, +.status-dot.captions { background: var(--vb-color-live); box-shadow: 0 0 6px color-mix(in srgb, var(--vb-color-live) 53%, transparent); } +.status-dot.error { background: var(--vb-color-danger); } .status-dot.connecting { background: var(--primary); animation: pulse 1.2s infinite; } @keyframes pulse { @@ -70,6 +72,9 @@ body { } /* ── Play button ─────────────────────────────────────────────────────── */ +.play-btn[hidden] { + display: none; +} .play-btn { display: flex; align-items: center; @@ -78,15 +83,15 @@ body { width: 100%; padding: 12px 20px; border: none; - border-radius: 8px; + border-radius: var(--vb-radius-sm); background: var(--primary); color: #fff; font-family: var(--font); font-size: 14px; - font-weight: 700; + font-weight: 600; cursor: pointer; transition: opacity 0.15s, transform 0.1s; - letter-spacing: 0.02em; + letter-spacing: 0.01em; } .play-btn:hover:not(:disabled) { opacity: 0.88; transform: translateY(-1px); } .play-btn:active:not(:disabled) { transform: translateY(0); } @@ -98,9 +103,9 @@ body { max-height: 160px; overflow-y: auto; padding: 10px 14px; - background: var(--bg); + background: var(--surface-2, var(--bg)); border: 1px solid var(--border); - border-radius: 8px; + border-radius: var(--vb-radius-sm); font-size: 13px; line-height: 1.55; color: var(--text); diff --git a/portal/static/js/audio-scheduler.js b/portal/static/js/audio-scheduler.js index 3dd199342..f0beb54e0 100644 --- a/portal/static/js/audio-scheduler.js +++ b/portal/static/js/audio-scheduler.js @@ -43,6 +43,7 @@ function createAudioScheduler(audioCtx, opts) { ? opts.comfortNoiseLevelDb : -40; var COMFORT_NOISE_FADE_SEC = typeof opts.comfortNoiseFadeSec === 'number' ? opts.comfortNoiseFadeSec : 0.5; + var destination = opts.destination || audioCtx.destination; /** @type {number} audioCtx.currentTime when the last scheduled buffer ends */ var nextScheduledTime = 0; @@ -95,7 +96,7 @@ function createAudioScheduler(audioCtx, opts) { comfortNoiseGain.gain.linearRampToValueAtTime( 1, audioCtx.currentTime + COMFORT_NOISE_FADE_SEC ); - comfortNoiseGain.connect(audioCtx.destination); + comfortNoiseGain.connect(destination); comfortNoiseSource = audioCtx.createBufferSource(); comfortNoiseSource.buffer = getComfortNoiseBuffer(); @@ -196,7 +197,7 @@ function createAudioScheduler(audioCtx, opts) { var source = audioCtx.createBufferSource(); source.buffer = audioBuffer; - source.connect(audioCtx.destination); + source.connect(destination); source.onended = function () { scheduledSources.delete(source); }; diff --git a/portal/static/js/embed-player.js b/portal/static/js/embed-player.js index 5a2aef49d..cabfc6609 100644 --- a/portal/static/js/embed-player.js +++ b/portal/static/js/embed-player.js @@ -1,63 +1,117 @@ -'use strict'; - -(function() { - document.addEventListener('DOMContentLoaded', function() { - const configEl = document.getElementById('embed-config'); - if (!configEl) { - console.error('Embed configuration not found.'); - return; - } - - let config; - try { - config = JSON.parse(configEl.textContent); - } catch (e) { - console.error('Failed to parse embed configuration:', e); - return; - } +export function isJwtExpired(token, nowSeconds = Date.now() / 1000) { + if (!token || typeof token !== 'string') return false; + const parts = token.split('.'); + if (parts.length !== 3) return false; + try { + const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/'); + const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4); + const json = typeof atob === 'function' + ? atob(padded) + : Buffer.from(padded, 'base64').toString('utf8'); + const payload = JSON.parse(json); + return typeof payload.exp === 'number' && payload.exp <= nowSeconds; + } catch (err) { + console.error('Failed to decode embed token expiry:', err); + return false; + } +} - const WHEP_URL = config.whep_url; - const CAPTION_URL = config.caption_url; - const CAPTIONS_ON = config.captions_enabled; - const EMBED_TOKEN = config.token; - const TARGET_LANG = config.target_lang_code; - const SOURCE_LANG = config.source_lang_code; +export function initEmbedPlayer(env = {}) { + const doc = env.document || document; + const win = env.window || window; + const WebSocketCtor = env.WebSocket || win.WebSocket; + const AudioContextCtor = env.AudioContext || win.AudioContext || win.webkitAudioContext; + const whepFactory = env.createWhepClient || win.createWhepClient; + const ttsParser = env.TTSParser || win.TTSParser; + const audioSchedulerFactory = env.AudioScheduler || win.AudioScheduler; + const schedule = env.setTimeout || win.setTimeout.bind(win); + const cancel = env.clearTimeout || win.clearTimeout.bind(win); - const audioEl = document.getElementById('embed-audio'); - const playBtn = document.getElementById('play-btn'); - const statusDot = document.getElementById('status-dot'); - const statusText = document.getElementById('status-text'); - const captionsEl = document.getElementById('captions-box') || null; + const configEl = doc.getElementById('embed-config'); + if (!configEl) { + console.error('Embed configuration not found.'); + return null; + } - let playing = false; + let config; + try { + config = JSON.parse(configEl.textContent); + } catch (err) { + console.error('Failed to parse embed configuration:', err); + return null; + } - function setStatus(state, text) { - statusDot.className = 'status-dot ' + (state || ''); - statusText.textContent = text; - } + const AUDIO_MODE = config.audio_mode || 'whep'; + const WHEP_URL = config.whep_url || ''; + const TTS_URL = config.tts_url || ''; + const CAPTION_URL = config.caption_url || ''; + const CAPTIONS_ON = Boolean(config.captions_enabled); + const EMBED_TOKEN = config.token || ''; + const TARGET_LANG = config.target_lang_code || ''; + const SOURCE_LANG = config.source_lang_code || ''; + const AUDIO_DELAY_MS = Math.min(Math.max(Number(config.audio_delay_ms) || 0, 0), 10000); + + const audioEl = doc.getElementById('embed-audio'); + const playBtn = doc.getElementById('play-btn'); + const statusDot = doc.getElementById('status-dot'); + const statusText = doc.getElementById('status-text'); + const captionsEl = doc.getElementById('captions-box') || null; - function setExpired() { - setStatus('error', 'Session expired'); + let playing = false; + let expired = false; + let captionWs = null; + let ttsWs = null; + let captionRetryTimer = null; + let ttsRetryTimer = null; + + function postToParent(type, payload) { + if (!config.headless || !win.parent) return; + win.parent.postMessage( + { source: 'voxbento-embed', v: 1, type, payload }, + config.target_origin, + ); + } + + function setStatus(state, text) { + statusDot.className = 'status-dot ' + (state || ''); + statusText.textContent = text; + } + + function setExpired() { + if (expired) return; + expired = true; + playing = false; + setStatus('error', 'Session expired'); + if (playBtn) { playBtn.textContent = '\u26a0 Session Expired \u2014 Reload Host Page'; playBtn.disabled = true; } + if (audioController && audioController.stop) audioController.stop(); + if (captionRetryTimer) { cancel(captionRetryTimer); captionRetryTimer = null; } + if (ttsRetryTimer) { cancel(ttsRetryTimer); ttsRetryTimer = null; } + if (captionWs) { const ws = captionWs; captionWs = null; ws.close(); } + if (ttsWs) { const ws = ttsWs; ttsWs = null; ws.close(); } + postToParent('error', { code: 'session_expired', message: 'Embed token expired' }); + } + + function buildWsUrl(httpOrWsUrl) { + const wsProto = win.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const urlPath = new URL(httpOrWsUrl).pathname; + return wsProto + '//' + win.location.host + urlPath + '?token=' + encodeURIComponent(EMBED_TOKEN); + } - const whep = createWhepClient(); + // ── Audio Controllers ────────────────────────────────────────────────── + function createWhepController() { + const whep = whepFactory(); + let detached = false; whep.start({ whepUrl: WHEP_URL, - audioEl: audioEl, + audioEl, audioDelayMs: config.audio_delay_ms, - onState: function(s) { - if (config.headless) { - window.parent.postMessage({ - source: 'voxbento-embed', - v: 1, - type: 'booth_state', - payload: { state: s.peerConnection } - }, config.target_origin); - } - + onState(s) { + if (detached) return; + postToParent('booth_state', { state: s.peerConnection }); if (s.peerConnection === 'connected') { setStatus('live', 'Live'); playBtn.disabled = false; @@ -69,176 +123,513 @@ setStatus('connecting', 'Connecting\u2026'); } }, - onLog: function() {}, + onLog() {}, }); - playBtn.addEventListener('click', function() { - if (!playing) { - audioEl.play().then(function() { - playing = true; - playBtn.textContent = '\u23f8 Pause'; - }).catch(function() { - setStatus('error', 'Playback blocked \u2014 check browser permissions'); - }); - } else { + let whepPlayRequestId = 0; + + return { + play() { + if (expired) return Promise.reject(new Error('Session expired')); + const reqId = ++whepPlayRequestId; + return audioEl.play().then( + () => { + if (reqId !== whepPlayRequestId) return; + if (expired) { + audioEl.pause(); + return; + } + playing = true; + playBtn.textContent = '\u23f8 Pause'; + }, + (err) => { + if (reqId !== whepPlayRequestId || expired) return; + throw err; + }, + ); + }, + pause() { + whepPlayRequestId++; audioEl.pause(); playing = false; playBtn.textContent = '\u25b6 Play Audio'; + }, + stop() { + detached = true; + whepPlayRequestId++; + if (whep && typeof whep.stop === 'function') whep.stop(); + audioEl.pause(); + playing = false; + }, + setVolume(v) { + audioEl.volume = v; + }, + }; + } + + function createTtsController() { + let audioCtx = null; + let gainNode = null; + let audioScheduler = null; + let playRequestId = 0; + let resumeInFlight = false; + let currentVolume = 1; + let ttsRetryDelayMs = 1000; + let segmentStore = Object.create(null); + let expectedSeq = null; + let isSegmentPlaying = false; + let seqWaitTimer = null; + let fallbackQueueTimer = null; + const delayTimers = new Set(); + + function ensureAudioGraph() { + if (!audioCtx) { + const ctx = new AudioContextCtor(); + const gain = ctx.createGain(); + gain.gain.value = currentVolume; + gain.connect(ctx.destination); + const sched = audioSchedulerFactory.create(ctx, { + jitterBufferSec: 0.25, + comfortNoiseEnabled: false, + destination: gain, + }); + audioCtx = ctx; + gainNode = gain; + audioScheduler = sched; } - }); + return audioCtx; + } + + function clearPendingPlayback() { + delayTimers.forEach((t) => cancel(t)); + delayTimers.clear(); + if (seqWaitTimer) { cancel(seqWaitTimer); seqWaitTimer = null; } + if (fallbackQueueTimer) { cancel(fallbackQueueTimer); fallbackQueueTimer = null; } + segmentStore = Object.create(null); + expectedSeq = null; + isSegmentPlaying = false; + if (audioScheduler) { + audioScheduler.reset(); + } + } - if (CAPTIONS_ON && captionsEl) { - var wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - var urlPath = new URL(CAPTION_URL).pathname; - var wsUrl = wsProto + '//' + window.location.host + urlPath + '?token=' + encodeURIComponent(EMBED_TOKEN); - var captionWs = null; - var captionRetryDelayMs = 1000; - - var historyEl = document.getElementById('embed-caption-history'); - var currentEl = document.getElementById('embed-caption-current'); - var maxHistoryDOM = 50; - // How close to the bottom (in px) still counts as "following" the captions. - var FOLLOW_THRESHOLD_PX = 40; - - var captionHistoryHeadless = []; - var maxHistoryHeadless = 2; - - function handleCaptionMessage(ev) { + function advanceSeq(seqId) { + isSegmentPlaying = false; + delete segmentStore[seqId]; + expectedSeq++; + fallbackQueueTimer = schedule(pumpSegmentQueue, 30); + } + + function pumpSegmentQueue() { + if (!playing || isSegmentPlaying) return; + const nextSeg = segmentStore[expectedSeq]; + if (!nextSeg) { + if (!seqWaitTimer) { + seqWaitTimer = schedule(() => { + seqWaitTimer = null; + const storedSeqs = Object.keys(segmentStore).map(Number).filter((n) => !isNaN(n)).sort((a, b) => a - b); + const nextAvailable = storedSeqs.find((s) => s > expectedSeq); + if (nextAvailable !== undefined) { + expectedSeq = nextAvailable; + pumpSegmentQueue(); + } + }, 1500); + } + return; + } + + if (seqWaitTimer) { cancel(seqWaitTimer); seqWaitTimer = null; } + isSegmentPlaying = true; + + if (nextSeg.error || nextSeg.empty) { + advanceSeq(expectedSeq); + return; + } + + if (nextSeg.audioBuffer && audioScheduler) { + const finishedSeq = expectedSeq; + audioScheduler.scheduleBuffer(nextSeg.audioBuffer); + advanceSeq(finishedSeq); + } else { + // Waiting for Stage 2 audio: arm seqWaitTimer so a dropped Stage-2 frame cannot stall forever. + isSegmentPlaying = false; + if (!seqWaitTimer) { + const elapsed = Date.now() - (nextSeg.receivedAt || Date.now()); + seqWaitTimer = schedule(() => { + seqWaitTimer = null; + if (segmentStore[expectedSeq]) { + segmentStore[expectedSeq].error = 'tts_timeout'; + } + pumpSegmentQueue(); + }, Math.max(0, 65000 - elapsed)); + } + } + } + + function processFrame(frame) { + if (!playing) return; + const seq = frame.header && frame.header.seq; + if (!seq) return; + if (expectedSeq === null || expectedSeq === undefined) expectedSeq = seq; + if (seq < expectedSeq) return; + + const hasAudio = Boolean(!frame.header.error && frame.audioBytes && frame.audioBytes.byteLength > 0); + let audioBuffer = null; + if (hasAudio && audioCtx) { + const aligned = frame.audioBytes.buffer.slice( + frame.audioBytes.byteOffset, + frame.audioBytes.byteOffset + frame.audioBytes.byteLength, + ); + const int16 = new Int16Array(aligned); + const float32 = new Float32Array(int16.length); + for (let i = 0; i < int16.length; i++) { + float32[i] = int16[i] / 32768.0; + } + audioBuffer = audioCtx.createBuffer(1, float32.length, 24000); + audioBuffer.copyToChannel(float32, 0); + } + + segmentStore[seq] = { + seq, + error: frame.header.error || (frame.header.audio_pending === false && !hasAudio ? 'no_audio' : null), + empty: !frame.header.translation && !frame.header.error && frame.header.audio_pending === false, + audioBuffer, + receivedAt: (segmentStore[seq] && segmentStore[seq].receivedAt) || Date.now(), + }; + + const storedSeqs = Object.keys(segmentStore).map(Number).sort((a, b) => a - b); + if (storedSeqs.length > 5) { + while (storedSeqs.length > 5) { + const oldest = storedSeqs.shift(); + delete segmentStore[oldest]; + } + expectedSeq = storedSeqs[0]; + if (seqWaitTimer) { + cancel(seqWaitTimer); + seqWaitTimer = null; + } + } + pumpSegmentQueue(); + } + + function openTtsWs() { + if (expired || !TTS_URL) return; + const ws = new WebSocketCtor(buildWsUrl(TTS_URL)); + ws.binaryType = 'arraybuffer'; + ttsWs = ws; + setStatus('connecting', 'Connecting\u2026'); + postToParent('booth_state', { state: 'connecting' }); + + ws.onopen = function () { + if (ttsWs !== ws) return; + setStatus('live', 'Live'); + playBtn.disabled = false; + playBtn.textContent = playing ? '\u23f8 Pause' : '\u25b6 Play Audio'; + postToParent('booth_state', { state: 'connected' }); + }; + + ws.onmessage = function (ev) { + if (ttsWs !== ws) return; + ttsRetryDelayMs = 1000; + if (!(ev.data instanceof ArrayBuffer) || !playing) return; try { - var msg = JSON.parse(ev.data); - var isValid = false; - if (config.headless) { - // Headless: Forward both the original captions and the requested translations - if (msg.type === 'caption') isValid = true; - if (msg.type === 'translation' && msg.language_code === TARGET_LANG) isValid = true; + const frame = ttsParser.parseFrame(ev.data); + if (AUDIO_DELAY_MS > 0) { + const timer = schedule(() => { + delayTimers.delete(timer); + processFrame(frame); + }, AUDIO_DELAY_MS); + delayTimers.add(timer); } else { - // Visible UI: Only show one language track to prevent overlapping text - const isTranslating = TARGET_LANG && TARGET_LANG !== SOURCE_LANG; - if (isTranslating) { - if (msg.type === 'translation' && msg.language_code === TARGET_LANG) isValid = true; - } else { - if (msg.type === 'caption') isValid = true; - } + processFrame(frame); } - - if (isValid) { - var status = msg.type === 'translation' ? 'final' : (msg.status || 'final'); - var text = (msg.text || '').trim(); - - if (config.headless) { - // Headless: maintain a short array buffer and send concatenated string - if (status === 'clear') { - captionHistoryHeadless = []; - text = ''; - } else if (status === 'final') { - if (text) { - captionHistoryHeadless.push(text); - if (captionHistoryHeadless.length > maxHistoryHeadless) { - captionHistoryHeadless.shift(); - } - } - text = ''; - } - var displayText = captionHistoryHeadless.concat(text ? [text] : []).join(' '); - - window.parent.postMessage({ - source: 'voxbento-embed', - v: 1, - type: 'subtitle', - payload: { - text: displayText, - language: msg.language_code || SOURCE_LANG, - msg_type: msg.type, - raw_status: status, - raw_text: msg.text - } - }, config.target_origin); - } else { - // Visible UI: build a DOM history like Voxbento's main listener UI. - // Follow new captions only while the viewer is already at the bottom, - // so scrolling up to re-read a line is not undone by the next partial. - var followLatest = - captionsEl.scrollHeight - captionsEl.scrollTop - captionsEl.clientHeight <= FOLLOW_THRESHOLD_PX; - if (status === 'clear') { - currentEl.textContent = ''; - } else if (status === 'final') { - if (text) { - var p = document.createElement('div'); - p.textContent = text; - historyEl.appendChild(p); - while (historyEl.children.length > maxHistoryDOM) { - historyEl.removeChild(historyEl.firstChild); - } - } - currentEl.textContent = ''; - } else if (status === 'partial') { - currentEl.textContent = text; - } - - if (historyEl.children.length === 0 && !currentEl.textContent) { - captionsEl.classList.add('empty'); - } else { - captionsEl.classList.remove('empty'); - } - if (followLatest) { - captionsEl.scrollTop = captionsEl.scrollHeight; - } + } catch (err) { + console.error('TTS frame parse error:', err); + } + }; + ws.onclose = function (ev) { + if (ttsWs !== ws) return; + ttsWs = null; + clearPendingPlayback(); + if (ev.code === 4001 || ev.code === 4003 || (ev.code === 1006 && isJwtExpired(EMBED_TOKEN))) { + setExpired(); + return; + } + setStatus('connecting', 'Reconnecting\u2026'); + postToParent('booth_state', { state: 'connecting' }); + ttsRetryTimer = schedule(openTtsWs, ttsRetryDelayMs * (0.5 + Math.random() / 2)); + ttsRetryDelayMs = Math.min(ttsRetryDelayMs * 2, 15000); + }; + } + + openTtsWs(); + + return { + play() { + if (expired) return Promise.reject(new Error('Session expired')); + const reqId = ++playRequestId; + return Promise.resolve() + .then(() => { + if (reqId !== playRequestId || expired) return null; + return ensureAudioGraph(); + }) + .then((ctx) => { + if (!ctx || reqId !== playRequestId || expired) return null; + resumeInFlight = true; + return ctx.resume().then( + () => { + resumeInFlight = false; + return ctx; + }, + (err) => { + resumeInFlight = false; + throw err; + }, + ); + }) + .then((ctx) => { + if (!ctx || reqId !== playRequestId || expired) return; + if (ctx.state !== 'running') { + throw new Error('AudioContext resume blocked'); } + playing = true; + playBtn.textContent = '\u23f8 Pause'; + }); + }, + pause() { + const reqId = ++playRequestId; + playing = false; + clearPendingPlayback(); + if (audioCtx && (audioCtx.state === 'running' || resumeInFlight)) { + Promise.resolve(audioCtx.suspend()).catch((err) => { + if (reqId === playRequestId) console.error('AudioContext suspend failed:', err); + }); + } + playBtn.textContent = '\u25b6 Play Audio'; + }, + stop() { + const reqId = ++playRequestId; + playing = false; + clearPendingPlayback(); + if (audioCtx) { + const ctx = audioCtx; + audioCtx = null; + gainNode = null; + audioScheduler = null; + if (typeof ctx.close === 'function' && ctx.state !== 'closed') { + Promise.resolve(ctx.close()).catch((err) => { + if (reqId === playRequestId) console.error('AudioContext close failed:', err); + }); + } else if (ctx.state === 'running' || resumeInFlight) { + Promise.resolve(ctx.suspend()).catch((err) => { + if (reqId === playRequestId) console.error('AudioContext suspend failed:', err); + }); } - } catch (_) {} - } - - function openCaptionWs() { - var ws = new WebSocket(wsUrl); - captionWs = ws; - ws.onopen = function() { - captionRetryDelayMs = 1000; - }; - ws.onmessage = handleCaptionMessage; - ws.onclose = function(ev) { - if (ev.code === 4001) { setExpired(); return; } - // 4003: the token is for another event, so reconnecting cannot help. - if (ev.code === 4003 || captionWs !== ws) return; - // Any other close (network drop, server restart, proxy timeout) would - // otherwise stop captions until the host page is reloaded. - captionWs = null; - // Wait between half and all of the current delay, so embeds dropped by the same - // restart do not all reconnect at the same moment. - setTimeout(openCaptionWs, captionRetryDelayMs * (0.5 + Math.random() / 2)); - captionRetryDelayMs = Math.min(captionRetryDelayMs * 2, 15000); - }; + } + }, + setVolume(v) { + currentVolume = v; + if (gainNode) gainNode.gain.value = v; + }, + }; + } + + function createNoneController() { + if (playBtn) playBtn.hidden = true; + if (CAPTIONS_ON && (captionsEl || config.headless) && CAPTION_URL) { + setStatus('connecting', 'Connecting captions\u2026'); + } else { + setStatus('error', 'Captions unavailable'); + } + return { + play() { return Promise.resolve(); }, + pause() {}, + setVolume() {}, + }; + } + + const audioController = + AUDIO_MODE === 'tts' + ? createTtsController() + : AUDIO_MODE === 'none' + ? createNoneController() + : createWhepController(); + + if (playBtn && AUDIO_MODE !== 'none') { + playBtn.addEventListener('click', function () { + if (!playing) { + audioController.play().catch((err) => { + console.error('Playback blocked:', err); + setStatus('error', 'Playback blocked \u2014 check browser permissions'); + }); + } else { + audioController.pause(); } + }); + } + + // ── Captions WebSocket ───────────────────────────────────────────────── + + if (CAPTIONS_ON && (captionsEl || config.headless) && CAPTION_URL) { + const wsUrl = buildWsUrl(CAPTION_URL); + let captionRetryDelayMs = 1000; + const historyEl = doc.getElementById('embed-caption-history'); + const currentEl = doc.getElementById('embed-caption-current'); + const maxHistoryDOM = 50; + const FOLLOW_THRESHOLD_PX = 40; + let captionHistoryHeadless = []; + const maxHistoryHeadless = 2; - openCaptionWs(); + function isCaptionRelevant(msg) { + if (config.headless) { + if (msg.type === 'caption') return true; + if (msg.type === 'translated_caption' && (!msg.language_code || msg.language_code === TARGET_LANG)) return true; + if (msg.type === 'translation' && msg.language_code === TARGET_LANG) return true; + return false; + } + const isTranslating = Boolean(TARGET_LANG && TARGET_LANG !== SOURCE_LANG) || AUDIO_MODE !== 'whep'; + if (isTranslating) { + if (msg.type === 'translated_caption' && (!msg.language_code || msg.language_code === TARGET_LANG)) return true; + if (msg.type === 'translation' && msg.language_code === TARGET_LANG) return true; + return false; + } + return msg.type === 'caption'; } - if (config.headless) { - window.addEventListener('message', function(event) { - if (config.allowed_origins.length > 0 && !config.allowed_origins.includes(event.origin)) return; - if (!event.data || event.data.source !== 'voxbento-parent') return; + function handleCaptionMessage(ev) { + let msg; + try { + msg = JSON.parse(ev.data); + } catch (err) { + console.error('Invalid caption JSON:', err); + return; + } + if (!isCaptionRelevant(msg)) return; + + const status = (msg.type === 'translation' || msg.type === 'translated_caption') + ? 'final' + : (msg.status || 'final'); + let text = (msg.text || '').trim(); - if (event.data.type === 'play') { - audioEl.play().then(function() { - playing = true; - }).catch(function(err) { - window.parent.postMessage({ - source: 'voxbento-embed', - v: 1, - type: 'error', - payload: { code: 'autoplay_blocked', message: err.message } - }, config.target_origin); - }); + if (config.headless) { + if (status === 'clear') { + captionHistoryHeadless = []; + text = ''; + } else if (status === 'final') { + if (text) { + captionHistoryHeadless.push(text); + if (captionHistoryHeadless.length > maxHistoryHeadless) { + captionHistoryHeadless.shift(); + } + } + text = ''; + } + const displayText = captionHistoryHeadless.concat(text ? [text] : []).join(' '); + postToParent('subtitle', { + text: displayText, + language: msg.language_code || TARGET_LANG || SOURCE_LANG, + msg_type: msg.type, + raw_status: status, + raw_text: msg.text, + }); + return; + } + + const followLatest = + captionsEl.scrollHeight - captionsEl.scrollTop - captionsEl.clientHeight <= FOLLOW_THRESHOLD_PX; + if (status === 'clear') { + currentEl.textContent = ''; + } else if (status === 'final') { + if (text) { + const p = doc.createElement('div'); + p.textContent = text; + historyEl.appendChild(p); + while (historyEl.children.length > maxHistoryDOM) { + historyEl.removeChild(historyEl.firstChild); + } + } + currentEl.textContent = ''; + } else if (status === 'partial') { + currentEl.textContent = text; + } + + if (historyEl.children.length === 0 && !currentEl.textContent) { + captionsEl.classList.add('empty'); + } else { + captionsEl.classList.remove('empty'); + } + if (followLatest) { + captionsEl.scrollTop = captionsEl.scrollHeight; + } + } + + function openCaptionWs() { + if (expired) return; + const ws = new WebSocketCtor(wsUrl); + captionWs = ws; + ws.onopen = function () { + if (captionWs !== ws) return; + if (AUDIO_MODE === 'none') { + setStatus('captions', 'Captions only'); + postToParent('booth_state', { state: 'connected' }); } - if (event.data.type === 'pause') { - audioEl.pause(); - playing = false; + }; + ws.onmessage = function (ev) { + if (captionWs !== ws) return; + captionRetryDelayMs = 1000; + handleCaptionMessage(ev); + }; + ws.onclose = function (ev) { + if (captionWs !== ws) return; + if (ev.code === 4001) { setExpired(); return; } + if (ev.code === 4003) { + captionWs = null; + if (AUDIO_MODE === 'none') setStatus('error', 'Access denied'); + postToParent('error', { code: 'access_denied', message: 'Captions access denied' }); + return; } - if (event.data.type === 'set_volume') { - const v = Number(event.data.volume); - if (v >= 0 && v <= 1) audioEl.volume = v; + captionWs = null; + if (AUDIO_MODE === 'none') { + setStatus('connecting', 'Reconnecting\u2026'); + postToParent('booth_state', { state: 'connecting' }); } - }); + captionRetryTimer = schedule(openCaptionWs, captionRetryDelayMs * (0.5 + Math.random() / 2)); + captionRetryDelayMs = Math.min(captionRetryDelayMs * 2, 15000); + }; } + + openCaptionWs(); + } + + // ── Headless Parent Commands ─────────────────────────────────────────── + + if (config.headless) { + win.addEventListener('message', function (event) { + if (event.source !== win.parent) return; + if (config.allowed_origins.length > 0 && !config.allowed_origins.includes(event.origin)) return; + if (!event.data || event.data.source !== 'voxbento-parent') return; + + if (event.data.type === 'play') { + audioController.play().catch((err) => { + postToParent('error', { code: 'autoplay_blocked', message: err.message }); + }); + } + if (event.data.type === 'pause') { + audioController.pause(); + } + if (event.data.type === 'set_volume') { + const v = Number(event.data.volume); + if (v >= 0 && v <= 1) audioController.setVolume(v); + } + }); + } + + return { audioController }; +} + +if (typeof document !== 'undefined') { + document.addEventListener('DOMContentLoaded', function () { + initEmbedPlayer(); }); -})(); +} diff --git a/portal/templates/embed.html b/portal/templates/embed.html index e3d3e54ee..ef4c012c6 100644 --- a/portal/templates/embed.html +++ b/portal/templates/embed.html @@ -22,6 +22,7 @@ > + {% if custom_css_url %} @@ -33,19 +34,21 @@ /* ── CSS variables — all values are server-sanitised ─────────────────── */ :root { --primary: #{{ primary_color }}; - --font: '{{ font_family }}', Inter, system-ui, sans-serif; + --font: '{{ font_family }}', var(--vb-font); {% if theme == "dark" %} - --bg: #0d0f10; - --surface: #1a1d21; - --border: #2a2d32; - --text: #f1f5f9; - --muted: #94a3b8; + --bg: #0d0f10; + --surface: #1a1d21; + --surface-2: #14171a; + --border: #2a2d32; + --text: #f1f5f9; + --muted: #94a3b8; {% else %} - --bg: #f8f9fa; - --surface: #ffffff; - --border: #e2e8f0; - --text: #0d0f10; - --muted: #64748b; + --bg: var(--vb-color-bg); + --surface: var(--vb-color-surface); + --surface-2: var(--vb-color-surface-2); + --border: var(--vb-color-border); + --text: var(--vb-color-text); + --muted: var(--vb-color-muted); {% endif %} } @@ -61,7 +64,7 @@ Connecting… - @@ -80,22 +83,26 @@ + + - + {% include "_auth_sync.html" %} diff --git a/portal/websockets/handlers.py b/portal/websockets/handlers.py index 16c41f90e..30b9effe5 100644 --- a/portal/websockets/handlers.py +++ b/portal/websockets/handlers.py @@ -227,10 +227,11 @@ async def ws_captions(websocket: WebSocket, booth_id: str) -> None: is_anonymous = not bool(token) booth_event: str | None = None + booth_room: int | None = None try: from portal.booth_identity import parse_booth_id - booth_event, _, _ = parse_booth_id(booth_id) + booth_event, booth_room, _ = parse_booth_id(booth_id) except ValueError: if "/" in booth_id: booth_event = booth_id.split("/")[0] @@ -245,8 +246,11 @@ async def ws_captions(websocket: WebSocket, booth_id: str) -> None: if await resolve_session_user(payload) is None: reject_code = 4001 elif is_listener_token(payload): + token_room = payload.get("room_id") if not payload.get("event_slug") or booth_event != payload["event_slug"]: reject_code = 4003 + elif token_room is not None and (booth_room is None or str(token_room) != str(booth_room)): + reject_code = 4003 elif not payload.get("event_slug") or not await resolve_booth_role(payload, booth_id): reject_code = 4003 except SQLAlchemyError: @@ -342,7 +346,7 @@ async def _authorize_tts( import jwt - from portal.auth import WSAuthError, decode_token, get_booth_sessions, resolve_booth_role + from portal.auth import EmbedTokenExpiredError, WSAuthError, decode_token, get_booth_sessions, resolve_booth_role from portal.booth_identity import parse_booth_id, validate_language_code from portal.config import settings from portal.database import get_event_by_slug, get_session @@ -366,8 +370,21 @@ async def _authorize_tts( if token: try: payload = decode_token(token) - except jwt.InvalidTokenError: - raise WSAuthError("Invalid token.") + except jwt.ExpiredSignatureError as exc: + try: + unverified = jwt.decode( + token, + settings.effective_jwt_secret, + algorithms=["HS256"], + options={"verify_exp": False}, + ) + except jwt.InvalidTokenError: + unverified = {} + if unverified.get("purpose") == "embed": + raise EmbedTokenExpiredError("Embed token has expired.") from exc + raise WSAuthError("Token has expired.") from exc + except jwt.InvalidTokenError as exc: + raise WSAuthError("Invalid token.") from exc if payload.get("user"): user = await resolve_session_user(payload) @@ -380,6 +397,9 @@ async def _authorize_tts( if is_listener_token(payload): if not token_event or token_event != event_slug: raise WSAuthError("Listener token event_slug does not match.") + token_room = payload.get("room_id") + if token_room is not None and str(token_room) != str(actual_room): + raise WSAuthError("Listener token room_id does not match.") return token_lang = payload.get("language_code", "") @@ -433,6 +453,9 @@ async def _authorize_tts( if is_listener_token(payload): if not token_event or token_event != event_slug: raise WSAuthError("Listener token event_slug does not match.") + token_room = payload.get("room_id") + if token_room is not None and str(token_room) != str(actual_room): + raise WSAuthError("Listener token room_id does not match.") return token_lang = payload.get("language_code", "") @@ -485,9 +508,18 @@ async def ws_tts(websocket: WebSocket, room_id: int, language_code: str, booth_i # Accept before closing: a close before accept() becomes an HTTP 403 and # browsers only report 1006, so the listener could not tell a refusal # (stop) from a dropped connection (reconnect). Nothing is registered or sent. - # A throttled join code clears on its own, so it gets 1008 (retry) as on /ws/captions. + # Throttled join codes get 1008 (retry), expired embed tokens get 4001, and + # other refusals get 4003. + from portal.auth import EmbedTokenExpiredError + await websocket.accept() - await websocket.close(code=1008 if isinstance(exc.__cause__, JoinCodeThrottled) else 4003) + if isinstance(exc.__cause__, JoinCodeThrottled): + close_code = 1008 + elif isinstance(exc, EmbedTokenExpiredError): + close_code = 4001 + else: + close_code = 4003 + await websocket.close(code=close_code) return except SQLAlchemyError: _log.exception("TTS authorization database lookup failed") diff --git a/portal/websockets/manager.py b/portal/websockets/manager.py index 0741b7b48..f92e6b697 100644 --- a/portal/websockets/manager.py +++ b/portal/websockets/manager.py @@ -16,7 +16,7 @@ from sqlalchemy.exc import SQLAlchemyError import portal.webhooks.worker as _wh_worker -from portal.auth import WSAuthError, can_perform_role +from portal.auth import EmbedTokenExpiredError, WSAuthError, can_perform_role from portal.booth_identity import booth_id_to_mediamtx_path, parse_booth_id from portal.booth_publish import ( TICKET_TTL_SECS, @@ -691,10 +691,11 @@ async def deliver(ws: WebSocket, authorize: Callable[[], Awaitable[None]] | None if ws not in self._rooms.get(key, set()): return await ws.send_bytes(frame) - except WSAuthError: + except WSAuthError as exc: self.remove(ws, room_id, language_code, booth_id) + close_code = 4001 if isinstance(exc, EmbedTokenExpiredError) else WS_CLOSE_REVOKED try: - await asyncio.wait_for(ws.close(code=WS_CLOSE_REVOKED), timeout=2.0) + await asyncio.wait_for(ws.close(code=close_code), timeout=2.0) except (WebSocketDisconnect, RuntimeError, OSError, TimeoutError): pass except SQLAlchemyError: diff --git a/tests/test_audio_scheduler.js b/tests/test_audio_scheduler.js index 7d4c5d1cb..582f7f8ed 100644 --- a/tests/test_audio_scheduler.js +++ b/tests/test_audio_scheduler.js @@ -333,6 +333,98 @@ console.log('\n=== AudioScheduler Tests ===\n'); assertApprox(timings[4].endTime, 2.6, 0.01, 'Total scheduled end time is correct'); })(); +// Test 8: Custom destination node receives scheduled sources +(function () { + console.log('\nTest 8: Custom destination node receives scheduled sources'); + const ctx = new MockAudioContext(); + ctx._currentTime = 0.0; + const customDest = { label: 'masterGain' }; + const connectedTo = []; + ctx.createBufferSource = function () { + return { + buffer: null, + loop: false, + connect: function (dest) { connectedTo.push(dest); }, + start: function () {}, + stop: function () {}, + onended: null, + }; + }; + + const scheduler = createAudioScheduler(ctx, { + jitterBufferSec: 0.1, + comfortNoiseEnabled: false, + destination: customDest, + }); + + const buf = ctx.createBuffer(1, 12000, 24000); + buf.duration = 0.5; + scheduler.scheduleBuffer(buf); + + assert(connectedTo.length === 1 && connectedTo[0] === customDest, 'BufferSource connects to custom destination'); +})(); + +// Test 9: Comfort noise connects to custom destination and reset() stops active sources +(function () { + console.log('\nTest 9: Comfort noise routing to custom destination and reset()'); + const ctx = new MockAudioContext(); + ctx._currentTime = 0.0; + const customDest = { label: 'masterGain' }; + const gainConnections = []; + const origCreateGain = ctx.createGain.bind(ctx); + ctx.createGain = function () { + const g = origCreateGain(); + g.connect = function (dest) { gainConnections.push(dest); }; + return g; + }; + let stoppedCount = 0; + const scheduledSources = []; + ctx.createBufferSource = function () { + const src = { + buffer: null, + loop: false, + connect: function () {}, + start: function () {}, + stop: function () { stoppedCount++; }, + onended: null, + }; + scheduledSources.push(src); + return src; + }; + + const origSetTimeout = global.setTimeout; + const origClearTimeout = global.clearTimeout; + let idleCb = null; + global.setTimeout = function (fn) { idleCb = fn; return 1; }; + global.clearTimeout = function () {}; + + try { + const scheduler = createAudioScheduler(ctx, { + jitterBufferSec: 0.1, + comfortNoiseEnabled: true, + destination: customDest, + }); + + const buf = ctx.createBuffer(1, 12000, 24000); + buf.duration = 0.5; + scheduler.scheduleBuffer(buf); + + assert(typeof idleCb === 'function', 'Schedules idle check timer for comfort noise'); + ctx._currentTime = 1.0; + idleCb(); + assert(gainConnections.includes(customDest), 'Comfort noise GainNode connects to custom destination'); + + // Schedule another buffer and verify reset() stops it + scheduler.scheduleBuffer(buf); + const beforeStop = stoppedCount; + scheduler.reset(); + assert(stoppedCount > beforeStop, 'reset() stops active scheduled sources'); + } finally { + global.setTimeout = origSetTimeout; + global.clearTimeout = origClearTimeout; + } +})(); + // ── Summary ────────────────────────────────────────────────────────────── console.log('\n=== Results: ' + passed + ' passed, ' + failed + ' failed ===\n'); diff --git a/tests/test_embed_player.js b/tests/test_embed_player.js new file mode 100644 index 000000000..19a309aab --- /dev/null +++ b/tests/test_embed_player.js @@ -0,0 +1,584 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); + +let passed = 0; +let failed = 0; + +function assert(condition, message) { + if (!condition) { + console.error(' FAIL: ' + message); + failed++; + } else { + console.log(' PASS: ' + message); + passed++; + } +} + +function makeFakeDoc(configObj) { + const elements = new Map(); + function makeEl(id, extra = {}) { + const el = { + id, + textContent: '', + className: '', + classList: { + add() {}, + remove() {}, + }, + children: [], + listeners: {}, + disabled: false, + hidden: false, + volume: 1, + scrollHeight: 0, + scrollTop: 0, + clientHeight: 0, + addEventListener(ev, fn) { this.listeners[ev] = fn; }, + appendChild(c) { this.children.push(c); }, + removeChild(c) { + const idx = this.children.indexOf(c); + if (idx >= 0) this.children.splice(idx, 1); + }, + play() { return Promise.resolve(); }, + pause() {}, + ...extra, + }; + elements.set(id, el); + return el; + } + + makeEl('embed-config', { textContent: JSON.stringify(configObj) }); + makeEl('embed-audio'); + makeEl('play-btn'); + makeEl('status-dot'); + makeEl('status-text'); + if (configObj.captions_enabled) { + makeEl('captions-box'); + makeEl('embed-caption-history'); + makeEl('embed-caption-current'); + } + + return { + elements, + getElementById(id) { return elements.get(id) || null; }, + createElement() { return { textContent: '' }; }, + }; +} + +function makeFakeJwt(expSeconds) { + const header = Buffer.from(JSON.stringify({ alg: 'HS256' })).toString('base64url'); + const payload = Buffer.from(JSON.stringify({ kind: 'listener', exp: expSeconds })).toString('base64url'); + return `${header}.${payload}.sig`; +} + +async function runTests() { + const mod = await import( + pathToFileURL(path.join(__dirname, '..', 'portal', 'static', 'js', 'embed-player.js')).href + ); + + // Test 1: isJwtExpired helper + console.log('\nTest 1: isJwtExpired'); + assert(mod.isJwtExpired(makeFakeJwt(1000), 2000) === true, 'Expired JWT returns true'); + assert(mod.isJwtExpired(makeFakeJwt(3000), 2000) === false, 'Valid JWT returns false'); + + // Test 2: TTS mode connects /ws/tts, decodes PCM, supports play/pause/set_volume/delay/expiry + console.log('\nTest 2: TTS mode playback, volume, pause, delay, and auth expiry'); + { + const sockets = []; + const posted = []; + const scheduledBuffers = []; + const timers = []; + let schedulerStopAllCount = 0; + let resumeCalls = 0; + let suspendCalls = 0; + let masterGain = null; + const messageListeners = []; + const embedToken = makeFakeJwt(Math.floor(Date.now() / 1000) + 600); + + class FakeWS { + constructor(url) { + this.url = url; + this.binaryType = ''; + sockets.push(this); + } + close() {} + } + + class FakeAudioContext { + constructor() { + this.state = 'suspended'; + this.destination = { label: 'dest' }; + } + createGain() { + masterGain = { gain: { value: 1 }, connect() {} }; + return masterGain; + } + createBuffer(ch, len, rate) { + return { ch, len, rate, copyToChannel() {} }; + } + resume() { + resumeCalls++; + this.state = 'running'; + return Promise.resolve(); + } + suspend() { + suspendCalls++; + this.state = 'suspended'; + return Promise.resolve(); + } + } + + const doc = makeFakeDoc({ + audio_mode: 'tts', + whep_url: '', + tts_url: 'wss://example.com/ws/tts/5/es/ev-5-floor', + caption_url: 'wss://example.com/ws/captions/ev-5-es', + captions_enabled: false, + token: embedToken, + audio_delay_ms: 150, + source_lang_code: 'es', + target_lang_code: 'es', + headless: true, + target_origin: '*', + allowed_origins: [], + }); + + const fakeWin = { + location: { protocol: 'https:', host: 'example.com' }, + parent: { postMessage(msg) { posted.push(msg); } }, + addEventListener(ev, fn) { if (ev === 'message') messageListeners.push(fn); }, + setTimeout, + clearTimeout, + }; + + mod.initEmbedPlayer({ + document: doc, + window: fakeWin, + WebSocket: FakeWS, + AudioContext: FakeAudioContext, + TTSParser: { + parseFrame() { + return { + header: { seq: 1, translation: 'Hola', error: null, audio_pending: false }, + audioBytes: new Uint8Array([0, 0, 100, 0]), + }; + }, + }, + AudioScheduler: { + create(_ctx, opts) { + assert(opts.destination === masterGain, 'AudioScheduler receives master GainNode'); + return { + scheduleBuffer(buf) { scheduledBuffers.push(buf); }, + reset() { schedulerStopAllCount++; }, + }; + }, + }, + setTimeout(fn, delay) { + const entry = { fn, delay, cancelled: false }; + timers.push(entry); + return entry; + }, + clearTimeout(entry) { + if (entry) entry.cancelled = true; + }, + }); + + assert( + sockets.length === 1 && new URL(sockets[0].url).searchParams.get('token') === embedToken, + 'Opens /ws/tts with exact token query param' + ); + sockets[0].onopen(); + assert(posted.some((m) => m.type === 'booth_state' && m.payload.state === 'connected'), 'Emits connected booth_state'); + + // Frame arriving before play is ignored + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + assert(scheduledBuffers.length === 0, 'Does not schedule audio before play'); + + // Start playback so masterGain is initialized (gain === 1) + messageListeners[0]({ source: fakeWin.parent, origin: 'https://parent', data: { source: 'voxbento-parent', type: 'play' } }); + for (let i = 0; i < 5; i++) await Promise.resolve(); + assert(resumeCalls === 1, 'Resumes AudioContext on play'); + assert(masterGain && masterGain.gain.value === 1, 'Initializes masterGain to 1'); + + // Message from non-parent source is ignored + messageListeners[0]({ source: {}, origin: 'https://parent', data: { source: 'voxbento-parent', type: 'set_volume', volume: 0.1 } }); + assert(masterGain.gain.value === 1, 'Ignores postMessage when event.source !== window.parent'); + + // Parent set_volume + delayed frame + messageListeners[0]({ source: fakeWin.parent, origin: 'https://parent', data: { source: 'voxbento-parent', type: 'set_volume', volume: 0.4 } }); + assert(masterGain.gain.value === 0.4, 'Applies set_volume to master GainNode'); + + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + assert(scheduledBuffers.length === 0, 'Does not schedule buffer before nonzero audio_delay_ms expires'); + const delayTimer = timers.find((t) => !t.cancelled && t.delay === 150); + assert(Boolean(delayTimer), 'Schedules 150ms delay timer for audio_delay_ms'); + delayTimer.fn(); + assert(scheduledBuffers.length === 1, 'Schedules decoded PCM buffer after audio_delay_ms timer fires'); + + // Pause suspends AudioContext and resets scheduler + messageListeners[0]({ source: fakeWin.parent, origin: 'https://parent', data: { source: 'voxbento-parent', type: 'pause' } }); + assert(suspendCalls === 1 && schedulerStopAllCount === 1, 'Pause suspends AudioContext and calls scheduler.reset()'); + + // 4003 close stops reconnects and marks expired; subsequent play is rejected + sockets[0].onclose({ code: 4003 }); + assert(doc.getElementById('status-text').textContent === 'Session expired', 'Marks expired on 4003'); + assert(posted.some((m) => m.type === 'error' && m.payload.code === 'session_expired'), 'Emits session_expired error'); + messageListeners[0]({ source: fakeWin.parent, origin: 'https://parent', data: { source: 'voxbento-parent', type: 'play' } }); + for (let i = 0; i < 5; i++) await Promise.resolve(); + assert(resumeCalls === 1, 'Does not resume AudioContext on play after session expiry'); + } + + // Test 3: Captions-only ("none") mode + translated_caption without language_code + console.log('\nTest 3: Captions-only mode and translated_caption handling'); + { + const sockets = []; + class FakeWS { + constructor(url) { this.url = url; sockets.push(this); } + close() {} + } + const doc = makeFakeDoc({ + audio_mode: 'none', + whep_url: '', + tts_url: '', + caption_url: 'wss://example.com/ws/captions/ev-5-de', + captions_enabled: true, + token: makeFakeJwt(Math.floor(Date.now() / 1000) + 600), + audio_delay_ms: 0, + source_lang_code: 'de', + target_lang_code: 'de', + headless: false, + target_origin: '*', + allowed_origins: [], + }); + + mod.initEmbedPlayer({ + document: doc, + window: { + location: { protocol: 'https:', host: 'example.com' }, + setTimeout, + clearTimeout, + }, + WebSocket: FakeWS, + }); + + assert(doc.getElementById('play-btn').hidden === true, 'Hides play button in captions-only mode'); + assert(sockets.length === 1 && sockets[0].url.includes('/ws/captions/ev-5-de?token='), 'Connects only captionWs'); + sockets[0].onopen(); + assert(doc.getElementById('status-text').textContent === 'Captions only', 'Shows Captions only status'); + sockets[0].onmessage({ data: JSON.stringify({ type: 'translated_caption', status: 'final', text: 'Hallo Welt' }) }); + assert(doc.getElementById('embed-caption-history').children.length === 1, 'Renders translated_caption without language_code'); + assert(doc.getElementById('embed-caption-history').children[0].textContent === 'Hallo Welt', 'Rendered text matches'); + + sockets[0].onclose({ code: 4003 }); + assert(doc.getElementById('status-text').textContent === 'Access denied', 'Shows Access denied on caption 4003 close'); + } + + // Test 4: Reconnect clears pending Stage-1 segmentStore so playback does not stall + console.log('\nTest 4: TTS reconnect clears pending Stage-1 segment and resumes playback'); + { + const sockets = []; + const scheduledSeqs = []; + const timers = []; + let currentFrame = null; + + class FakeWS { + constructor(url) { this.url = url; this.binaryType = ''; sockets.push(this); } + close() {} + } + class FakeAudioContext { + constructor() { this.state = 'suspended'; this.destination = {}; } + createGain() { return { gain: { value: 1 }, connect() {} }; } + createBuffer(_ch, len) { return { len, copyToChannel() {} }; } + resume() { this.state = 'running'; return Promise.resolve(); } + suspend() { this.state = 'suspended'; return Promise.resolve(); } + } + + const doc = makeFakeDoc({ + audio_mode: 'tts', + whep_url: '', + tts_url: 'wss://example.com/ws/tts/5/es/ev-5-floor', + caption_url: '', + captions_enabled: false, + token: makeFakeJwt(Math.floor(Date.now() / 1000) + 600), + audio_delay_ms: 0, + source_lang_code: 'es', + target_lang_code: 'es', + headless: false, + target_origin: '*', + allowed_origins: [], + }); + + mod.initEmbedPlayer({ + document: doc, + window: { location: { protocol: 'https:', host: 'example.com' }, setTimeout, clearTimeout }, + WebSocket: FakeWS, + AudioContext: FakeAudioContext, + TTSParser: { parseFrame: () => currentFrame }, + AudioScheduler: { + create() { + return { + scheduleBuffer(buf) { scheduledSeqs.push(buf.len); }, + reset() {}, + }; + }, + }, + setTimeout(fn, delay) { + const entry = { fn, delay, cancelled: false }; + timers.push(entry); + return entry; + }, + clearTimeout(entry) { + if (entry) entry.cancelled = true; + }, + }); + + sockets[0].onopen(); + doc.getElementById('play-btn').listeners.click(); + for (let i = 0; i < 5; i++) await Promise.resolve(); + + // Stage 1 (audio_pending: true, no audioBytes) arrives for seq 1 right before disconnect + currentFrame = { + header: { seq: 1, translation: 'Hola', error: null, audio_pending: true }, + audioBytes: new Uint8Array(0), + }; + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + assert(scheduledSeqs.length === 0, 'Stage 1 without audio does not schedule playback'); + + // Socket drops unexpectedly and reconnects + sockets[0].onclose({ code: 1006 }); + const reconnectTimer = timers.find((t) => !t.cancelled && t.delay >= 500 && t.delay <= 1000); + assert(Boolean(reconnectTimer), 'Schedules reconnect timer after 1006'); + reconnectTimer.fn(); + assert(sockets.length === 2, 'Opens replacement TTS WebSocket'); + sockets[1].onopen(); + + // New seq 2 with audio arrives after reconnect: must NOT be blocked by stale seq 1 + currentFrame = { + header: { seq: 2, translation: 'Mundo', error: null, audio_pending: false }, + audioBytes: new Uint8Array([0, 0, 100, 0]), + }; + sockets[1].onmessage({ data: new ArrayBuffer(8) }); + assert(scheduledSeqs.length === 1, 'Plays seq 2 after reconnect without stalling on pre-disconnect seq 1'); + } + + // Test 5: Dropped Stage-2 audio evicts oldest segment on overflow (>5) and also times out via seqWaitTimer + console.log('\nTest 5: Dropped Stage-2 audio is evicted on overflow and timed out via seqWaitTimer'); + { + const sockets = []; + const scheduled = []; + const timers = []; + let currentFrame = null; + + class FakeWS { + constructor(url) { this.url = url; this.binaryType = ''; sockets.push(this); } + close() {} + } + class FakeAudioContext { + constructor() { this.state = 'suspended'; this.destination = {}; } + createGain() { return { gain: { value: 1 }, connect() {} }; } + createBuffer(_ch, len) { return { len, copyToChannel() {} }; } + resume() { this.state = 'running'; return Promise.resolve(); } + suspend() { this.state = 'suspended'; return Promise.resolve(); } + } + + const doc = makeFakeDoc({ + audio_mode: 'tts', + whep_url: '', + tts_url: 'wss://example.com/ws/tts/5/es/ev-5-floor', + caption_url: '', + captions_enabled: false, + token: makeFakeJwt(Math.floor(Date.now() / 1000) + 600), + audio_delay_ms: 0, + source_lang_code: 'es', + target_lang_code: 'es', + headless: false, + target_origin: '*', + allowed_origins: [], + }); + + mod.initEmbedPlayer({ + document: doc, + window: { location: { protocol: 'https:', host: 'example.com' }, setTimeout, clearTimeout }, + WebSocket: FakeWS, + AudioContext: FakeAudioContext, + TTSParser: { parseFrame: () => currentFrame }, + AudioScheduler: { + create() { + return { + scheduleBuffer(buf) { scheduled.push(buf.len); }, + reset() {}, + }; + }, + }, + setTimeout(fn, delay) { + const entry = { fn, delay, cancelled: false }; + timers.push(entry); + return entry; + }, + clearTimeout(entry) { + if (entry) entry.cancelled = true; + }, + }); + + sockets[0].onopen(); + doc.getElementById('play-btn').listeners.click(); + for (let i = 0; i < 5; i++) await Promise.resolve(); + + // Stage 1 for seq 1 arrives without Stage 2; seqWaitTimer (65000ms) must be armed + currentFrame = { + header: { seq: 1, translation: 'One', error: null, audio_pending: true }, + audioBytes: new Uint8Array(0), + }; + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + const waitTimer = timers.find((t) => !t.cancelled && t.delay >= 60000); + assert(Boolean(waitTimer), 'Arms 65s wait timer when Stage-1 segment has audioBuffer === null'); + + // Send seq 2 with audio (queue < 5 items) and fire 65s wait timer -> seq 2 plays + currentFrame = { + header: { seq: 2, translation: 'Two', error: null, audio_pending: false }, + audioBytes: new Uint8Array([0, 0, 100, 0]), + }; + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + assert(scheduled.length === 0, 'Seq 2 waits while seq 1 is pending below eviction limit'); + const activeWaitTimer = timers.find((t) => !t.cancelled && t.delay >= 60000); + assert(Boolean(activeWaitTimer), 'Wait timer remains uncancelled after seq 2 arrives'); + activeWaitTimer.cancelled = true; + activeWaitTimer.fn(); + const advanceTimer = timers.find((t) => !t.cancelled && t.delay === 30); + assert(Boolean(advanceTimer), 'Schedules 30ms advance timer after 65s timeout marks seq 1 errored'); + advanceTimer.cancelled = true; + advanceTimer.fn(); + assert(scheduled.length === 1, 'Firing 65s wait timer skips stuck seq 1 and plays seq 2'); + + // Also send seq 3..8 with audio after another Stage-1 gap (seq 3 pending, 4..9 audio) to test >5 overflow eviction + currentFrame = { + header: { seq: 3, translation: 'Three', error: null, audio_pending: true }, + audioBytes: new Uint8Array(0), + }; + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + for (let s = 4; s <= 9; s++) { + currentFrame = { + header: { seq: s, translation: 'Seg ' + s, error: null, audio_pending: false }, + audioBytes: new Uint8Array([0, 0, 100, 0]), + }; + sockets[0].onmessage({ data: new ArrayBuffer(8) }); + } + assert(scheduled.length >= 2, 'Evicts stuck seq 3 on overflow (>5) and schedules seq 4'); + + // Pump remaining via fallbackQueueTimer (30ms) + let safety = 0; + while (safety++ < 10) { + const pumpTimer = timers.find((t) => !t.cancelled && t.delay === 30); + if (!pumpTimer) break; + pumpTimer.cancelled = true; + pumpTimer.fn(); + } + assert(scheduled.length === 7, 'Drains all remaining buffered segments (seq 2 + seq 4..9)'); + } + + // Test 6: WHEP mode (default when audio_mode is omitted) + console.log('\nTest 6: WHEP mode uses createWhepClient and forwards play/pause'); + { + let whepOpts = null; + let clientPlayCalls = 0; + let clientPauseCalls = 0; + + const doc = makeFakeDoc({ + whep_url: 'https://example.com/whep/ev-5/1/en', + tts_url: '', + caption_url: '', + captions_enabled: false, + token: makeFakeJwt(Math.floor(Date.now() / 1000) + 600), + audio_delay_ms: 200, + source_lang_code: 'en', + target_lang_code: 'en', + headless: false, + target_origin: '*', + allowed_origins: [], + }); + + const audioEl = doc.getElementById('embed-audio'); + audioEl.play = function () { clientPlayCalls++; return Promise.resolve(); }; + audioEl.pause = function () { clientPauseCalls++; }; + + mod.initEmbedPlayer({ + document: doc, + window: { location: { protocol: 'https:', host: 'example.com' }, setTimeout, clearTimeout }, + createWhepClient() { + return { + start(opts) { + whepOpts = opts; + opts.onState({ peerConnection: 'connected' }); + }, + }; + }, + }); + + assert( + whepOpts && whepOpts.whepUrl === 'https://example.com/whep/ev-5/1/en' && whepOpts.audioDelayMs === 200, + 'Passes whep_url and audio_delay_ms to createWhepClient().start()' + ); + await doc.getElementById('play-btn').listeners.click(); + await Promise.resolve(); + assert(clientPlayCalls === 1, 'Play button triggers WHEP audioEl.play()'); + await doc.getElementById('play-btn').listeners.click(); + assert(clientPauseCalls === 1, 'Second click pauses WHEP audioEl.pause()'); + } + + // Test 7: Headless captions-only ("none") mode connects captionWs and emits subtitle postMessage + console.log('\nTest 7: Headless captions-only mode'); + { + const sockets = []; + class FakeWS { + constructor(url) { this.url = url; sockets.push(this); } + close() {} + } + const posted = []; + const doc = makeFakeDoc({ + audio_mode: 'none', + whep_url: '', + tts_url: '', + caption_url: 'wss://example.com/ws/captions/ev-5-de', + captions_enabled: true, + token: makeFakeJwt(Math.floor(Date.now() / 1000) + 600), + audio_delay_ms: 0, + source_lang_code: 'de', + target_lang_code: 'de', + headless: true, + target_origin: '*', + allowed_origins: [], + }); + mod.initEmbedPlayer({ + document: doc, + window: { + location: { protocol: 'https:', host: 'example.com' }, + parent: { postMessage(msg) { posted.push(msg); } }, + addEventListener() {}, + setTimeout, + clearTimeout, + }, + WebSocket: FakeWS, + }); + assert(sockets.length === 1, 'Headless captions-only connects captionWs'); + sockets[0].onopen(); + assert(doc.getElementById('status-text').textContent === 'Captions only', 'Updates status from Connecting captions to Captions only'); + sockets[0].onmessage({ + data: JSON.stringify({ type: 'translated_caption', language_code: 'de', text: 'Hallo Welt' }), + }); + assert( + posted.some((m) => m.type === 'subtitle' && m.payload.text === 'Hallo Welt'), + 'Posts subtitle message to parent in headless captions-only mode' + ); + } + + console.log(`\n=== Results: ${passed} passed, ${failed} failed ===\n`); + process.exit(failed > 0 ? 1 : 0); +} + +runTests().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/tests/test_fastapi_app.py b/tests/test_fastapi_app.py index a2b777639..3f9bc5142 100644 --- a/tests/test_fastapi_app.py +++ b/tests/test_fastapi_app.py @@ -5,6 +5,7 @@ import asyncio import json import os +import re import threading from unittest.mock import AsyncMock, patch @@ -12,12 +13,16 @@ # so use an unconditional assignment to guarantee a deterministic baseline. os.environ["BOOTH_ACCESS_TOKEN"] = "" +import anyio import pytest from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect from fastapi_app import app from portal.auth import create_participant_token, create_user_token +from portal.database import create_booth, create_event, create_room, get_session +from portal.models import RoomTranslationLanguage +from portal.websockets.manager import listener_manager, tts_manager client = TestClient(app) @@ -3589,6 +3594,8 @@ def test_build_embed_context_keys_and_fallbacks(): "language_code", "whep_url", "caption_url", + "tts_url", + "audio_mode", "token", "theme", "primary_color", @@ -3602,6 +3609,8 @@ def test_build_embed_context_keys_and_fallbacks(): "allowed_origins_list", "audio_delay_ms", } + assert ctx["audio_mode"] == "whep" + assert ctx["tts_url"] == "" # font is capitalised for display assert ctx["font_family"] == "Inter" # target_lang=None must fall back to the lower-cased language code @@ -3646,7 +3655,7 @@ def test_sanitize_embed_theme_allowlist(): # Invalid theme/font/color fall back; non-https custom CSS is dropped. theme, font, primary, css = _sanitize_embed_theme("neon", "comic-sans", "not-a-color", "http://insecure/x.css") - assert theme == "dark" + assert theme == "light" assert font == "inter" assert primary == _DEFAULT_PRIMARY assert css is None @@ -3690,13 +3699,288 @@ def test_embed_rendered_html_uses_sanitized_theme_values(): assert res.status_code == 200, res.text assert "text/html" in res.headers["content-type"] # Invalid primaryColor falls back to the default VoxBento blue in the CSS variable. - assert "#3b82f6" in res.text + assert "#2563eb" in res.text # The embed-config payload still carries the delay after the refactor. assert '"audio_delay_ms"' in res.text # CSP header is still emitted with the sanitized policy. assert "frame-ancestors" in res.headers.get("content-security-policy", "") +def _seed_ai_embed_room( + event_slug: str = "ai-event", + *, + lang_code: str = "es", + lang_name: str = "Spanish", + floor_translation_enabled: bool = True, + floor_tts_enabled: bool = True, + lang_enabled: bool = True, + lang_tts_enabled: bool = True, + with_booth: bool = False, +) -> int: + async def setup() -> int: + async with get_session() as session: + ev = await create_event(session, slug=event_slug, display_name="AI Event") + room = await create_room(session, event_id=ev.id, display_name="Main Hall") + room.floor_translation_enabled = floor_translation_enabled + room.floor_tts_enabled = floor_tts_enabled + session.add( + RoomTranslationLanguage( + room_id=room.id, + language_code=lang_code, + language_name=lang_name, + enabled=lang_enabled, + tts_enabled=lang_tts_enabled, + ) + ) + if with_booth: + await create_booth( + session, + event_id=ev.id, + room_id=room.id, + language_code=lang_code, + language_name=lang_name, + ) + await session.flush() + return room.id + + return anyio.run(setup) + + +def _extract_embed_config(html: str) -> dict: + match = re.search(r'', html, re.S) + assert match, "embed-config JSON block not found" + return json.loads(match.group(1)) + + +def test_embed_ai_voice_channel_resolves_tts_config(): + room_id = _seed_ai_embed_room("ai-voice-ev", lang_code="es", floor_tts_enabled=True, lang_tts_enabled=True) + token = _embed_listener_token("ai-voice-ev") + res = client.get(f"/embed/ai-voice-ev/{room_id}/es?token={token}&captions=true", headers={"accept": "text/html"}) + assert res.status_code == 200, res.text + cfg = _extract_embed_config(res.text) + assert cfg["audio_mode"] == "tts" + assert cfg["whep_url"] == "" + assert cfg["tts_url"].endswith(f"/ws/tts/{room_id}/es/ai-voice-ev-{room_id}-floor") + assert cfg["caption_url"].endswith(f"/ws/captions/ai-voice-ev-{room_id}-es") + assert cfg["target_lang_code"] == "es" + assert cfg["captions_enabled"] is True + + +def test_embed_ai_text_channel_resolves_captions_only(): + room_id = _seed_ai_embed_room("ai-text-ev", lang_code="de", floor_tts_enabled=True, lang_tts_enabled=False) + token = _embed_listener_token("ai-text-ev") + res = client.get(f"/embed/ai-text-ev/{room_id}/de?token={token}", headers={"accept": "text/html"}) + assert res.status_code == 200, res.text + cfg = _extract_embed_config(res.text) + assert cfg["audio_mode"] == "none" + assert cfg["whep_url"] == "" + assert cfg["tts_url"] == "" + assert cfg["caption_url"].endswith(f"/ws/captions/ai-text-ev-{room_id}-de") + assert cfg["captions_enabled"] is True + + +def test_embed_ai_text_caption_ws_delivers_caption(): + room_id = _seed_ai_embed_room("ai-cap-ev", lang_code="de", floor_tts_enabled=True, lang_tts_enabled=False) + token = _embed_listener_token("ai-cap-ev") + res = client.get(f"/embed/ai-cap-ev/{room_id}/de?token={token}", headers={"accept": "text/html"}) + assert res.status_code == 200, res.text + cfg = _extract_embed_config(res.text) + + channel = f"ai-cap-ev-{room_id}-de" + payload = {"type": "translated_caption", "status": "final", "text": "Hallo Welt"} + with client.websocket_connect(f"{cfg['caption_url']}?token={token}") as ws: + ws.portal.call(listener_manager.broadcast, channel, payload) + received = [] + + def read_until_caption() -> None: + for _ in range(5): + msg = ws.receive_json() + received.append(msg) + if msg.get("type") == "translated_caption": + return + + reader = threading.Thread(target=read_until_caption, daemon=True) + reader.start() + reader.join(5.0) + assert not reader.is_alive(), "Timed out waiting for caption message" + assert any(m == payload for m in received), f"Expected caption payload, got {received}" + + +def test_embed_disabled_ai_language_returns_404(): + room_id = _seed_ai_embed_room("ai-off-ev", lang_code="fr", lang_enabled=False) + token = _embed_listener_token("ai-off-ev") + res = client.get(f"/embed/ai-off-ev/{room_id}/fr?token={token}") + assert res.status_code == 404 + + +def test_embed_booth_takes_precedence_over_ai_language(): + room_id = _seed_ai_embed_room("both-ev", lang_code="es", with_booth=True) + token = _embed_listener_token("both-ev") + res = client.get(f"/embed/both-ev/{room_id}/es?token={token}", headers={"accept": "text/html"}) + assert res.status_code == 200, res.text + cfg = _extract_embed_config(res.text) + assert cfg["audio_mode"] == "whep" + assert cfg["whep_url"].endswith(f"/both-ev/{room_id}/es/whep") + assert cfg["tts_url"] == "" + + +def test_embed_legacy_single_room_route_supports_ai_voice(): + room_id = _seed_ai_embed_room("single-ai-ev", lang_code="es") + token = _embed_listener_token("single-ai-ev") + res = client.get(f"/embed/single-ai-ev/es?token={token}", headers={"accept": "text/html"}) + assert res.status_code == 200, res.text + cfg = _extract_embed_config(res.text) + assert cfg["audio_mode"] == "tts" + assert cfg["tts_url"].endswith(f"/ws/tts/{room_id}/es/single-ai-ev-{room_id}-floor") + + +def test_ws_tts_accepts_embed_token_and_rejects_cross_event_embed_token(): + room_id = _seed_ai_embed_room("embed-tts-ws", lang_code="es") + valid_tok = _embed_listener_token("embed-tts-ws") + booth_id = f"embed-tts-ws-{room_id}-floor" + with client.websocket_connect(f"/ws/tts/{room_id}/es/{booth_id}?token={valid_tok}") as ws: + ws.portal.call( + lambda: tts_manager.broadcast_bundle( + room_id, + "es", + booth_id, + b"\x01\x02\x03\x04", + "seg-1", + 1, + translation="Hola", + ) + ) + frames: list[bytes] = [] + reader = threading.Thread(target=lambda: frames.append(ws.receive_bytes()), daemon=True) + reader.start() + reader.join(5.0) + assert not reader.is_alive() and len(frames) == 1, "Timed out waiting for TTS bundle" + assert b"Hola" in frames[0] and frames[0].endswith(b"\x01\x02\x03\x04") + + other_tok = _embed_listener_token("other-event") + with pytest.raises(WebSocketDisconnect) as exc_info: + with client.websocket_connect(f"/ws/tts/{room_id}/es/{booth_id}?token={other_tok}") as ws: + _expect_refusal(ws) + assert exc_info.value.code == 4003 + + +def test_embed_room_scoped_token_enforces_room_on_page_and_ws(): + from portal.auth import create_embed_token + + async def setup() -> tuple[int, int]: + async with get_session() as session: + ev = await create_event(session, slug="scoped-ev", display_name="Scoped Event") + r1 = await create_room(session, event_id=ev.id, display_name="Room 1") + r2 = await create_room(session, event_id=ev.id, display_name="Room 2") + r1.floor_translation_enabled = True + r2.floor_translation_enabled = True + session.add( + RoomTranslationLanguage(room_id=r1.id, language_code="de", language_name="German", enabled=True) + ) + session.add( + RoomTranslationLanguage(room_id=r2.id, language_code="de", language_name="German", enabled=True) + ) + await session.flush() + return r1.id, r2.id + + r1_id, r2_id = anyio.run(setup) + scoped_r1 = create_embed_token(event_slug="scoped-ev", room_id=r1_id) + unscoped = create_embed_token(event_slug="scoped-ev") + + # Same-room /embed succeeds; cross-room /embed returns 403; unscoped works for both + assert client.get(f"/embed/scoped-ev/{r1_id}/de?token={scoped_r1}", headers={"accept": "text/html"}).status_code == 200 + assert client.get(f"/embed/scoped-ev/{r2_id}/de?token={scoped_r1}", headers={"accept": "text/html"}).status_code == 403 + assert client.get(f"/embed/scoped-ev/{r1_id}/de?token={unscoped}", headers={"accept": "text/html"}).status_code == 200 + assert client.get(f"/embed/scoped-ev/{r2_id}/de?token={unscoped}", headers={"accept": "text/html"}).status_code == 200 + + # Same-room /ws/captions connects; cross-room /ws/captions closes with 4003; unscoped works for both + def _assert_caption_connects(booth_id: str, tok: str) -> None: + payload = {"type": "caption", "status": "final", "text": "ok"} + with client.websocket_connect(f"/ws/captions/{booth_id}?token={tok}") as ws: + ws.portal.call(listener_manager.broadcast, booth_id, payload) + got: list[dict] = [] + + def read() -> None: + for _ in range(5): + msg = ws.receive_json() + got.append(msg) + if msg.get("type") == "caption": + return + + reader = threading.Thread(target=read, daemon=True) + reader.start() + reader.join(5.0) + assert not reader.is_alive() and payload in got + + _assert_caption_connects(f"scoped-ev-{r1_id}-de", scoped_r1) + + with pytest.raises(WebSocketDisconnect) as exc_info: + with client.websocket_connect(f"/ws/captions/scoped-ev-{r2_id}-de?token={scoped_r1}") as ws: + _expect_refusal(ws) + assert exc_info.value.code == 4003 + + _assert_caption_connects(f"scoped-ev-{r2_id}-de", unscoped) + + +def test_ws_tts_expired_embed_token_closes_with_4001_on_connect_and_midstream(monkeypatch): + from datetime import datetime, timedelta, timezone + + import jwt + + from portal.auth import LISTENER_TOKEN_KIND + from portal.config import settings + + room_id = _seed_ai_embed_room("tts-exp-ev", lang_code="es") + booth_id = f"tts-exp-ev-{room_id}-floor" + + expired_tok = jwt.encode( + { + "sub": "exp-sub", + "kind": LISTENER_TOKEN_KIND, + "purpose": "embed", + "event_slug": "tts-exp-ev", + "iat": datetime.now(timezone.utc) - timedelta(hours=1), + "exp": datetime.now(timezone.utc) - timedelta(seconds=10), + }, + settings.effective_jwt_secret, + algorithm="HS256", + ) + with pytest.raises(WebSocketDisconnect) as exc_info: + with client.websocket_connect(f"/ws/tts/{room_id}/es/{booth_id}?token={expired_tok}") as ws: + _expect_refusal(ws) + assert exc_info.value.code == 4001 + + # Mid-stream expiry during 5s recheck closes with 4001 + valid_tok = _embed_listener_token("tts-exp-ev") + orig_reauth = tts_manager.reauthorize_seconds + tts_manager.reauthorize_seconds = 0.0 + try: + with client.websocket_connect(f"/ws/tts/{room_id}/es/{booth_id}?token={valid_tok}") as ws: + # Force subsequent decode_token calls to raise ExpiredSignatureError + import portal.auth as portal_auth + + def _expired_decode(_token: str): + raise jwt.ExpiredSignatureError("Token expired mid-stream") + + monkeypatch.setattr(portal_auth, "decode_token", _expired_decode) + ws.portal.call( + lambda: tts_manager.broadcast_bundle( + room_id, + "es", + booth_id, + b"\x01\x02", + "seg-exp", + 1, + translation="Adios", + ) + ) + with pytest.raises(WebSocketDisconnect) as mid_exc: + _expect_refusal(ws) + assert mid_exc.value.code == 4001 + finally: + tts_manager.reauthorize_seconds = orig_reauth + + def test_unhandled_exception_response_has_security_headers(): @app.get("/__boom", include_in_schema=False) async def boom(): diff --git a/website/docs/listener/attending-an-event.mdx b/website/docs/listener/attending-an-event.mdx index e1e689d41..7aa8674d9 100644 --- a/website/docs/listener/attending-an-event.mdx +++ b/website/docs/listener/attending-an-event.mdx @@ -60,6 +60,16 @@ If your browser's autoplay policy prevents audio from starting automatically, a Audio starts within a second over WebRTC. You are now listening to live interpretation. Leave this tab open for the duration of the session. +## Embedded Player & AI Channels + +Event organizers can embed a compact VoxBento player directly into third-party websites using a short-lived embed token (`/embed/{event_slug}/{room_id}/{language_code}?token=...`). + +Depending on how the room is configured, the embed player automatically selects the right delivery mode for each language: + +- **Interpreter Booth / Floor (WebRTC):** Streams live human audio via WHEP when a booth or floor audio source is active. +- **AI Voice (TTS):** When a room has AI floor translation and text-to-speech enabled for a language without a human booth, the embed player streams synthesized audio over WebSockets and renders translated captions alongside it (for standalone `/embed/` URLs, translated captions are rendered only when `captions=true` is included). +- **AI Captions Only:** When AI translation is enabled for a language without TTS or a human booth, the player hides the audio play button, enables live captions automatically, and displays or posts translated captions in real time. + --- ## Frequently Asked Questions