From b4fcbd38ba3ceedf6414bc71f365fc34e8a2db59 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 22 Oct 2026 20:23:33 +0800 Subject: [PATCH] chore: brand icon and title by default --- DEPLOYMENT.md | 357 +++++++++----- backend/routes/streams.py | 50 ++ backend/services/stream_service.py | 13 + backend/tests/test_access_and_sessions.py | 1 + backend/tests/test_live_only_audit.py | 137 ++++++ frontend/index.html | 3 +- frontend/public/favicon.ico | Bin 0 -> 9423 bytes frontend/public/favicon.svg | 1 - frontend/public/icons.svg | 24 - frontend/src/App.tsx | 3 +- frontend/src/admin/pages/LiveBoard.tsx | 23 +- frontend/src/admin/pages/ReplayEditor.tsx | 16 +- frontend/src/admin/pages/StreamForm.tsx | 191 ++++++-- frontend/src/admin/pages/StreamList.tsx | 7 +- frontend/src/api/streams.ts | 28 +- frontend/src/viewer/pages/WatchPage.tsx | 45 +- scripts/streamcore-service.ps1 | 568 ++++++++++++++++++++++ 17 files changed, 1254 insertions(+), 213 deletions(-) create mode 100644 backend/tests/test_live_only_audit.py create mode 100644 frontend/public/favicon.ico delete mode 100644 frontend/public/favicon.svg delete mode 100644 frontend/public/icons.svg create mode 100644 scripts/streamcore-service.ps1 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 0000000000000000000000000000000000000000..ee3740f0b921e77c063d8e04996f42dc6d4fd146 GIT binary patch literal 9423 zcmdVAhgTEZ7dD(wrHKuYCMq>juS)MCLPC`grGr!h3B4l_#NL3=q@yMvp|{W>TtrZ+ zp#>t4s~`plL4;63;LY#*{)zXUnYCul%voz@&N=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%OHnYBWYouCD?oMt8TC7?I~fjhCv?v1oQd^!9#wJt zoMRU*)fCNRe_=`ex~c^^qsiY~=oh=DK>2^Q0H-$*lrBOH6ryeeYJO*}1pr}XQ39ys zOXWPCgQ+qN6O%LSEU}XdlFJH2<2fufSn5sJ2>>RgVeB|tfV&_4M_IZaG0$nQAzl-v zc)Rqbf!12G=nL)tI@p=jcW~z?*eQO%MeMd1p`g#+QD(*aoml3gWiD_Ae1Hw_>b>pm z^O$Cl;UmD{D&{{N3CXUgtf2wWSeoa=Ix!oFd zskPD$%klO(tz7qRdEC`HL)~}gE4;Mxo&H1+YtsD?y1b~&l%g+v@m$k~)=bS9vd+#D z@a>g}D|@(&q`@x=@y&EO#W*hA#64LjuPoD8vCT^q6>!0b<-hg$htk7`9{v)bOUG*S z)X9#agy)6deVb?0gc%pxeuEWd9-(-@W*xozp@iNjnuZ@;Eb{h*fBa|Ca8et>UwXV-4< zMd^-fTbI)G-w3(HIR+L6v$>uacgk87UztS|1!2vgkYg%{U3cIGp{}#b3P9LrJcze% zf!4ZsWipd9M2>8Vw^!qu<3|*9iuSx*PmE=&+t9NrjpKaWb*MU4EZHKXl3@fSHGQeF zz=!ZAaXsMG@g&Z8zg|?k0aVc_ytc9K6wWPmbF{jLiFvSH^t$FQhbOT6GBsi8BIfh! zkG<`WIGjq)nb%#?O=FD`CQyl}u9PAR5qEfkd>p}(=TJM8FOIP2jyuDxs&I~Q`4i*U zsJV8`MGFQ}2w_^o-*h@C7k?%$jpY&kiBgRZQ3wcX2e#JWa2<+DN&mOj$h>@d%>A)t Wk?3nUgkskg0l? \ 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() { - +