chore: brand icon and title by default
This commit is contained in:
1 parent
8e61dc111c
commit
b4fcbd38ba
17 files changed
+1254
-213
No files matched your search
@@ -124,6 +124,28 @@ def _valid_replay_url(url: str | None) -> str | None:
|
||||
return url
|
||||
|
||||
|
||||
def _parse_scheduled_at(value: str | None) -> datetime | None:
|
||||
"""Turn the ISO string a client sends into the value the column stores.
|
||||
|
||||
`scheduled_at` is a DateTime column and SQLite's binder rejects a str outright
|
||||
("SQLite DateTime type only accepts Python datetime and date objects"), so an
|
||||
update that carried a schedule failed with a 500 — a large part of why the
|
||||
schedule looked like a property that could only be set at creation.
|
||||
|
||||
Creation stores UTC wall-clock with tzinfo dropped; do the same here.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail="预定开播时间格式无效") from exc
|
||||
return parsed.replace(tzinfo=None) if parsed.tzinfo else parsed
|
||||
|
||||
|
||||
def _utc_iso(moment: datetime) -> str:
|
||||
"""Render a stored timestamp as an explicit UTC instant for JSON.
|
||||
|
||||
@@ -263,6 +285,14 @@ async def viewer_heartbeat(stream_id: int, body: ViewerHeartbeat,
|
||||
stream = await StreamService(db).get_stream(stream_id)
|
||||
if not stream:
|
||||
raise HTTPException(status_code=404, detail="节目不存在")
|
||||
if stream.status.value != "live":
|
||||
# Audit sessions describe live playback: node, rendition, buffer and remote
|
||||
# adjustment only mean something while the programme is on air. A replay is
|
||||
# a plain file served straight to the browser, so recording a session for it
|
||||
# only filled the audit board with rows nobody could act on. This answers a
|
||||
# no-op instead of an error so a tab left open across the end of a broadcast
|
||||
# does not start failing its heartbeats.
|
||||
return {"ok": True, "remote_adjusted": False, "audit_active": False}
|
||||
session_id = body.session_id.strip()
|
||||
if not session_id or len(session_id) > 64:
|
||||
raise HTTPException(status_code=422, detail="观众会话 ID 无效")
|
||||
@@ -428,6 +458,14 @@ async def update_stream(stream_id: int, body: StreamUpdate, db: AsyncSession = D
|
||||
if replay_fields.intersection(updates) and existing.status.value != "ended":
|
||||
raise HTTPException(status_code=409, detail="仅已结束的节目可以配置回放和章节")
|
||||
|
||||
if "title" in updates:
|
||||
title = (updates["title"] or "").strip()
|
||||
if not title:
|
||||
raise HTTPException(status_code=422, detail="节目标题不能为空")
|
||||
updates["title"] = title
|
||||
if "scheduled_at" in updates:
|
||||
updates["scheduled_at"] = _parse_scheduled_at(updates["scheduled_at"])
|
||||
|
||||
if updates.get("replay_file"):
|
||||
_media_path(updates["replay_file"])
|
||||
if "replay_url" in updates and updates["replay_url"] is not None:
|
||||
@@ -561,6 +599,8 @@ async def create_remote_session(stream_id: int, body: RemoteSessionCreate,
|
||||
stream = await StreamService(db).get_stream(stream_id)
|
||||
if not stream or not stream.remote_control_enabled:
|
||||
raise HTTPException(status_code=409, detail="节目未启用远程控制")
|
||||
if stream.status.value != "live":
|
||||
raise HTTPException(status_code=409, detail="节目未在直播,无需控制回放观众")
|
||||
expires_in = min(max(body.expires_in, 30), 3600)
|
||||
session = ControlSession(
|
||||
token=secrets.token_urlsafe(24),
|
||||
@@ -586,6 +626,8 @@ async def send_remote_command(stream_id: int, body: RemoteCommand,
|
||||
stream = await StreamService(db).get_stream(stream_id)
|
||||
if not stream or not stream.remote_control_enabled:
|
||||
raise HTTPException(status_code=409, detail="节目未启用远程控制")
|
||||
if stream.status.value != "live":
|
||||
raise HTTPException(status_code=409, detail="节目未在直播,无需控制回放观众")
|
||||
if body.action not in {"switch_node", "switch_quality", "restore_auto"}:
|
||||
raise HTTPException(status_code=422, detail="不支持的远程命令")
|
||||
if not body.targets:
|
||||
@@ -616,6 +658,14 @@ async def send_remote_command(stream_id: int, body: RemoteCommand,
|
||||
@router.get("/{stream_id}/remote-command")
|
||||
async def poll_remote_command(stream_id: int, session_id: str,
|
||||
db: AsyncSession = Depends(get_db)):
|
||||
stream = await StreamService(db).get_stream(stream_id)
|
||||
if not stream:
|
||||
raise HTTPException(status_code=404, detail="节目不存在")
|
||||
if stream.status.value != "live" or not stream.remote_control_enabled:
|
||||
# Same rule as heartbeats: nobody is audited during a replay, and a
|
||||
# programme that never opted into control must not have viewers polling for
|
||||
# commands either. Answer "nothing to do" instead of registering a session.
|
||||
return None
|
||||
viewer = await db.get(ViewerSession, session_id)
|
||||
if not viewer:
|
||||
raise HTTPException(status_code=404, detail="观众会话不存在")
|
||||
|
||||
@@ -192,6 +192,19 @@ class StreamService:
|
||||
stream = await self.get_stream_by_key(stream_key)
|
||||
if not stream:
|
||||
return {"lines": [], "qualities": [], "multicast_available": False, "selected_node": None}
|
||||
# Live HLS lines only exist while the programme is on air. Before it starts
|
||||
# nothing has been published to MediaMTX, and once it has ended the
|
||||
# playlists under /hls/<key> are stale or gone. Handing those URLs back for
|
||||
# a pending or ended programme is what made the replay watch API carry live
|
||||
# HLS data: the viewer page then showed a dead line/quality picker instead
|
||||
# of the recorded file it was actually meant to play.
|
||||
if stream.status != StreamStatus.live:
|
||||
return {
|
||||
"lines": [],
|
||||
"qualities": [],
|
||||
"multicast_available": multicast_detector.is_available(),
|
||||
"selected_node": None,
|
||||
}
|
||||
qualities = self.watch_renditions(stream)
|
||||
best_node = lb.select_best_node(client_ip)
|
||||
if not best_node:
|
||||
|
||||
@@ -18,6 +18,7 @@ class StreamAccessSerializationTest(unittest.TestCase):
|
||||
"ended_at": None,
|
||||
"multicast_enabled": False,
|
||||
"replay_file": None,
|
||||
"replay_url": None,
|
||||
"chapters_json": "[]",
|
||||
"transcode_profile": "default",
|
||||
"homepage_visible": False,
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from database import Base
|
||||
from models.audit import ViewerSession
|
||||
from models.stream import StreamStatus
|
||||
from routes.streams import (
|
||||
ViewerHeartbeat,
|
||||
_parse_scheduled_at,
|
||||
poll_remote_command,
|
||||
viewer_heartbeat,
|
||||
)
|
||||
from services import stream_service as stream_service_module
|
||||
from services.stream_service import StreamService
|
||||
|
||||
|
||||
def _multicast_off():
|
||||
"""Keep the watch-URL tests off the network; the probe is a real socket call."""
|
||||
return patch.object(stream_service_module.multicast_detector, "is_available", return_value=False)
|
||||
|
||||
|
||||
class StreamTestBase(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.engine = create_async_engine("sqlite+aiosqlite:///:memory:")
|
||||
async with self.engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
self.session_factory = async_sessionmaker(self.engine, expire_on_commit=False)
|
||||
|
||||
async def asyncTearDown(self):
|
||||
await self.engine.dispose()
|
||||
|
||||
async def make_stream(self, **fields):
|
||||
async with self.session_factory() as session:
|
||||
stream = await StreamService(session).create_stream(title="Programme")
|
||||
if fields:
|
||||
await StreamService(session).update_stream(stream.id, **fields)
|
||||
return stream.id, stream.stream_key
|
||||
|
||||
|
||||
class WatchUrlScopeTest(StreamTestBase):
|
||||
"""The watch API must not mix live HLS into a programme that is not on air."""
|
||||
|
||||
async def test_ended_programme_exposes_no_live_hls_lines(self):
|
||||
_, key = await self.make_stream(status=StreamStatus.ended, replay_url="https://cdn.example.com/vod.mp4")
|
||||
with _multicast_off():
|
||||
async with self.session_factory() as session:
|
||||
urls = await StreamService(session).get_watch_urls(key, None)
|
||||
self.assertEqual(urls["lines"], [])
|
||||
self.assertEqual(urls["qualities"], [])
|
||||
self.assertIsNone(urls["selected_node"])
|
||||
|
||||
async def test_pending_programme_exposes_no_live_hls_lines_yet(self):
|
||||
_, key = await self.make_stream(status=StreamStatus.pending)
|
||||
with _multicast_off():
|
||||
async with self.session_factory() as session:
|
||||
urls = await StreamService(session).get_watch_urls(key, None)
|
||||
self.assertEqual(urls["lines"], [])
|
||||
self.assertEqual(urls["qualities"], [])
|
||||
|
||||
async def test_live_programme_still_exposes_hls_lines_and_renditions(self):
|
||||
_, key = await self.make_stream(status=StreamStatus.live)
|
||||
with _multicast_off():
|
||||
async with self.session_factory() as session:
|
||||
urls = await StreamService(session).get_watch_urls(key, None)
|
||||
self.assertEqual(len(urls["lines"]), 1)
|
||||
line = urls["lines"][0]
|
||||
self.assertEqual(line["url"], f"/hls/{key}/index.m3u8")
|
||||
self.assertTrue(line["qualities"])
|
||||
self.assertTrue(urls["qualities"])
|
||||
# The stream-copy rendition leads the ladder and is served from its slug.
|
||||
self.assertEqual(line["qualities"][0]["url"], f"/hls/{key}/source/index.m3u8")
|
||||
self.assertIsNotNone(urls["selected_node"])
|
||||
|
||||
|
||||
class ViewerAuditScopeTest(StreamTestBase):
|
||||
"""Viewer heartbeats and remote control exist for live playback only."""
|
||||
|
||||
async def test_heartbeat_is_a_noop_for_a_replay_programme(self):
|
||||
stream_id, _ = await self.make_stream(status=StreamStatus.ended)
|
||||
async with self.session_factory() as session:
|
||||
payload = await viewer_heartbeat(
|
||||
stream_id, ViewerHeartbeat(session_id="viewer-replay"), session
|
||||
)
|
||||
self.assertTrue(payload["ok"])
|
||||
self.assertFalse(payload["remote_adjusted"])
|
||||
self.assertFalse(payload["audit_active"])
|
||||
async with self.session_factory() as session:
|
||||
self.assertIsNone(await session.get(ViewerSession, "viewer-replay"))
|
||||
|
||||
async def test_heartbeat_registers_a_session_for_a_live_programme(self):
|
||||
stream_id, _ = await self.make_stream(status=StreamStatus.live, remote_control_enabled=True)
|
||||
async with self.session_factory() as session:
|
||||
payload = await viewer_heartbeat(
|
||||
stream_id, ViewerHeartbeat(session_id="viewer-live", quality="720p"), session
|
||||
)
|
||||
self.assertTrue(payload["ok"])
|
||||
async with self.session_factory() as session:
|
||||
viewer = await session.get(ViewerSession, "viewer-live")
|
||||
self.assertIsNotNone(viewer)
|
||||
self.assertEqual(viewer.quality, "720p")
|
||||
|
||||
async def test_remote_command_poll_stays_closed_for_a_replay_programme(self):
|
||||
stream_id, _ = await self.make_stream(status=StreamStatus.ended, remote_control_enabled=True)
|
||||
async with self.session_factory() as session:
|
||||
self.assertIsNone(await poll_remote_command(stream_id, "viewer-replay", session))
|
||||
|
||||
async def test_remote_command_poll_stays_closed_without_an_opt_in(self):
|
||||
stream_id, _ = await self.make_stream(status=StreamStatus.live, remote_control_enabled=False)
|
||||
async with self.session_factory() as session:
|
||||
self.assertIsNone(await poll_remote_command(stream_id, "viewer-live", session))
|
||||
|
||||
|
||||
class ScheduledAtParseTest(unittest.TestCase):
|
||||
"""The PUT route has to turn the client's ISO string into a datetime itself."""
|
||||
|
||||
def test_iso_z_suffix_is_stored_as_naive_utc(self):
|
||||
self.assertEqual(
|
||||
_parse_scheduled_at("2026-08-12T21:49:12.000Z"),
|
||||
datetime(2026, 8, 12, 21, 49, 12),
|
||||
)
|
||||
|
||||
def test_empty_values_clear_the_schedule(self):
|
||||
self.assertIsNone(_parse_scheduled_at(None))
|
||||
self.assertIsNone(_parse_scheduled_at(" "))
|
||||
|
||||
def test_invalid_value_is_rejected_with_422(self):
|
||||
with self.assertRaises(HTTPException) as caught:
|
||||
_parse_scheduled_at("not-a-date")
|
||||
self.assertEqual(caught.exception.status_code, 422)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user