diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 0a1bbb1..113f30e 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -1,124 +1,233 @@ -# Deployment - -The maintained deployment target for this project is Windows first. Linux and macOS can still run services manually, but real end-to-end deployment testing should use the PowerShell flow below. - -Runtime paths are resolved relative to the repository by default and can be overridden with environment variables. - -- LS_DATABASE_URL: SQLAlchemy database URL. -- LS_REPLAY_MEDIA_DIR: server-local directory containing replay files. When started by start.ps1, the default is runtime\replay under the repository. -- LS_HLS_RUNTIME_DIR: backend and FFmpeg HLS output directory. When started by start.ps1, the default is runtime\hls under the repository. - -## Windows deployment - -Run these commands from PowerShell on the Windows node. - -### 1. Install prerequisites - -Required on PATH: Python 3.11+, FFmpeg, and MediaMTX. MediaMTX may instead be left in the repository's `mediamtx\` directory, which is where the backend looks second. Node.js is only needed to build the frontend for deployment. - -### 2. Install application dependencies - -```powershell -powershell -ExecutionPolicy Bypass -File .\start.ps1 -InstallDeps -``` - -### 3. Build the frontend - -Once per deployment, and again whenever the frontend changes. The build output is -committed to the server by the build step and then served by the backend itself, -so **Node.js is a build-time dependency only** — production runs without it and -without a Vite dev server. - -```powershell -cd frontend -npm install -npm run build -cd .. -``` - -Skipping this is not silent: the backend answers every page with HTTP 503 and -`s Frontend not built` until `frontend\dist` exists. - -### 4. Start the stack - -```powershell -powershell -ExecutionPolicy Bypass -File .\start.ps1 -``` - -This starts one process on 0.0.0.0:8080 that owns everything: - -- **The frontend** is served from `frontend\dist` on the same port. Unknown paths - return the app shell so client-side routes survive a refresh. -- **MediaMTX** is started at boot if nothing is already answering its API on :9997, and restarted by the supervisor if it dies. Set `LS_MEDIA_ORIGIN_AUTOSTART=false` to manage it externally; the backend then only supervises transcoders. -- **Transcoders** are started for every live stream whose MediaMTX path is publishing, and restarted within ~10s of an ffmpeg process exiting. They encode on the GPU when one is available (see below). -- **HLS** is written under `runtime\hls` and served through `GET /hls/...`, which falls back to proxying MediaMTX's own HLS when the local files are absent. - -Open http://127.0.0.1:8080/ for the site and /docs for the API. Publish RTMP to -rtmp://127.0.0.1:1935/live/. - -### Hardware encoding - -The transcoders detect the best encoder the host actually has, at startup, by -encoding a test frame with each candidate in turn: - -1. `h264_nvenc` / `hevc_nvenc` (NVIDIA) -2. `h264_qsv` (Intel iGPU) -3. `h264_amf` (AMD) -4. `libx264` (CPU fallback) - -Only encoders that really work are used — being compiled into ffmpeg is not -enough, since `h264_amf` fails without `amfrt64.dll` and `h264_qsv` fails without -an Intel iGPU. The choice is logged at startup as `[transcoder] hardware encoder: -…`, or `[transcoder] no working hardware encoder; falling back to libx264` with -the probed candidates listed. On the reference GTX 1060, one 1080p→720p -rendition costs ~62% of a core on NVENC versus ~109% on libx264 ultrafast. - -### 5. Useful variants - -```powershell -powershell -ExecutionPolicy Bypass -File .\start.ps1 -HostAddress 0.0.0.0 -BackendPort 8080 -``` - -### 6. Smoke test commands - -```powershell -curl.exe http://127.0.0.1:8080/api/health -curl.exe http://127.0.0.1:9997/v3/paths/list -ffmpeg -version -mediamtx --version -nvidia-smi -``` - -If browser or network tests run from another machine, open the Windows firewall for ports 8080, 1935, and 8888. - -## Windows edge node launcher - -Build and start an edge node from a Windows edge machine: - -```powershell -powershell -ExecutionPolicy Bypass -File .\edge-agent\start-edge.ps1 -Build -OriginUrl http://:8080 -NodeId edge-win-01 -Region default -HlsPort 8889 -ApiPort 9997 -``` - -For normal subsequent starts, omit `-Build`: - -```powershell -powershell -ExecutionPolicy Bypass -File .\edge-agent\start-edge.ps1 -OriginUrl http://:8080 -NodeId edge-win-01 -Region default -HlsPort 8889 -ApiPort 9997 -``` - -The launcher sets the StreamCore edge environment variables, starts the Windows edge-agent executable, stores runtime data under `ProgramData\StreamCore\edge\` by default, and writes logs to that node data directory. The edge agent then manages its embedded MediaMTX edge process. - -## Edge node scripts - -```cmd -mediamtx\scripts\start_origin.bat -mediamtx\scripts\start_edge.bat 1 127.0.0.1 -mediamtx\scripts\check_multicast.bat -``` - -## Replay file safety - -Replay records store paths relative to LS_REPLAY_MEDIA_DIR. Absolute paths and parent-directory traversal are rejected. - -## Linux and macOS - -Linux and macOS are not the primary deployment path. For local development, run the backend with uvicorn from `backend`, run the frontend with `npm run dev` from `frontend`, and set `LS_HLS_RUNTIME_DIR` to a writable directory. \ No newline at end of file +# Deployment + +The maintained deployment target for this project is Windows first. Linux and macOS can still run services manually, but real end-to-end deployment testing should use the PowerShell flow below. + +Runtime paths are resolved relative to the repository by default and can be overridden with environment variables. + +- LS_DATABASE_URL: SQLAlchemy database URL. +- LS_REPLAY_MEDIA_DIR: server-local directory containing replay files. When started by start.ps1, the default is runtime\replay under the repository. +- LS_HLS_RUNTIME_DIR: backend and FFmpeg HLS output directory. When started by start.ps1, the default is runtime\hls under the repository. + +## Windows deployment + +Run these commands from PowerShell on the Windows node. + +### 1. Install prerequisites + +Required on PATH: Python 3.11+, FFmpeg, and MediaMTX. MediaMTX may instead be left in the repository's `mediamtx\` directory, which is where the backend looks second. Node.js is only needed to build the frontend for deployment. + +### 2. Install application dependencies + +```powershell +powershell -ExecutionPolicy Bypass -File .\start.ps1 -InstallDeps +``` + +### 3. Build the frontend + +Once per deployment, and again whenever the frontend changes. The build output is +committed to the server by the build step and then served by the backend itself, +so **Node.js is a build-time dependency only** — production runs without it and +without a Vite dev server. + +```powershell +cd frontend +npm install +npm run build +cd .. +``` + +Skipping this is not silent: the backend answers every page with HTTP 503 and +`s Frontend not built` until `frontend\dist` exists. + +### 4. Start the stack + +```powershell +powershell -ExecutionPolicy Bypass -File .\start.ps1 +``` + +This starts one process on 0.0.0.0:8080 that owns everything: + +- **The frontend** is served from `frontend\dist` on the same port. Unknown paths + return the app shell so client-side routes survive a refresh. +- **MediaMTX** is started at boot if nothing is already answering its API on :9997, and restarted by the supervisor if it dies. Set `LS_MEDIA_ORIGIN_AUTOSTART=false` to manage it externally; the backend then only supervises transcoders. +- **Transcoders** are started for every live stream whose MediaMTX path is publishing, and restarted within ~10s of an ffmpeg process exiting. They encode on the GPU when one is available (see below). +- **HLS** is written under `runtime\hls` and served through `GET /hls/...`, which falls back to proxying MediaMTX's own HLS when the local files are absent. + +Open http://127.0.0.1:8080/ for the site and /docs for the API. Publish RTMP to +rtmp://127.0.0.1:1935/live/. + +### Hardware encoding + +The transcoders detect the best encoder the host actually has, at startup, by +encoding a test frame with each candidate in turn: + +1. `h264_nvenc` / `hevc_nvenc` (NVIDIA) +2. `h264_qsv` (Intel iGPU) +3. `h264_amf` (AMD) +4. `libx264` (CPU fallback) + +Only encoders that really work are used — being compiled into ffmpeg is not +enough, since `h264_amf` fails without `amfrt64.dll` and `h264_qsv` fails without +an Intel iGPU. The choice is logged at startup as `[transcoder] hardware encoder: +…`, or `[transcoder] no working hardware encoder; falling back to libx264` with +the probed candidates listed. On the reference GTX 1060, one 1080p→720p +rendition costs ~62% of a core on NVENC versus ~109% on libx264 ultrafast. + +### 5. Useful variants + +```powershell +powershell -ExecutionPolicy Bypass -File .\start.ps1 -HostAddress 0.0.0.0 -BackendPort 8080 +``` + +### 6. Smoke test commands + +```powershell +curl.exe http://127.0.0.1:8080/api/health +curl.exe http://127.0.0.1:9997/v3/paths/list +ffmpeg -version +mediamtx --version +nvidia-smi +``` + +If browser or network tests run from another machine, open the Windows firewall for ports 8080, 1935, and 8888. + +## Windows service: autostart behind nginx + +`start.ps1` above is the manual/dev path: one foreground process on :8080 that +serves the frontend itself. On the production box the stack instead runs as a +background service behind nginx, and `scripts\streamcore-service.ps1` owns it. + +```powershell +# one-off, elevated: register the boot task +powershell -ExecutionPolicy Bypass -File .\scripts\streamcore-service.ps1 -Action Install + +# day to day +powershell -ExecutionPolicy Bypass -File .\scripts\streamcore-service.ps1 -Action Status +powershell -ExecutionPolicy Bypass -File .\scripts\streamcore-service.ps1 -Action Restart +powershell -ExecutionPolicy Bypass -File .\scripts\streamcore-service.ps1 -Action Stop +powershell -ExecutionPolicy Bypass -File .\scripts\streamcore-service.ps1 -Action Doctor +``` + +- The scheduled task `StreamCore-AutoStart` fires at startup as **SYSTEM**, with a + 20-second delay, no execution time limit, and restart-on-failure. It runs in + session 0, so no console window ever appears. +- nginx is `D:\nginx-1.31.6`, started with `-p D:\nginx-1.31.6` so the relative + paths in `conf\nginx.conf` resolve inside that directory. It serves + `frontend\dist` and the HLS segments from disk and proxies `/api/`, `/docs`, + `/openapi.json` and the HLS fallback to `127.0.0.1:8080`. +- The backend is plain `uvicorn main:app --port 8080` against the machine-wide + Python install, not a venv. If it dies the launcher restarts it after 10s, and + nginx is re-checked on every 15s health tick. +- MediaMTX is still owned by the backend, which starts it if nothing answers + :9997 (see `LS_MEDIA_ORIGIN_AUTOSTART` above). + +Two things about running as SYSTEM are worth knowing, because both fail *only* +in service mode: + +- **ffmpeg.** winget installs it per-user, so SYSTEM never sees it on PATH. The + launcher prepends `%LOCALAPPDATA%\Microsoft\WinGet\Links` explicitly. Run + `-Action Doctor` and check the `executables` block after a reboot to confirm. +- **`nginx -s reload` / `-s stop`.** nginx signals its master through the global + event `Global\ngx_stop_`, which an administrator shell cannot open + (`OpenEvent ... Access is denied`). Use `-Action Restart` after editing + `nginx.conf`; it replaces the worker tree directly. + +Logs land in `runtime\logs`: `backend.err.log` (uvicorn banner) and +`backend.out.log` (request log), `service.log` (what the launcher did), +`nginx-launch.*.log`, plus nginx's own logs in `D:\nginx-1.31.6\logs`. + +## Windows edge node launcher + +Build and start an edge node from a Windows edge machine: + +```powershell +powershell -ExecutionPolicy Bypass -File .\edge-agent\start-edge.ps1 -Build -OriginUrl http://:8080 -NodeId edge-win-01 -Region default -HlsPort 8889 -ApiPort 9997 +``` + +For normal subsequent starts, omit `-Build`: + +```powershell +powershell -ExecutionPolicy Bypass -File .\edge-agent\start-edge.ps1 -OriginUrl http://:8080 -NodeId edge-win-01 -Region default -HlsPort 8889 -ApiPort 9997 +``` + +The launcher sets the StreamCore edge environment variables, starts the Windows edge-agent executable, stores runtime data under `ProgramData\StreamCore\edge\` by default, and writes logs to that node data directory. The edge agent then manages its embedded MediaMTX edge process. + +## Edge node scripts + +```cmd +mediamtx\scripts\start_origin.bat +mediamtx\scripts\start_edge.bat 1 127.0.0.1 +mediamtx\scripts\check_multicast.bat +``` + +## Replay file safety + +Replay records store paths relative to LS_REPLAY_MEDIA_DIR. Absolute paths and parent-directory traversal are rejected. + +## Linux (systemd, production) + +Reference host: Arch Linux, `newvision@10.1.120.53`, code and database under +`/opt/live`. Two units own everything; nothing runs in a shell. + +| Unit | Role | +| --- | --- | +| `streamcore-backend.service` | uvicorn on `127.0.0.1:18080`. Also supervises MediaMTX and the ffmpeg transcoders as child processes. | +| `nginx.service` | distro unit. Serves `frontend/dist` and the HLS segments from disk on :80/:443 and proxies `/api`, `/docs`, `/openapi.json` and the HLS fallback to the backend. | + +`/opt/live` is expected to be owned by `newvision` — the SQLite file, +`settings.json`, `nodes.json`, `runtime/` and `media/` are all written at runtime. + +### One-time setup + +```bash +# packages: nginx from pacman; Python deps in a venv (Arch enforces PEP 668, +# so a system-wide pip install is refused); npm only to build the frontend +sudo pacman -Sy --needed nginx npm +python3 -m venv /opt/live/backend/venv +/opt/live/backend/venv/bin/pip install -r /opt/live/backend/requirements.txt + +# MediaMTX ships no binary in the repo; drop the release build beside its config +tar -xzf mediamtx_v1.21.2_linux_amd64.tar.gz -C /tmp +install -m 755 /tmp/mediamtx /opt/live/mediamtx/mediamtx + +# the frontend is built once; dist/ is gitignored +cd /opt/live/frontend && npm install && npm run build + +sudo mkdir -p /etc/nginx/certs/{ecc,rsa} /opt/live/{media,runtime/{hls,replay,logs}} +sudo chown -R newvision:newvision /opt/live +``` + +### Ports + +`8080` is taken by the gitea container on the reference host, so the backend +listens on loopback `:18080` and only nginx is public. MediaMTX keeps its own +ports (`1935` RTMP, `8554` RTSP, `8888` HLS, `8889` WebRTC, `9997` API) and +publishers go to it directly — RTMP is not proxied through nginx. + +### Operating it + +```bash +systemctl status streamcore-backend +sudo systemctl restart streamcore-backend # restart; MediaMTX comes back with it +sudo journalctl -u streamcore-backend -f # backend + MediaMTX + transcoder logs +sudo systemctl reload nginx # only after editing the config +``` + +Both units are `enabled`, so a reboot brings the stack up without a login. + +### Notes specific to this host + +- **No GPU.** `detect_encoder()` probes NVENC/QSV/AMF and falls back to + `libx264`, logging the choice at startup. Expect CPU cost per rendition. +- **nginx file descriptors.** Arch sets only the *hard* `DefaultLimitNOFILE` + (524288) and leaves the soft limit at 1024, which makes nginx clamp + `worker_connections 4096` and warn. `/etc/systemd/system/nginx.service.d/nofile.conf` + pins `LimitNOFILE=65535:65535`. Running `nginx -t` by hand still inherits the + shell's 1024 and prints that warning — it is not the service's limit. +- **A stale `live` stream in the database** makes the lifespan start transcoders + for a publisher that is not there: a few ffmpeg processes spawn, exit, and sit + as zombies. Mark the row `ended` rather than leaving it `live`. + +For local development on any platform, run the backend with uvicorn from +`backend`, run the frontend with `npm run dev` from `frontend`, and set +`LS_HLS_RUNTIME_DIR` to a writable directory. \ No newline at end of file diff --git a/backend/routes/streams.py b/backend/routes/streams.py index 677fc5c..6c9b673 100644 --- a/backend/routes/streams.py +++ b/backend/routes/streams.py @@ -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="观众会话不存在") diff --git a/backend/services/stream_service.py b/backend/services/stream_service.py index d6b1f26..24dd0db 100644 --- a/backend/services/stream_service.py +++ b/backend/services/stream_service.py @@ -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/ 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: diff --git a/backend/tests/test_access_and_sessions.py b/backend/tests/test_access_and_sessions.py index ab2e0f7..839906f 100644 --- a/backend/tests/test_access_and_sessions.py +++ b/backend/tests/test_access_and_sessions.py @@ -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, diff --git a/backend/tests/test_live_only_audit.py b/backend/tests/test_live_only_audit.py new file mode 100644 index 0000000..9fdb032 --- /dev/null +++ b/backend/tests/test_live_only_audit.py @@ -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() diff --git a/frontend/index.html b/frontend/index.html index aa1e627..ec80305 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,9 +2,8 @@ - - StreamCore +
diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..ee3740f Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg deleted file mode 100644 index 6893eb1..0000000 --- a/frontend/public/favicon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/frontend/public/icons.svg b/frontend/public/icons.svg deleted file mode 100644 index e952219..0000000 --- a/frontend/public/icons.svg +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 88511f5..d8ad74c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -91,7 +91,8 @@ function RouteShell() { } /> } /> } /> - } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/admin/pages/LiveBoard.tsx b/frontend/src/admin/pages/LiveBoard.tsx index 9ecc593..a156ef0 100644 --- a/frontend/src/admin/pages/LiveBoard.tsx +++ b/frontend/src/admin/pages/LiveBoard.tsx @@ -3,6 +3,7 @@ import { RefreshCw, Maximize2, Minimize2, Users, Signal, TriangleAlert, Cpu, Mem import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Select, @@ -65,9 +66,13 @@ export default function LiveBoard() { const programs = await fetchStreams(true) setStreams(programs) const nextId = streamId || programs.find((p) => p.status === 'live')?.id + const nextProgram = programs.find((p) => p.id === nextId) if (nextId) { setStreamId(nextId) - setSessions(await fetchViewerSessions(nextId)) + // Viewer sessions audit live playback. A replay produces none — and rows + // left over from when the programme was live would describe a broadcast + // that is over — so nothing is fetched for a non-live programme. + setSessions(nextProgram?.status === 'live' ? await fetchViewerSessions(nextId) : []) } else { setSessions([]) } @@ -105,10 +110,13 @@ export default function LiveBoard() { if (nodeId === 'auto' && quality === 'auto') await sendRemoteCommand(streamId, session.token, 'restore_auto', targets) toast.success(`已向 ${selected.size} 个观众下发节点与清晰度策略`) } catch { - toast.error('控制命令下发失败,请确认节目已启用审计式播放控制') + toast.error('控制命令下发失败,请确认节目正在直播并已启用审计式播放控制') } } + const selectedProgram = streams.find((p) => p.id === streamId) + const isLiveProgram = selectedProgram?.status === 'live' + const activeSessions = sessions.filter((s) => Date.now() - new Date(s.last_heartbeat).getTime() < 30000) const buffering = activeSessions.filter( (s) => s.playback_state === 'buffering' || Number(s.buffered_seconds || 0) < 1, @@ -187,7 +195,16 @@ export default function LiveBoard() { - {streamId && ( + {streamId && !isLiveProgram && ( + + 观众会话审计仅适用于直播 + + 当前选中的节目不是直播状态。回放是直接下发的录制文件,没有线路、清晰度或播放控制可审计,因此不产生观众会话。 + + + )} + + {streamId && isLiveProgram && ( 审计式观众会话 diff --git a/frontend/src/admin/pages/ReplayEditor.tsx b/frontend/src/admin/pages/ReplayEditor.tsx index 9231d82..f5a33d6 100644 --- a/frontend/src/admin/pages/ReplayEditor.tsx +++ b/frontend/src/admin/pages/ReplayEditor.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react' import { useNavigate, useParams } from 'react-router-dom' -import { ArrowLeft, ArrowDown, ArrowUp, Trash2, Plus } from 'lucide-react' +import { ArrowLeft, ArrowDown, ArrowUp, Trash2, Plus, Pencil } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -123,10 +123,16 @@ export default function ReplayEditor() { return (
- +
+ + +
{!isEditable ? ( diff --git a/frontend/src/admin/pages/StreamForm.tsx b/frontend/src/admin/pages/StreamForm.tsx index f61fafc..24a134a 100644 --- a/frontend/src/admin/pages/StreamForm.tsx +++ b/frontend/src/admin/pages/StreamForm.tsx @@ -1,6 +1,6 @@ -import { useState } from 'react' -import { useNavigate } from 'react-router-dom' -import { Copy, ArrowLeft, CheckCircle2, Plus, Trash2 } from 'lucide-react' +import { useEffect, useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' +import { Copy, ArrowLeft, CheckCircle2, Plus, Trash2, Clapperboard } from 'lucide-react' import { toast } from 'sonner' import axios from 'axios' import { Button } from '@/components/ui/button' @@ -16,7 +16,7 @@ import { SelectTrigger, SelectValue, } from '@/components/ui/select' -import { createStream, type RenditionConfig } from '@/api/streams' +import { createStream, getStream, updateStream, type RenditionConfig } from '@/api/streams' const DEFAULT_RENDITIONS: RenditionConfig[] = [ { label: '1080p', enabled: true, width: 1920, height: 1080, fps: 30, codec: 'libx264', bitrate: '5000k', crf: 23, preset: 'veryfast', audio_bitrate: '128k', keyframe_seconds: 2 }, @@ -25,8 +25,28 @@ const DEFAULT_RENDITIONS: RenditionConfig[] = [ const PRESETS = ['ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium', 'slow'] +/** + * Render a stored schedule for a datetime-local input. + * + * Rows hold naive UTC ("2026-08-12 21:49:12"). Without the trailing Z the browser + * would read that as local time and shift the schedule by the UTC offset, which is + * exactly how a freshly created programme came back looking hours off. + */ +function toScheduledInput(value?: string | null): string { + if (!value) return '' + const normalized = /(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(value) ? value : `${value.replace(' ', 'T')}Z` + const date = new Date(normalized) + if (Number.isNaN(date.getTime())) return '' + const pad = (n: number) => String(n).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}` +} + export default function StreamForm() { const navigate = useNavigate() + const { id } = useParams<{ id: string }>() + const streamId = Number(id) + const isEdit = Number.isInteger(streamId) && streamId > 0 + const [title, setTitle] = useState('') const [description, setDescription] = useState('') const [coverUrl, setCoverUrl] = useState('') @@ -35,9 +55,47 @@ export default function StreamForm() { const [homepageVisible, setHomepageVisible] = useState(true) const [remoteControl, setRemoteControl] = useState(false) const [renditions, setRenditions] = useState(DEFAULT_RENDITIONS) + // True once the ladder is either stored on the programme or edited here. While it + // is false the form is only *showing* the preset's fallback tiers, and the update + // must not send them: that would silently pin the preset into a custom ladder. + const [renditionsPinned, setRenditionsPinned] = useState(false) + const [streamKey, setStreamKey] = useState('') + const [streamStatus, setStreamStatus] = useState('') + const [loadingData, setLoadingData] = useState(isEdit) const [loading, setLoading] = useState(false) const [result, setResult] = useState<{ rtmp_url: string; stream_key: string } | null>(null) + // Edit mode loads the programme first so every property starts at its stored + // value instead of the form defaults. + useEffect(() => { + if (!isEdit) return + let active = true + getStream(streamId) + .then((program) => { + if (!active) return + setTitle(program.title) + setDescription(program.description ?? '') + setCoverUrl(program.cover_url ?? '') + setScheduledAt(toScheduledInput(program.scheduled_at)) + setTranscodeProfile(program.transcode_profile || 'standard') + setHomepageVisible(program.homepage_visible) + setRemoteControl(program.remote_control_enabled) + setStreamKey(program.stream_key ?? '') + setStreamStatus(program.status) + if (program.renditions?.length) { + setRenditions(program.renditions) + setRenditionsPinned(true) + } + }) + .catch(() => toast.error('无法载入节目信息')) + .finally(() => { + if (active) setLoadingData(false) + }) + return () => { + active = false + } + }, [isEdit, streamId]) + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!title.trim()) { @@ -45,31 +103,69 @@ export default function StreamForm() { return } setLoading(true) + const schedule = scheduledAt ? new Date(scheduledAt).toISOString() : null try { - const res = await createStream({ - title: title.trim(), - description: description || undefined, - cover_url: coverUrl || undefined, - scheduled_at: scheduledAt ? new Date(scheduledAt).toISOString() : undefined, - transcode_profile: transcodeProfile, - homepage_visible: homepageVisible, - remote_control_enabled: remoteControl, - renditions, - }) - setResult({ rtmp_url: res.rtmp_url, stream_key: res.stream_key }) - toast.success('直播已创建') + if (isEdit) { + await updateStream(streamId, { + title: title.trim(), + description: description.trim() || null, + cover_url: coverUrl.trim() || null, + scheduled_at: schedule, + transcode_profile: transcodeProfile, + homepage_visible: homepageVisible, + remote_control_enabled: remoteControl, + ...(renditionsPinned ? { renditions } : {}), + }) + toast.success('节目属性已更新') + navigate('/admin/streams') + } else { + const res = await createStream({ + title: title.trim(), + description: description.trim() || null, + cover_url: coverUrl.trim() || null, + scheduled_at: schedule, + transcode_profile: transcodeProfile, + homepage_visible: homepageVisible, + remote_control_enabled: remoteControl, + renditions, + }) + setResult({ rtmp_url: res.rtmp_url, stream_key: res.stream_key }) + toast.success('直播已创建') + } } catch (error) { const detail = axios.isAxiosError(error) ? error.response?.data?.detail : undefined - toast.error(typeof detail === 'string' ? detail : '创建失败,请稍后重试') + toast.error(typeof detail === 'string' ? detail : isEdit ? '保存失败,请稍后重试' : '创建失败,请稍后重试') } finally { setLoading(false) } } const updateRendition = (index: number, patch: Partial) => { + setRenditionsPinned(true) setRenditions((cur) => cur.map((r, i) => (i === index ? { ...r, ...patch } : r))) } + const removeRendition = (index: number) => { + setRenditionsPinned(true) + setRenditions((cur) => cur.filter((_, i) => i !== index)) + } + + const addRendition = () => { + setRenditionsPinned(true) + setRenditions((cur) => [ + ...cur, + { label: '480p', enabled: true, width: 854, height: 480, fps: 30, codec: 'libx264', bitrate: '1000k', crf: 23, preset: 'veryfast', audio_bitrate: '128k', keyframe_seconds: 2 }, + ]) + } + + if (loadingData) { + return ( +
+
+
+ ) + } + if (result) { return (
@@ -116,10 +212,45 @@ export default function StreamForm() { 返回列表 + {isEdit && ( + + +
+ +
{streamKey || '—'}
+
+
+ + +
+ {streamStatus && streamStatus !== 'ended' && ( +

回放与章节需在节目结束后配置

+ )} +
+
+ )} + - 创建节目 -

填写节目信息并预约播出,系统将生成推流码与 RTMP 地址

+ {isEdit ? '编辑节目' : '创建节目'} +

+ {isEdit ? '修改标题、简介、排期与转码参数,保存后立即生效' : '填写节目信息并预约播出,系统将生成推流码与 RTMP 地址'} +

@@ -150,7 +281,10 @@ export default function StreamForm() { 带宽节省 -

可直接使用预设,也可在下方逐档调整参数

+

+ 可直接使用预设,也可在下方逐档调整参数 + {isEdit && !renditionsPinned && ';当前沿用预设档位,修改任意一档后才会保存为自定义清晰度'} +

@@ -166,7 +300,7 @@ export default function StreamForm() { onChange={(e) => updateRendition(index, { label: e.target.value })} />
-
@@ -225,16 +359,7 @@ export default function StreamForm() {
))} - @@ -250,13 +375,13 @@ export default function StreamForm() {
-

仅在明确启用后允许创建限时控制会话

+

仅直播期间生效,回放观众不参与审计与控制

diff --git a/frontend/src/admin/pages/StreamList.tsx b/frontend/src/admin/pages/StreamList.tsx index b62d53f..7a07837 100644 --- a/frontend/src/admin/pages/StreamList.tsx +++ b/frontend/src/admin/pages/StreamList.tsx @@ -1,6 +1,6 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' -import { Plus, Play, Square, Trash2, Link, Eye, Pencil } from 'lucide-react' +import { Plus, Play, Square, Trash2, Link, Eye, Pencil, Clapperboard } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' @@ -152,9 +152,12 @@ export default function StreamList() { - +