Add timeslot exclude list so manual Douyin lives are not auto-selected.

Prevents time-slot relay and schedule auto-fill from colliding with URLs already used for manual/featured pushes; UI sits beside full-channel fill.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-05 22:50:25 -05:00
parent fa403d7b6a
commit c06e2b1385
5 changed files with 1379 additions and 195 deletions

View File

@ -163,6 +163,12 @@ async def lifespan(_: FastAPI):
asyncio.create_task(backup_loop())
asyncio.create_task(alert_loop())
try:
from . import ops_neko_sync
asyncio.create_task(ops_neko_sync.edge_sync_loop(interval_sec=5.0))
except Exception:
pass
asyncio.create_task(_ops_background_loops())
@ -2986,6 +2992,7 @@ async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
stream_key=body.stream_key,
note=body.note,
enabled=body.enabled,
category=body.category,
)
neko_sync = g.pop("neko_sync", None) if isinstance(g, dict) else None
return {"ok": True, "group": g, "neko_sync": neko_sync}
@ -3163,6 +3170,28 @@ async def youtube_studio_ingest(body: dict[str, Any] | None = None) -> dict[str,
return await asyncio.to_thread(youtube_neko.ingest_studio_telemetry, body or {})
@app.get("/api/youtube/studio/samples")
async def youtube_studio_samples(
group_id: str = "",
youtube_channel_id: str = "",
source_room_id: str = "",
neko_ref: str = "",
limit: int = 200,
) -> dict[str, Any]:
"""Analytics: Douyin room ↔ YouTube channel ↔ Studio viewer samples."""
from . import yt_studio_db
rows = await asyncio.to_thread(
yt_studio_db.list_samples,
group_id=group_id,
youtube_channel_id=youtube_channel_id,
source_room_id=source_room_id,
neko_ref=neko_ref,
limit=limit,
)
return {"ok": True, "count": len(rows), "samples": rows}
@app.post("/api/youtube/neko/instances/{instance_id}/{action}")
async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
try:
@ -3228,6 +3257,29 @@ async def youtube_assign_neko_open_prefer(group_id: str, body: dict[str, Any] =
return {"ok": True, "group": g}
@app.post("/api/youtube/assign/groups/{group_id}/ops-neko-bind")
async def youtube_assign_ops_neko_bind(group_id: str, body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
"""Hub UI: bind assign group to a physical ops-neko from the edge catalog (or clear)."""
open_url = str((body or {}).get("open_url") or "").strip()
slot = int((body or {}).get("slot") or 0)
edge_label = str((body or {}).get("edge_label") or "").strip()
prefer = str((body or {}).get("prefer") or "").strip().lower()
g = await asyncio.to_thread(
yt_assign_db.set_ops_neko_bind,
group_id,
open_url=open_url,
slot=slot,
edge_label=edge_label,
)
if not g:
raise HTTPException(404, "分组不存在")
if prefer in {"local", "remote"}:
g = await asyncio.to_thread(yt_assign_db.set_neko_open_prefer, group_id, prefer)
elif open_url:
g = await asyncio.to_thread(yt_assign_db.set_neko_open_prefer, group_id, "remote")
return {"ok": True, "group": g}
@app.delete("/api/youtube/assign/groups/{group_id}")
async def yt_assign_delete_group(group_id: str) -> dict[str, Any]:
return yt_assign_db.delete_group(group_id)
@ -3380,6 +3432,37 @@ async def yt_assign_auto_fill_all(body: YtAssignAutoFillBody | None = None) -> d
raise HTTPException(400, str(exc)) from exc
@app.get("/api/youtube/assign/timeslot-exclude")
async def yt_assign_timeslot_exclude_get() -> dict[str, Any]:
"""URLs time_slot must not use (manual-live collision guard — not a blacklist)."""
return await asyncio.to_thread(yt_assign_db.timeslot_exclude_status)
@app.post("/api/youtube/assign/timeslot-exclude")
async def yt_assign_timeslot_exclude_set(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
"""Replace exclude list from pasted text (multiline / comma / pool-line; deduped)."""
text = str((body or {}).get("text") or "")
return await asyncio.to_thread(yt_assign_db.set_timeslot_exclude_text, text)
@app.post("/api/youtube/assign/timeslot-exclude/preview")
async def yt_assign_timeslot_exclude_preview(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
"""Parse+dedupe without saving — for UI preview."""
text = str((body or {}).get("text") or "")
return await asyncio.to_thread(yt_assign_db.parse_timeslot_exclude_text, text)
@app.post("/api/youtube/assign/timeslot-exclude/import-manual")
async def yt_assign_timeslot_exclude_import_manual(
body: dict[str, Any] = Body(default={}),
) -> dict[str, Any]:
"""Import 普通分类精选 URLs into the exclude list."""
merge = True if (body or {}).get("merge") is None else bool((body or {}).get("merge"))
return await asyncio.to_thread(
lambda: yt_assign_db.import_timeslot_exclude_from_manual(merge=merge)
)
@app.get("/api/youtube/resolve")
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
try:
@ -3670,12 +3753,14 @@ async def ops_neko_overview() -> dict[str, Any]:
from . import host_profile
from . import ops_neko
from . import ops_neko_db
from . import ops_neko_sync
return {
"ok": True,
"peer": await asyncio.to_thread(ops_neko_db.peer_status),
"host_profile": await asyncio.to_thread(host_profile.status),
"instances": await asyncio.to_thread(ops_neko.list_enriched),
"sync": await asyncio.to_thread(ops_neko_sync.status),
"isolation": {
"assign_prefix": "douyinweb-neko-",
"ops_prefix": "douyinweb-ops-neko-",
@ -3770,6 +3855,172 @@ async def ops_neko_peer_set(body: dict[str, Any] = Body(default={})) -> dict[str
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/ops/neko/hub/credentials")
async def ops_neko_hub_credentials() -> dict[str, Any]:
"""VPS assign page: domain + token for physical pairing (auto-ensure hub)."""
from . import ops_neko_db
return await asyncio.to_thread(lambda: ops_neko_db.ensure_hub_credentials(rotate=False))
@app.post("/api/ops/neko/hub/credentials")
async def ops_neko_hub_credentials_set(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
from . import ops_neko_db
rotate = bool((body or {}).get("rotate_token"))
return await asyncio.to_thread(lambda: ops_neko_db.ensure_hub_credentials(rotate=rotate))
@app.post("/api/ops/neko/hub/catalog")
async def ops_neko_hub_catalog(request: Request, body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
"""Physical edge pushes ops-neko instance list for VPS dropdown."""
from . import ops_neko_db
token = (
request.headers.get("X-Ops-Neko-Token")
or request.headers.get("x-ops-neko-token")
or ""
).strip()
if not await asyncio.to_thread(ops_neko_db.verify_peer_token, token):
raise HTTPException(status_code=401, detail="invalid ops neko peer token")
items = list((body or {}).get("instances") or [])
rows = await asyncio.to_thread(
ops_neko_db.upsert_edge_catalog,
items,
edge_id=str((body or {}).get("edge_id") or ""),
edge_label=str((body or {}).get("edge_label") or ""),
)
# Mirror Studio telemetry so VPS assign UI can chart remote Nekos.
mirrored = 0
assign_mirrored = 0
try:
from . import youtube_neko
for it in items:
slot = int(it.get("slot") or 0)
studio = it.get("studio") if isinstance(it.get("studio"), dict) else None
if slot < 1 or not studio:
continue
r = await asyncio.to_thread(youtube_neko.ingest_remote_studio_mirror, slot, studio)
if r.get("ok"):
mirrored += 1
except Exception:
mirrored = 0
# Edge assign on_air → hub yt_studio_samples (dual-deploy live-map parity).
try:
from . import yt_assign_db
from . import yt_studio_db
lives = list((body or {}).get("assign_lives") or [])
groups = await asyncio.to_thread(lambda: yt_assign_db.list_groups(include_urls=False))
by_cid = {
str(g.get("youtube_channel_id") or "").strip(): g
for g in groups
if str(g.get("youtube_channel_id") or "").strip()
}
by_gid = {str(g.get("id") or "").strip(): g for g in groups if str(g.get("id") or "").strip()}
def _ingest_one(al: dict[str, Any]) -> bool:
if not isinstance(al, dict) or not al.get("on_air"):
return False
cid = str(al.get("youtube_channel_id") or "").strip()
gid = str(al.get("group_id") or "").strip()
g = by_gid.get(gid) or by_cid.get(cid)
if not g:
return False
hub_gid = str(g.get("id") or "")
# Dedupe: skip if a fresh on_air sample already exists for this group.
try:
import time as _time
recent = yt_studio_db.list_samples(
group_id=hub_gid, since_ts=_time.time() - 90.0, limit=3
)
if any(bool(s.get("on_air")) for s in recent):
return True
except Exception:
pass
yt_studio_db.insert_sample(
ts=float(al.get("ts") or 0) or None,
group_id=str(g.get("id") or ""),
channel_pk=str(g.get("channel_pk") or al.get("channel_pk") or ""),
youtube_channel_id=cid or str(g.get("youtube_channel_id") or ""),
neko_kind="edge",
neko_ref=str(al.get("neko_ref") or "edge:assign")[:64],
live_page_open=True,
on_air=True,
live_status=str(al.get("live_status") or "live")[:32],
health=str(al.get("health") or "")[:32],
viewer_count=al.get("viewer_count"),
studio_url=str(al.get("studio_url") or "")[:200],
detect_source="edge_assign_live",
stream_title=str(al.get("name") or g.get("name") or "")[:120],
)
return True
for al in lives:
if await asyncio.to_thread(_ingest_one, al):
assign_mirrored += 1
except Exception:
assign_mirrored = 0
return {
"ok": True,
"count": len(rows),
"catalog": rows,
"studio_mirrored": mirrored,
"assign_lives_mirrored": assign_mirrored,
}
@app.get("/api/ops/neko/remote-catalog")
async def ops_neko_remote_catalog() -> dict[str, Any]:
"""Hub UI: physical ops-neko instances available to bind on assign page."""
from . import ops_neko_db
rows = await asyncio.to_thread(ops_neko_db.list_edge_catalog)
return {"ok": True, "instances": rows}
@app.post("/api/ops/neko/pair")
async def ops_neko_pair(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
"""Physical Neko tab: paste VPS domain + token → edge pair + catalog sync."""
from . import ops_neko
return await asyncio.to_thread(
ops_neko.pair_as_edge,
hub_base=str((body or {}).get("hub_base") or (body or {}).get("peer_base_url") or ""),
token=str((body or {}).get("token") or ""),
public_base=str((body or {}).get("public_base") or ""),
)
@app.post("/api/ops/neko/push-catalog")
async def ops_neko_push_catalog() -> dict[str, Any]:
from . import ops_neko
from . import ops_neko_sync
out = await asyncio.to_thread(ops_neko.push_catalog_to_hub)
ops_neko_sync.kick()
return out
@app.get("/api/ops/neko/sync-status")
async def ops_neko_sync_status() -> dict[str, Any]:
from . import ops_neko_sync
return await asyncio.to_thread(ops_neko_sync.status)
@app.post("/api/ops/neko/sync-now")
async def ops_neko_sync_now() -> dict[str, Any]:
"""Immediate edge→hub heartbeat (also wakes the realtime loop)."""
from . import ops_neko_sync
out = await asyncio.to_thread(ops_neko_sync.sync_once)
ops_neko_sync.kick()
return out
@app.get("/api/ops/neko/hub/assign-cards")
async def ops_neko_hub_assign_cards(request: Request) -> dict[str, Any]:
"""Token-auth export of YouTube 分配 cards for physical edge binding."""
@ -3814,6 +4065,9 @@ async def ops_neko_hub_bind(request: Request, body: dict[str, Any] = Body(defaul
)
if not row:
raise HTTPException(status_code=404, detail="assign group not found")
# Match Hub UI bind: bound remote desktop ⇒ prefer remote for open/gate.
if open_url:
row = await asyncio.to_thread(yt_assign_db.set_neko_open_prefer, gid, "remote") or row
return {"ok": True, "group": row}

View File

@ -39,6 +39,11 @@ def _time_slot_mode(cfg: dict[str, Any] | None = None) -> bool:
return bool(cfg.get("youtube_relay_time_slot_mode"))
def _group_uses_time_slot(group: dict[str, Any]) -> bool:
"""Per-group category: time_slot → schedule/live sources; normal → manual/featured."""
return yt_assign_db.group_is_time_slot(group)
def _group_in_active_slot(group_id: str, *, keyed_only: bool = False) -> bool:
return yt_assign_db.group_in_rotation_slot(group_id, keyed_only=keyed_only)
@ -50,24 +55,34 @@ def pick_source_for_group(
time_slot_mode: bool | None = None,
prefer_room_id: str = "",
prefer_source_url: str = "",
exclude_room_ids: set[str] | frozenset[str] | None = None,
) -> dict[str, str] | None:
"""Choose Douyin source.
- 时间段模式: only when group is in active 24/N slot; source = currently-live monitor rooms.
- 普通模式: featured list (prefer live), optionally gated by schedule.
- 时间段分类: only when group is in active 24/N slot; source = currently-live monitor rooms.
- 普通分类: featured list (prefer live), optionally gated by schedule.
``time_slot_mode`` kept for API compatibility; per-group ``category`` is authoritative.
``exclude_room_ids`` skips rooms already probed offline this tick (time_slot sticky-lag).
"""
gid = str(group.get("id") or "")
if not gid or not group.get("enabled"):
return None
cfg = db.get_settings_map()
slot_mode = bool(cfg.get("youtube_relay_time_slot_mode")) if time_slot_mode is None else bool(time_slot_mode)
slot_mode = _group_uses_time_slot(group)
_ = time_slot_mode # call-site compat; category is authoritative
exclude = {str(x).strip() for x in (exclude_room_ids or ()) if str(x or "").strip()}
if slot_mode:
if respect_schedule and not _group_in_active_slot(gid, keyed_only=True):
return None
rooms = db.list_live_douyin_rooms_for_shorts(limit=40)
prefer_rid = str(prefer_room_id or "").strip()
prefer_url = str(prefer_source_url or "").strip()
_ = str(prefer_source_url or "").strip() # kept for call-site compat; rid is authoritative
try:
manual_block = yt_assign_db.timeslot_exclude_room_ids(include_manual_featured=True)
except Exception:
manual_block = set()
exclude = set(exclude) | set(manual_block)
def _row_to_src(row: dict[str, Any]) -> dict[str, str]:
url = str(row.get("url") or "").strip()
@ -78,7 +93,9 @@ def pick_source_for_group(
"anchor_name": str(row.get("last_anchor") or row.get("last_title") or rid).strip(),
}
if prefer_rid:
# Sticky prefer only while that room is still in the live list AND not excluded
# (exclude = probe just said offline — monitor list can lag behind Douyin status=4).
if prefer_rid and prefer_rid not in exclude:
for row in rooms:
if str(row.get("room_id") or "").strip() == prefer_rid:
return _row_to_src(row)
@ -87,7 +104,7 @@ def pick_source_for_group(
for row in rooms:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
if not url or not rid:
if not url or not rid or rid in exclude:
continue
return _row_to_src(row)
return None
@ -188,7 +205,7 @@ class YoutubeRelayPipeline:
pipeline_enabled=pipeline_enabled or gid in self._manual_hold,
log_age_seconds=log_age_seconds(st, now),
lane_armed=gid in self._manual_hold or pipeline_enabled,
time_slot_mode=_time_slot_mode(cfg),
time_slot_mode=_group_uses_time_slot(g),
)
receiving = bool(monitor.get("is_pushing"))
if monitor.get("is_pushing"):
@ -237,37 +254,52 @@ class YoutubeRelayPipeline:
)
neko_id = int(g.get("neko_instance_id") or 0)
raw_neko = neko_by_id.get(neko_id) if neko_id > 0 else None
neko_state = None
if isinstance(raw_neko, dict):
neko_state = {
"id": raw_neko.get("id"),
"running": bool(raw_neko.get("running")),
"ready": bool(raw_neko.get("ready")),
"status": raw_neko.get("status"),
"studio_url": raw_neko.get("studio_url"),
"exists": bool(raw_neko.get("exists")),
prefer = str(g.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(g.get("ops_neko_open_url") or "").strip())
neko_state: dict[str, Any] | None = {
"id": neko_id if neko_id > 0 else None,
"running": bool(raw_neko.get("running")) if isinstance(raw_neko, dict) else False,
"ready": bool(raw_neko.get("ready")) if isinstance(raw_neko, dict) else False,
"status": (raw_neko.get("status") if isinstance(raw_neko, dict) else None) or (
"remote" if prefer == "remote" and remote_bound else "stopped"
),
"studio_url": (
str(g.get("neko_open_url") or "")
or (raw_neko.get("studio_url") if isinstance(raw_neko, dict) else "")
or ""
),
"exists": bool(raw_neko.get("exists")) if isinstance(raw_neko, dict) else remote_bound,
"open_prefer": prefer,
"remote_bound": remote_bound,
"ops_neko_slot": int(g.get("ops_neko_slot") or 0),
}
try:
snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=120.0)
neko_state["studio"] = {
"live_page_open": bool(snap.get("live_page_open")),
"on_air": bool(snap.get("on_air")),
"live_status": snap.get("live_status") or "",
"health": snap.get("health") or "",
"viewer_count": snap.get("viewer_count"),
"like_count": snap.get("like_count"),
"total_views": snap.get("total_views"),
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"stream_title": snap.get("stream_title") or "",
"url": snap.get("url") or "",
"received_at": snap.get("received_at") or 0,
"age_sec": snap.get("age_sec"),
"detect_source": snap.get("detect_source") or "",
"minute_reports": snap.get("minute_reports") or [],
"neko_ref": snap.get("neko_ref") or "",
"neko_kind": snap.get("neko_kind") or "",
"ui_source": snap.get("ui_source") or "",
}
try:
snap = youtube_neko.studio_on_air_lookup(neko_id, max_age_sec=120.0)
neko_state["studio"] = {
"live_page_open": bool(snap.get("live_page_open")),
"on_air": bool(snap.get("on_air")),
"live_status": snap.get("live_status") or "",
"health": snap.get("health") or "",
"viewer_count": snap.get("viewer_count"),
"like_count": snap.get("like_count"),
"total_views": snap.get("total_views"),
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"stream_title": snap.get("stream_title") or "",
"url": snap.get("url") or "",
"received_at": snap.get("received_at") or 0,
"age_sec": snap.get("age_sec"),
"detect_source": snap.get("detect_source") or "",
"minute_reports": snap.get("minute_reports") or [],
}
except Exception:
neko_state["studio"] = None
except Exception:
neko_state["studio"] = None
# If neither local container nor remote bind, drop empty neko block.
if not neko_id and not remote_bound:
neko_state = None
# Trim log text for poll JSON (selected card still has enough to read).
rl = monitor.get("recent_log")
if isinstance(rl, str) and len(rl) > 3500:
@ -299,11 +331,11 @@ class YoutubeRelayPipeline:
**monitor,
}
relay_groups.append(row)
# Light schedule — keyed-only when 时间段模式.
# Light schedule — keyed-only when any 时间段 groups (or legacy global toggle).
schedule = yt_assign_db.build_rotation_schedule(
include_urls=False,
groups=groups,
keyed_only=_time_slot_mode(cfg),
keyed_only=None,
)
preset_id = str(cfg.get("youtube_relay_quality_preset") or "720p")
encoding = resolve_relay_encoding(cfg)
@ -336,6 +368,7 @@ class YoutubeRelayPipeline:
"youtube_relay_quality_presets": list_relay_quality_presets(active_id=preset_id),
"youtube_relay_exclusive_live": bool(cfg.get("youtube_relay_exclusive_live", True)),
"youtube_relay_time_slot_mode": bool(cfg.get("youtube_relay_time_slot_mode")),
"youtube_relay_timeslot_exclude_count": 0,
},
"groups": relay_groups,
"schedule": schedule,
@ -343,6 +376,12 @@ class YoutubeRelayPipeline:
"neko_paused_instances": sorted(self._neko_paused_instances),
"studio_live": None,
}
try:
payload["settings"]["youtube_relay_timeslot_exclude_count"] = len(
yt_assign_db.timeslot_exclude_room_ids(include_manual_featured=True)
)
except Exception:
pass
try:
from . import youtube_neko
@ -396,9 +435,10 @@ class YoutubeRelayPipeline:
raise ValueError("该组已停用")
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
raise ValueError("请先配置 YouTube 直播 KEY")
# 时间段模式: sources come from currently-live monitor rooms (not 精选).
# 普通模式: still require 精选 list.
if not _time_slot_mode():
# 时间段分类: sources come from currently-live monitor rooms (not 精选).
# 普通分类: still require 精选 list; manual Start ignores schedule.
group_slot = _group_uses_time_slot(g)
if not group_slot:
featured = [
x
for x in (g.get("featured") or [])
@ -411,9 +451,9 @@ class YoutubeRelayPipeline:
# Exclusive FFmpeg/Neko lock applies only when push actually starts (see _ensure_group_relay).
await self.start()
self._manual_hold.add(gid)
# Time-slot: keep schedule gate so only the active slot winner pushes.
# Normal mode: manual Start ignores schedule window (force lane).
respect = True if _time_slot_mode() else False
# 时间段: keep schedule gate so only the active slot winner pushes.
# 普通: manual Start ignores schedule window (force lane).
respect = True if group_slot else False
result = await self._ensure_group_relay(g, force=True, respect_schedule=respect)
# Fatal = missing key / empty source only. Offline/risk → waiting, hold stays.
if result.get("fatal"):
@ -479,9 +519,6 @@ class YoutubeRelayPipeline:
try:
cfg = db.get_settings_map()
auto_on = bool(cfg.get("youtube_relay_enabled"))
slot_mode = _time_slot_mode(cfg)
# 时间段模式始终尊重 24/N 轮播;普通模式可读原开关。
respect = True if slot_mode else bool(cfg.get("youtube_relay_respect_schedule", True))
groups = yt_assign_db.list_groups(include_urls=True)
by_id = {str(g.get("id") or ""): g for g in groups}
active_ids: set[str] = set()
@ -496,18 +533,21 @@ class YoutubeRelayPipeline:
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
active_ids.add(gid)
# Manual hold: 普通 ignore schedule; 时间段 still respects window.
hold_respect = True if _group_uses_time_slot(g) else False
await self._ensure_group_relay(
g, force=False, respect_schedule=False, cfg=cfg
g, force=False, respect_schedule=hold_respect, cfg=cfg
)
# 2) Auto relay: same poll for enabled groups (schedule optional).
# 2) Auto relay: 时间段 groups via 24/N; 普通 = 手动 only (skip auto).
if auto_on:
from . import youtube_neko
# Time-slot: identify current winner once per tick (one group per YouTube channel).
slot_winner_gid = ""
slot_winner_g: dict[str, Any] | None = None
if slot_mode and respect:
time_slot_groups = [g for g in groups if _group_uses_time_slot(g)]
run_slot_auto = bool(time_slot_groups)
if run_slot_auto:
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
active_ch = next((c for c in sched.get("channels") or [] if c.get("active")), None)
if active_ch:
@ -532,8 +572,11 @@ class YoutubeRelayPipeline:
continue
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
# 时间段模式:非当前时段 → 停推流;仅在「单频道独占」时顺带停 Neko(物理机可常驻预热)。
if slot_mode and respect and gid != slot_winner_gid:
# 普通分类:仅手动推流,不走自动排班。
if not _group_uses_time_slot(g):
continue
# 时间段:非当前时段 → 停推流;仅在「单频道独占」时顺带停 Neko。
if run_slot_auto and gid != slot_winner_gid:
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
same_channel_as_winner = bool(
slot_winner_g and yt_assign_db.same_yt_channel(g, slot_winner_g)
@ -568,8 +611,7 @@ class YoutubeRelayPipeline:
continue
src = pick_source_for_group(
g,
respect_schedule=respect,
time_slot_mode=slot_mode,
respect_schedule=True,
prefer_room_id=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_room_id") or ""),
prefer_source_url=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_url") or ""),
)
@ -579,22 +621,21 @@ class YoutubeRelayPipeline:
active_ids.add(gid)
continue
# Outside schedule / empty list — idle, do not kill manual holds.
if slot_mode and gid in self._sessions and gid not in self._manual_hold:
if gid in self._sessions and gid not in self._manual_hold:
await self._halt_session(gid, reason="no_live_source")
if slot_mode:
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="时间段模式:等待在播抖音源",
recent_log=["[relay] waiting live Douyin source"],
)
# Keep winner Neko warm while waiting for a live room.
if slot_winner_g and gid == slot_winner_gid:
await self._enforce_exclusive_live(gid, slot_winner_g)
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="时间段模式:等待在播抖音源",
recent_log=["[relay] waiting live Douyin source"],
)
# Keep winner Neko warm while waiting for a live room.
if slot_winner_g and gid == slot_winner_gid:
await self._enforce_exclusive_live(gid, slot_winner_g)
continue
active_ids.add(gid)
await self._ensure_group_relay(
g, source=src, cfg=cfg, respect_schedule=respect
g, source=src, cfg=cfg, respect_schedule=True
)
else:
# Auto off: stop non-manual ffmpeg sessions only.
@ -665,7 +706,10 @@ class YoutubeRelayPipeline:
paused = await asyncio.to_thread(youtube_neko.stop_instances_except, winner_neko)
self._neko_paused_instances |= set(paused)
if winner_neko > 0:
prefer = str(winner_group.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(winner_group.get("ops_neko_open_url") or "").strip())
# Prefer remote ops-neko: do not force-start local assign Neko.
if winner_neko > 0 and not (prefer == "remote" and remote_bound):
await asyncio.to_thread(youtube_neko.ensure_instance_running, winner_neko)
async def _release_exclusive_live(self) -> None:
@ -723,10 +767,10 @@ class YoutubeRelayPipeline:
cfg = cfg or db.get_settings_map()
encoding = resolve_relay_encoding(cfg)
gid = str(group.get("id") or "")
slot_mode = _time_slot_mode(cfg)
slot_mode = _group_uses_time_slot(group)
if respect_schedule is None:
respect_schedule = True if slot_mode else bool(cfg.get("youtube_relay_respect_schedule", True))
if force:
if force and not slot_mode:
respect_schedule = False
relay_st = youtube_relay_db.get_relay_state(gid) or {}
@ -745,7 +789,6 @@ class YoutubeRelayPipeline:
src = source or pick_source_for_group(
group,
respect_schedule=respect_schedule,
time_slot_mode=slot_mode,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
@ -754,7 +797,6 @@ class YoutubeRelayPipeline:
any_src = pick_source_for_group(
group,
respect_schedule=False,
time_slot_mode=slot_mode,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
@ -867,6 +909,75 @@ class YoutubeRelayPipeline:
)
# sh2 youtube.py L1213-1229: is_live False → print 等待直播 + continue (never exit lane).
# Time-slot: monitor「进行中场次」can lag; sticky prefer must not glue forever onto status=4.
if not cands and slot_mode:
live_sess = self._sessions.get(gid)
if live_sess and live_sess.stats.running:
return {
"ok": True,
"group_id": gid,
"reused": True,
"ffmpeg_pid": int(live_sess.stats.pid or 0),
"note": "probe_miss_keep_ffmpeg",
}
exclude: set[str] = set()
failed_rid = str(src.get("room_id") or "").strip()
if failed_rid:
exclude.add(failed_rid)
boot_log.append(
f"[relay] room offline/probe-miss rid={failed_rid or '-'} "
f"status={probe.get('status_code')} → rotate live list"
)
for _ in range(8):
alt = pick_source_for_group(
group,
respect_schedule=respect_schedule,
prefer_room_id="",
prefer_source_url="",
exclude_room_ids=exclude,
)
if not alt:
break
alt_rid = str(alt.get("room_id") or "").strip()
if not alt_rid or alt_rid in exclude:
break
boot_log.append(
f"[relay] switch source {failed_rid or '-'} → {alt_rid} "
f"({alt.get('anchor_name') or '-'})"
)
src = alt
if probe.get("anchor_name") and not src.get("anchor_name"):
pass
probe = await check_room(src["source_url"], cookie=cookie)
if probe.get("anchor_name"):
src["anchor_name"] = str(probe.get("anchor_name") or src.get("anchor_name") or "")
boot_log.append(
f"[relay] probe ok={probe.get('ok')} live={probe.get('is_live')} "
f"status={probe.get('status_code')} risk={bool(probe.get('risk'))}"
)
cands = []
if probe.get("ok") and probe.get("is_live"):
raw_cands = probe.get("stream_candidates") or []
if isinstance(raw_cands, list):
cands = [
str(x).strip()
for x in raw_cands
if str(x or "").strip().startswith("http")
]
fresh = str(probe.get("stream_url") or "").strip()
if fresh.startswith("http") and fresh not in cands:
cands.insert(0, fresh)
if not cands and probe.get("ok") and probe.get("is_live"):
cands = await resolve_stream_candidates(
source_url=src["source_url"],
cookie=cookie,
prefer_fresh=True,
)
if cands:
break
exclude.add(alt_rid)
failed_rid = alt_rid
if not cands:
live_sess = self._sessions.get(gid)
if live_sess and live_sess.stats.running:
@ -943,32 +1054,40 @@ class YoutubeRelayPipeline:
await self._enforce_exclusive_live(gid, group)
# Exclusive: wait for Studio Live before FFmpeg. Without exclusive, only wait if this group's Neko is enabled.
# Studio Live gate: prefer remote ops-neko when bound; else local assign Neko.
from . import youtube_neko
prefer = str(group.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(group.get("ops_neko_open_url") or "").strip())
ops_slot = int(group.get("ops_neko_slot") or 0)
neko_id = int(group.get("neko_instance_id") or 0)
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
neko_gate = exclusive_on or bool(group.get("neko_enabled"))
if neko_id > 0 and neko_gate:
from . import youtube_neko
use_remote = prefer == "remote" and remote_bound and ops_slot > 0
neko_gate = use_remote or exclusive_on or bool(group.get("neko_enabled")) or (
neko_id > 0 and bool(group.get("neko_enabled"))
)
if neko_gate and (use_remote or neko_id > 0):
target = f"远程 Ops Neko #{ops_slot}" if use_remote else f"本机 Neko #{neko_id}"
boot_log.append(
f"[relay] waiting neko-{neko_id} YouTube Live 控制页就绪"
f"(须新遥测 + 稳定 ≥25s,禁止抢跑)…"
f"[relay] waiting {target} YouTube Live 控制页就绪"
f"(须新遥测 + 稳定 ≥20s,禁止抢跑)…"
)
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
error="等待 Neko 打开 YouTube Live 控制页…",
error=f"等待 {target} 打开 YouTube Live 控制页…",
recent_log=boot_log[-40:],
)
neko_wait = await asyncio.to_thread(
youtube_neko.wait_instance_ready_for_live,
neko_id,
youtube_neko.wait_group_ready_for_live,
group,
timeout_sec=120.0,
require_live_page=True,
settle_sec=20.0,
strict=True,
)
if not neko_wait.get("ok") or not neko_wait.get("live_studio"):
if not neko_wait.get("ok") or (
not neko_wait.get("skipped") and not neko_wait.get("live_studio")
):
err = str(
neko_wait.get("error")
or "YouTube Live 控制页未就绪,暂不推流(避免绿点无效 ingest)"
@ -981,13 +1100,17 @@ class YoutubeRelayPipeline:
recent_log=boot_log[-40:],
)
return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait}
boot_log.append(
f"[relay] neko Live 页就绪 src={neko_wait.get('detect_source') or 'telemetry'} "
f"settled={bool(neko_wait.get('settled'))} settle={neko_wait.get('settle_sec')}s "
f"live_status={neko_wait.get('live_status') or '-'} "
f"health={neko_wait.get('health') or '-'} "
f"url={(neko_wait.get('url') or '-')[:80]}"
)
if neko_wait.get("skipped"):
boot_log.append("[relay] neko Live 页检查跳过(无绑定)")
else:
boot_log.append(
f"[relay] neko Live 页就绪 kind={neko_wait.get('neko_kind') or '-'} "
f"src={neko_wait.get('detect_source') or 'telemetry'} "
f"settled={bool(neko_wait.get('settled'))} settle={neko_wait.get('settle_sec')}s "
f"live_status={neko_wait.get('live_status') or '-'} "
f"health={neko_wait.get('health') or '-'} "
f"url={(neko_wait.get('url') or '-')[:80]}"
)
sess = RelayPushSession(
group_id=gid,
@ -1039,17 +1162,95 @@ class YoutubeRelayPipeline:
async def _tick_stats(self) -> None:
now = time.time()
# After FFmpeg is up, Studio must leave NODATA/待开播 and become on_air.
# Green-dot loading without You're Live = invalid push — stop it.
try:
from . import youtube_neko as _yn
on_air_deadline = float(
(db.get_settings_map() or {}).get("youtube_relay_on_air_deadline_sec") or 90
)
except Exception:
_yn = None # type: ignore
on_air_deadline = 90.0
on_air_deadline = max(45.0, min(300.0, float(on_air_deadline)))
for gid, sess in list(self._sessions.items()):
if sess.stats.running:
st = youtube_relay_db.get_relay_state(gid) or {}
started = float(st.get("started_at") or now)
push_sec = max(0.0, now - started)
# Watchdog: fresh Studio telemetry still NODATA/待开播 after deadline → kill invalid ingest
if _yn is not None and push_sec >= on_air_deadline:
try:
group = yt_assign_db.get_group(gid) or {}
snap = _yn.studio_snapshot_for_group(group, max_age_sec=75.0)
age = snap.get("age_sec")
try:
fresh = age is not None and float(age) <= 75.0
except (TypeError, ValueError):
fresh = bool(snap.get("received_at"))
on_air = bool(snap.get("on_air"))
live_status = str(snap.get("live_status") or "").strip().lower()
page_open = bool(snap.get("live_page_open"))
# 待开播 only — never treat 断播(encoder_lost) as invalid-push kill.
pending = live_status in {"waiting", "ready", "signed_out", "offline"}
try:
payload_probe = {
"live_status": live_status,
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"text": "",
"signals": {
"nodata": live_status == "waiting",
"encoder_lost": live_status in {"encoder_lost", "stalled"},
"session_live": live_status in {"live", "encoder_lost", "stalled"},
"pending_go_live": pending,
},
}
if _yn._payload_encoder_lost(payload_probe) or live_status in {
"encoder_lost",
"stalled",
}:
pending = False
if not _yn._payload_nodata_or_pending(payload_probe):
pending = False
except Exception:
pass
# Only act on fresh evidence of 待开播 — never kill on 断播 / missing telemetry.
if fresh and page_open and (not on_air) and pending:
err = (
f"Studio 仍为 {live_status or '待开播/NODATA'}(未 on_air),"
f"推流已 {int(push_sec)}s — 判定无效推流,已自动停止"
)
boot = list(sess.stats.recent_log or [])
boot.append(f"[relay] {err}")
await asyncio.to_thread(sess.stop)
self._sessions.pop(gid, None)
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
ffmpeg_pid=0,
speed=0,
frame=0,
error=err,
recent_log=boot[-40:],
)
await asyncio.to_thread(
relay_sessions.end_session, gid, reason="studio_not_on_air"
)
# Drop manual hold so we don't immediately restart the same invalid push
self._manual_hold.discard(gid)
continue
except Exception:
pass
youtube_relay_db.upsert_relay_state(
gid,
status="pushing",
speed=float(sess.stats.speed),
frame=int(sess.stats.frame),
ffmpeg_pid=int(sess.stats.pid),
push_seconds=max(0.0, now - started),
push_seconds=push_sec,
recent_log=sess.stats.recent_log,
)
else:

View File

@ -105,6 +105,8 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
("ops_neko_bound_at", "REAL NOT NULL DEFAULT 0"),
# Which desktop the assign「打开」button prefers: local (native) | remote (ops-neko tab)
("neko_open_prefer", "TEXT NOT NULL DEFAULT 'local'"),
# Push category: normal (manual / featured) | time_slot (24/N schedule + live sources)
("category", "TEXT NOT NULL DEFAULT 'normal'"),
]:
if col not in gcols:
conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}")
@ -305,6 +307,26 @@ def _beijing_hour_fraction(ts: float | None = None) -> float:
return dt.hour + dt.minute / 60.0 + dt.second / 3600.0
ASSIGN_CATEGORIES = ("normal", "time_slot")
ASSIGN_CATEGORY_LABELS = {"normal": "普通", "time_slot": "时间段"}
def normalize_assign_category(value: Any) -> str:
"""Map UI/API values to stored category keys. Default / unknown → normal."""
raw = str(value or "").strip().lower()
if raw in {"time_slot", "timeslot", "time-slot", "slot", "时间段"}:
return "time_slot"
if raw in {"normal", "普通", "manual", "手动"}:
return "normal"
return "normal"
def group_is_time_slot(group: dict[str, Any] | None) -> bool:
if not group:
return False
return normalize_assign_category(group.get("category")) == "time_slot"
def _public_group(
row: dict[str, Any],
*,
@ -316,6 +338,8 @@ def _public_group(
out = dict(row)
out["enabled"] = bool(out.get("enabled"))
out["neko_enabled"] = bool(out.get("neko_enabled"))
out["category"] = normalize_assign_category(out.get("category"))
out["category_label"] = ASSIGN_CATEGORY_LABELS.get(out["category"], "普通")
neko_id = int(out.get("neko_instance_id") or 0)
out["neko_instance_id"] = neko_id
sk = str(out.get("stream_key") or "")
@ -574,6 +598,7 @@ def create_group(
stream_key: str = "",
note: str = "",
enabled: bool = True,
category: str = "normal",
) -> dict[str, Any]:
from . import db
@ -583,6 +608,7 @@ def create_group(
yt_id = str(youtube_channel_id or "").strip()
nm = str(name or "").strip()
stream_key = _sanitize_stream_key(stream_key)
cat = normalize_assign_category(category)
if ch_pk:
ch = db.get_shorts_channel(ch_pk)
if ch:
@ -631,9 +657,9 @@ def create_group(
"""
INSERT INTO yt_assign_groups(
id, name, channel_pk, youtube_channel_id, stream_key, note,
enabled, sort_order, neko_instance_id, neko_enabled,
enabled, sort_order, neko_instance_id, neko_enabled, category,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
gid,
@ -646,6 +672,7 @@ def create_group(
sort_order,
neko_instance_id,
0,
cat,
now,
now,
),
@ -702,6 +729,7 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
"enabled",
"sort_order",
"neko_enabled",
"category",
}
patch: dict[str, Any] = {}
for k, v in fields.items():
@ -711,6 +739,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
patch[k] = 1 if v else 0
elif k == "neko_enabled":
patch[k] = 1 if v else 0
elif k == "category":
patch[k] = normalize_assign_category(v)
elif k == "sort_order":
try:
patch[k] = int(v)
@ -1688,6 +1718,8 @@ def group_in_rotation_slot(group_id: str, *, keyed_only: bool | None = None) ->
keyed_only = False
if keyed_only and not _group_has_stream_key(g):
return False
if keyed_only and not group_is_time_slot(g):
return False
ch_key = _group_yt_channel_key(g)
sched = build_rotation_schedule(include_urls=False, keyed_only=keyed_only)
for c in sched.get("channels") or []:
@ -1724,12 +1756,15 @@ def build_rotation_schedule(
try:
from . import db as _db
keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode"))
# Prefer per-group 时间段 rows; fall back to legacy global toggle.
has_slot = any(group_is_time_slot(g) for g in raw if g.get("enabled"))
keyed_only = has_slot or bool(_db.get_settings_map().get("youtube_relay_time_slot_mode"))
except Exception:
keyed_only = False
enabled = [g for g in raw if g.get("enabled")]
if keyed_only:
keyed = [g for g in enabled if _group_has_stream_key(g)]
# 时间段排班:仅「时间段」分类 + 有 KEY 的频道参与 24/N
keyed = [g for g in enabled if _group_has_stream_key(g) and group_is_time_slot(g)]
rotation_rows = _dedupe_groups_by_yt_channel(keyed)
else:
rotation_rows = [(g, []) for g in enabled]
@ -1804,6 +1839,12 @@ def build_rotation_schedule(
def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: bool = False, force: bool = False) -> dict[str, Any]:
"""Fill slot lists from Douyin live + 24h session stats; round-robin across groups."""
ranked = _rank_douyin_rooms_for_relay(limit=max(8, min(int(limit), 80)))
try:
blocked = timeslot_exclude_room_ids(include_manual_featured=True)
except Exception:
blocked = set()
if blocked:
ranked = [r for r in ranked if str(r.get("room_id") or "").strip() not in blocked]
if not ranked:
return {"ok": True, "filled": 0, "skipped": "no_live_data", "schedule": build_rotation_schedule(include_urls=True)}
@ -1898,3 +1939,223 @@ def ensure_default_assign_data(*, force: bool = False) -> dict[str, Any]:
n = len(groups)
limit = max(12, min(48, n * 6))
return auto_fill_slots_from_live(all_groups=True, limit=limit, force=force)
TIMESLOT_EXCLUDE_SETTING_KEY = "youtube_relay_timeslot_exclude_urls"
def parse_timeslot_exclude_text(text: str) -> dict[str, Any]:
"""Parse pasted Douyin live URLs / room ids into a deduped exclude list.
Accepts multiline / comma-separated / pool-line formats. Not a blacklist —
only blocks time_slot auto sources so they don't collide with manual lives.
"""
items: list[dict[str, str]] = []
seen: set[str] = set()
skipped_dup = 0
skipped_invalid = 0
blob = str(text or "").strip().lstrip("\ufeff")
if not blob:
return {
"ok": True,
"items": [],
"count": 0,
"skipped_dup": 0,
"skipped_invalid": 0,
"text": "",
}
chunks: list[str] = []
for line in re.split(r"[\r\n]+", blob):
line = line.strip()
if not line:
continue
# Split comma-separated URLs on one line (keep 「主播: …」 with preceding url via parse_pool_line)
if re.search(r"https?://", line) and ("," in line or "," in line):
# Prefer whole-line parse first (url + 主播)
p0 = parse_pool_line(line)
if p0.get("url"):
chunks.append(line)
continue
for part in re.split(r"[,,\s]+", line):
part = part.strip()
if part:
chunks.append(part)
else:
chunks.append(line)
for raw in chunks:
p = parse_pool_line(raw)
url = str(p.get("url") or "").strip()
rid = str(p.get("room_id") or extract_room_id(raw) or "").strip()
if not url and rid:
url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}"
if not url and not rid:
skipped_invalid += 1
continue
if not rid:
rid = extract_room_id(url)
key = _dedupe_key(url, rid)
if key in seen:
skipped_dup += 1
continue
seen.add(key)
items.append(
{
"url": (normalize_room_url(url) or url)[:500],
"room_id": rid[:64],
"title": str(p.get("title") or "")[:120],
}
)
text_out = "\n".join(
f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "")
for it in items
)
return {
"ok": True,
"items": items,
"count": len(items),
"skipped_dup": skipped_dup,
"skipped_invalid": skipped_invalid,
"text": text_out,
}
def get_timeslot_exclude_items() -> list[dict[str, str]]:
from . import db
raw = db.get_settings_map().get(TIMESLOT_EXCLUDE_SETTING_KEY)
items: list[dict[str, str]] = []
if isinstance(raw, list):
for it in raw:
if isinstance(it, str):
p = parse_pool_line(it)
if p.get("url") or p.get("room_id"):
items.append(
{
"url": str(p.get("url") or "")[:500],
"room_id": str(p.get("room_id") or "")[:64],
"title": str(p.get("title") or "")[:120],
}
)
elif isinstance(it, dict):
url = str(it.get("url") or "").strip()
rid = str(it.get("room_id") or extract_room_id(url) or "").strip()
if not url and rid:
url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}"
if not url and not rid:
continue
items.append(
{
"url": (normalize_room_url(url) or url)[:500],
"room_id": rid[:64],
"title": str(it.get("title") or "")[:120],
}
)
elif isinstance(raw, str) and raw.strip():
items = list(parse_timeslot_exclude_text(raw).get("items") or [])
# Final dedupe
out: list[dict[str, str]] = []
seen: set[str] = set()
for it in items:
key = _dedupe_key(it.get("url") or "", it.get("room_id") or "")
if key in seen:
continue
seen.add(key)
out.append(it)
return out
def set_timeslot_exclude_text(text: str) -> dict[str, Any]:
from . import db
parsed = parse_timeslot_exclude_text(text)
items = list(parsed.get("items") or [])
db.update_settings_map({TIMESLOT_EXCLUDE_SETTING_KEY: items})
return {
"ok": True,
"items": items,
"count": len(items),
"skipped_dup": int(parsed.get("skipped_dup") or 0),
"skipped_invalid": int(parsed.get("skipped_invalid") or 0),
"text": str(parsed.get("text") or ""),
}
def import_timeslot_exclude_from_manual(*, merge: bool = True) -> dict[str, Any]:
"""Seed exclude list from 普通(manual) groups' featured Douyin URLs."""
existing = get_timeslot_exclude_items() if merge else []
seen = {_dedupe_key(it.get("url") or "", it.get("room_id") or "") for it in existing}
added = 0
for g in list_groups(include_urls=True):
if group_is_time_slot(g):
continue
for f in g.get("featured") or []:
if f.get("blacklisted"):
continue
url = str(f.get("url") or "").strip()
rid = str(f.get("room_id") or extract_room_id(url) or "").strip()
if not url and not rid:
continue
if not url and rid:
url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}"
key = _dedupe_key(url, rid)
if key in seen:
continue
seen.add(key)
existing.append(
{
"url": (normalize_room_url(url) or url)[:500],
"room_id": rid[:64],
"title": str(f.get("title") or f.get("pool_note") or "")[:120],
}
)
added += 1
from . import db
db.update_settings_map({TIMESLOT_EXCLUDE_SETTING_KEY: existing})
text = "\n".join(
f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "")
for it in existing
)
return {"ok": True, "items": existing, "count": len(existing), "added": added, "text": text}
def timeslot_exclude_room_ids(*, include_manual_featured: bool = True) -> set[str]:
"""Room ids time_slot relay / auto-fill must not use."""
out: set[str] = set()
for it in get_timeslot_exclude_items():
rid = str(it.get("room_id") or extract_room_id(it.get("url") or "") or "").strip()
if rid:
out.add(rid)
if include_manual_featured:
for g in list_groups(include_urls=True):
if group_is_time_slot(g):
continue
for f in g.get("featured") or []:
if f.get("blacklisted"):
continue
rid = str(f.get("room_id") or extract_room_id(str(f.get("url") or "")) or "").strip()
if rid:
out.add(rid)
return out
def timeslot_exclude_status() -> dict[str, Any]:
items = get_timeslot_exclude_items()
manual_ids = timeslot_exclude_room_ids(include_manual_featured=True)
stored_ids = timeslot_exclude_room_ids(include_manual_featured=False)
text = "\n".join(
f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "")
for it in items
)
return {
"ok": True,
"items": items,
"count": len(items),
"text": text,
"effective_room_count": len(manual_ids),
"stored_room_count": len(stored_ids),
"manual_featured_extra": max(0, len(manual_ids) - len(stored_ids)),
}

View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
"""Tests for timeslot exclude list parse/dedupe."""
from __future__ import annotations
from app.yt_assign_db import parse_timeslot_exclude_text
def test_parse_timeslot_exclude_dedupes_and_normalizes():
text = """
https://live.douyin.com/111111111111,主播: A,
https://live.douyin.com/111111111111
222222222222
https://live.douyin.com/222222222222?foo=1
not-a-url
https://live.douyin.com/333333333333,主播: B,
"""
r = parse_timeslot_exclude_text(text)
assert r["ok"] is True
assert r["count"] == 3
assert r["skipped_dup"] >= 2
assert r["skipped_invalid"] >= 1
ids = {it["room_id"] for it in r["items"]}
assert ids == {"111111111111", "222222222222", "333333333333"}
assert all(it["url"].startswith("https://live.douyin.com/") for it in r["items"])
def test_parse_timeslot_exclude_empty():
r = parse_timeslot_exclude_text(" \n ")
assert r["count"] == 0
assert r["items"] == []

View File

@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import Link from "next/link";
import {
Ban,
@ -11,6 +12,7 @@ import {
Download,
Eye,
EyeOff,
ListFilter,
Loader2,
Plus,
RefreshCw,
@ -21,7 +23,7 @@ import {
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
import { YtRelayLiveLogCard } from "@/components/YtRelayLiveLogCard";
import { YtRelayOpsHero } from "@/components/YtRelayOpsHero";
import { YtRelayProStatusPanel } from "@/components/YtRelayProStatusPanel";
import { YtRelayProStatusPanel, type OpsNekoCatalogItem } from "@/components/YtRelayProStatusPanel";
import { businessStatusLabel, isLivePushingRow, type RelayMonitorRow } from "@/lib/ytRelayStatus";
import { EnableSwitch } from "@/components/EnableSwitch";
import { useConfirm } from "@/components/ConfirmDialog";
@ -82,6 +84,8 @@ type SlotUrl = FeaturedUrl & {
window_hours?: number;
};
type AssignCategory = "normal" | "time_slot";
type AssignGroup = {
id: string;
name?: string;
@ -92,6 +96,8 @@ type AssignGroup = {
has_stream_key?: boolean;
note?: string;
enabled?: boolean;
category?: AssignCategory;
category_label?: string;
neko_instance_id?: number;
neko_enabled?: boolean;
neko_studio_url?: string;
@ -167,6 +173,7 @@ type RelaySettings = {
youtube_relay_quality_preset?: string;
youtube_relay_exclusive_live?: boolean;
youtube_relay_time_slot_mode?: boolean;
youtube_relay_timeslot_exclude_count?: number;
youtube_relay_encoding?: {
preset_id?: string;
width?: number;
@ -301,28 +308,111 @@ function AuthorizedChannelPicker({
disabled?: boolean;
}) {
const [open, setOpen] = useState(false);
const [menuPos, setMenuPos] = useState<{
top: number;
left: number;
width: number;
openUp: boolean;
} | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const btnRef = useRef<HTMLButtonElement>(null);
const selected = channels.find((c) => c.id === value) || null;
const placeMenu = useCallback(() => {
const el = btnRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
const spaceBelow = window.innerHeight - r.bottom - 8;
const openUp = spaceBelow < 200 && r.top > spaceBelow;
setMenuPos({
top: openUp ? r.top - 4 : r.bottom + 4,
left: Math.max(8, Math.min(r.left, window.innerWidth - r.width - 8)),
width: r.width,
openUp,
});
}, []);
useEffect(() => {
if (!open) return;
placeMenu();
const onDoc = (e: MouseEvent) => {
if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
const t = e.target as Node;
if (rootRef.current?.contains(t)) return;
if ((e.target as HTMLElement)?.closest?.("[data-auth-channel-menu]")) return;
setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false);
};
const onReposition = () => placeMenu();
document.addEventListener("mousedown", onDoc);
document.addEventListener("keydown", onKey);
window.addEventListener("resize", onReposition);
window.addEventListener("scroll", onReposition, true);
return () => {
document.removeEventListener("mousedown", onDoc);
document.removeEventListener("keydown", onKey);
window.removeEventListener("resize", onReposition);
window.removeEventListener("scroll", onReposition, true);
};
}, [open]);
}, [open, placeMenu]);
const menu =
open && menuPos
? createPortal(
<ul
data-auth-channel-menu
role="listbox"
style={{
position: "fixed",
top: menuPos.top,
left: menuPos.left,
width: menuPos.width,
zIndex: 200,
transform: menuPos.openUp ? "translateY(-100%)" : undefined,
}}
className="max-h-72 overflow-y-auto rounded-xl border border-white/10 bg-slate-950 py-1 shadow-2xl shadow-black/60 ring-1 ring-white/10"
>
{channels.length === 0 ? (
<li className="px-3 py-3 text-xs text-slate-500">暂无可用频道</li>
) : (
channels.map((c) => {
const active = c.id === value;
return (
<li key={c.id} role="option" aria-selected={active}>
<button
type="button"
onClick={() => {
onChange(c.id);
setOpen(false);
}}
className={`flex w-full items-center gap-2 px-2.5 py-2 text-left hover:bg-white/5 ${
active ? "bg-rose-500/10" : ""
}`}
>
<div className="min-w-0 flex-1">
<YtChannelProfileSnippet
profile={profileFor(c.id)}
fallbackName={c.title || c.name}
fallbackChannelId={c.youtube_channel_id || c.custom_url}
compact
/>
</div>
{active ? <Check className="h-4 w-4 shrink-0 text-rose-300" /> : null}
</button>
</li>
);
})
)}
</ul>,
document.body,
)
: null;
return (
<div ref={rootRef} className="relative min-w-0">
<div ref={rootRef} className="relative z-20 min-w-0">
<button
ref={btnRef}
type="button"
disabled={disabled || channels.length === 0}
onClick={() => setOpen((v) => !v)}
@ -344,44 +434,7 @@ function AuthorizedChannelPicker({
</div>
<ChevronDown className={`h-4 w-4 shrink-0 text-slate-400 transition ${open ? "rotate-180" : ""}`} />
</button>
{open ? (
<ul
role="listbox"
className="absolute z-40 mt-1 max-h-72 w-full overflow-y-auto rounded-xl border border-white/10 bg-slate-950 py-1 shadow-xl shadow-black/50"
>
{channels.length === 0 ? (
<li className="px-3 py-3 text-xs text-slate-500">暂无可用频道</li>
) : (
channels.map((c) => {
const active = c.id === value;
return (
<li key={c.id} role="option" aria-selected={active}>
<button
type="button"
onClick={() => {
onChange(c.id);
setOpen(false);
}}
className={`flex w-full items-center gap-2 px-2.5 py-2 text-left hover:bg-white/5 ${
active ? "bg-rose-500/10" : ""
}`}
>
<div className="min-w-0 flex-1">
<YtChannelProfileSnippet
profile={profileFor(c.id)}
fallbackName={c.title || c.name}
fallbackChannelId={c.youtube_channel_id || c.custom_url}
compact
/>
</div>
{active ? <Check className="h-4 w-4 shrink-0 text-rose-300" /> : null}
</button>
</li>
);
})
)}
</ul>
) : null}
{menu}
</div>
);
}
@ -447,6 +500,8 @@ export function YtAssignPanel({
const [schedule, setSchedule] = useState<RotationSchedule | null>(null);
const [groupId, setGroupId] = useState("");
const [profiles, setProfiles] = useState<Record<string, YtProfileSnippet>>({});
const [remoteCatalog, setRemoteCatalog] = useState<OpsNekoCatalogItem[]>([]);
const [hostProfile, setHostProfile] = useState("");
const [busy, setBusy] = useState(false);
const [showKey, setShowKey] = useState(false);
const [streamKeyDraft, setStreamKeyDraft] = useState("");
@ -454,13 +509,27 @@ export function YtAssignPanel({
const [poolDraft, setPoolDraft] = useState("");
const [newChannelPk, setNewChannelPk] = useState("");
const [newStreamKey, setNewStreamKey] = useState("");
const [newCategory, setNewCategory] = useState<AssignCategory>("normal");
const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>(
null
);
const [excludeOpen, setExcludeOpen] = useState(false);
const [excludeDraft, setExcludeDraft] = useState("");
const [excludeMeta, setExcludeMeta] = useState<{
count: number;
effective_room_count: number;
manual_featured_extra: number;
} | null>(null);
const [excludePreview, setExcludePreview] = useState<{
count: number;
skipped_dup: number;
skipped_invalid: number;
} | null>(null);
const [relayStatus, setRelayStatus] = useState<RelayStatus | null>(null);
const [relayBusy, setRelayBusy] = useState(false);
const [relayKickId, setRelayKickId] = useState("");
const [liveOnlyFilter, setLiveOnlyFilter] = useState(Boolean(liveLanding));
const [categoryFilter, setCategoryFilter] = useState<"all" | "normal" | "time_slot">("all");
const relayStatusRef = useRef<RelayStatus | null>(null);
const liveAutoPickedRef = useRef(false);
const { map: liveMap, refresh: refreshLiveMap } = useDouyinLiveMap();
@ -554,15 +623,21 @@ export function YtAssignPanel({
);
const orderedGroups = useMemo(() => {
if (!liveOnlyFilter && liveAssignIds.size === 0) return groups;
let list = groups;
if (categoryFilter === "normal") {
list = list.filter((g) => (g.category || "normal") !== "time_slot");
} else if (categoryFilter === "time_slot") {
list = list.filter((g) => g.category === "time_slot");
}
if (!liveOnlyFilter && liveAssignIds.size === 0) return list;
const live: AssignGroup[] = [];
const rest: AssignGroup[] = [];
for (const g of groups) {
for (const g of list) {
if (liveAssignIds.has(g.id)) live.push(g);
else if (!liveOnlyFilter) rest.push(g);
}
return [...live, ...rest];
}, [groups, liveAssignIds, liveOnlyFilter]);
}, [groups, liveAssignIds, liveOnlyFilter, categoryFilter]);
const selectedMonitor = useMemo(
() => relayEntries.find((e) => e.group_id === groupId),
@ -623,6 +698,19 @@ export function YtAssignPanel({
}
}, [toast, loadSchedule, focusGroupId]);
const loadRemoteCatalog = useCallback(async () => {
try {
const [cat, hp] = await Promise.all([
fetchJson("/api/ops/neko/remote-catalog").catch(() => ({ instances: [] })),
fetchJson("/api/ops/host-profile").catch(() => ({ profile: "" })),
]);
setRemoteCatalog(((cat as { instances?: OpsNekoCatalogItem[] }).instances || []) as OpsNekoCatalogItem[]);
setHostProfile(String((hp as { profile?: string }).profile || ""));
} catch {
/* ignore */
}
}, []);
useEffect(() => {
if (!focusGroupId || !groups.length) return;
if (groups.some((g) => g.id === focusGroupId)) {
@ -692,6 +780,7 @@ export function YtAssignPanel({
void loadGroups();
void loadAllProfiles();
void loadRelay();
void loadRemoteCatalog();
let cancelled = false;
let t: number | undefined;
const tick = () => {
@ -715,12 +804,16 @@ export function YtAssignPanel({
if (!document.hidden && !cancelled) void loadRelay();
};
document.addEventListener("visibilitychange", onVis);
const catTimer = window.setInterval(() => {
if (!document.hidden) void loadRemoteCatalog();
}, 5000);
return () => {
cancelled = true;
if (t) window.clearTimeout(t);
window.clearInterval(catTimer);
document.removeEventListener("visibilitychange", onVis);
};
}, [loadGroups, loadAllProfiles, loadRelay]);
}, [loadGroups, loadAllProfiles, loadRelay, loadRemoteCatalog]);
// Ordinary list titles + live badges: keep group payload in sync with live pool nicknames.
useEffect(() => {
@ -883,6 +976,7 @@ export function YtAssignPanel({
channel_pk: newChannelPk,
stream_key: streamKey,
enabled: true,
category: newCategory,
}),
})) as {
group?: AssignGroup;
@ -899,6 +993,7 @@ export function YtAssignPanel({
}
setNewChannelPk("");
setNewStreamKey("");
setNewCategory("normal");
await loadGroups();
if (r?.group?.id) setGroupId(r.group.id);
} catch (e) {
@ -928,6 +1023,23 @@ export function YtAssignPanel({
}
}
async function setGroupCategory(gid: string, category: AssignCategory) {
if (!gid) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/groups/${gid}`, {
method: "PATCH",
body: JSON.stringify({ category }),
});
toast.push(category === "time_slot" ? "已切换为时间段推流" : "已切换为普通(手动推流)", "ok");
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function removeGroup() {
if (!selected) return;
const ok = await confirm({
@ -1157,6 +1269,106 @@ export function YtAssignPanel({
}
}
async function openTimeslotExclude() {
setExcludeOpen(true);
setExcludePreview(null);
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/timeslot-exclude");
setExcludeDraft(String(r?.text || ""));
setExcludeMeta({
count: Number(r?.count || 0),
effective_room_count: Number(r?.effective_room_count || 0),
manual_featured_extra: Number(r?.manual_featured_extra || 0),
});
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function previewTimeslotExclude() {
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/timeslot-exclude/preview", {
method: "POST",
body: JSON.stringify({ text: excludeDraft }),
});
setExcludeDraft(String(r?.text || excludeDraft));
setExcludePreview({
count: Number(r?.count || 0),
skipped_dup: Number(r?.skipped_dup || 0),
skipped_invalid: Number(r?.skipped_invalid || 0),
});
toast.push(
`解析 ${Number(r?.count || 0)} 条` +
(Number(r?.skipped_dup || 0) ? ` · 去重 ${r.skipped_dup}` : "") +
(Number(r?.skipped_invalid || 0) ? ` · 无效 ${r.skipped_invalid}` : ""),
"ok"
);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function saveTimeslotExclude() {
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/timeslot-exclude", {
method: "POST",
body: JSON.stringify({ text: excludeDraft }),
});
setExcludeDraft(String(r?.text || ""));
setExcludeMeta({
count: Number(r?.count || 0),
effective_room_count: Number(r?.count || 0),
manual_featured_extra: excludeMeta?.manual_featured_extra || 0,
});
setExcludePreview({
count: Number(r?.count || 0),
skipped_dup: Number(r?.skipped_dup || 0),
skipped_invalid: Number(r?.skipped_invalid || 0),
});
// Refresh effective counts from server
const st = await fetchJson("/api/youtube/assign/timeslot-exclude");
setExcludeMeta({
count: Number(st?.count || 0),
effective_room_count: Number(st?.effective_room_count || 0),
manual_featured_extra: Number(st?.manual_featured_extra || 0),
});
toast.push(`已保存排除名单 ${Number(r?.count || 0)} 条`, "ok");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function importTimeslotExcludeFromManual() {
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/timeslot-exclude/import-manual", {
method: "POST",
body: JSON.stringify({ merge: true }),
});
setExcludeDraft(String(r?.text || ""));
const st = await fetchJson("/api/youtube/assign/timeslot-exclude");
setExcludeMeta({
count: Number(st?.count || 0),
effective_room_count: Number(st?.effective_room_count || 0),
manual_featured_extra: Number(st?.manual_featured_extra || 0),
});
toast.push(`已从普通精选导入 ${Number(r?.added || 0)} 条(合计 ${Number(r?.count || 0)})`, "ok");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function copyList(kind: "pool" | "featured" | "slots") {
if (!selected) return;
const rows =
@ -1276,7 +1488,7 @@ export function YtAssignPanel({
createForm={
<>
<form
className="grid gap-2 sm:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_auto] sm:items-center"
className="grid gap-2 sm:grid-cols-[minmax(0,1.2fr)_minmax(0,0.9fr)_minmax(7.5rem,auto)_auto] sm:items-center"
autoComplete="off"
onSubmit={(e) => {
e.preventDefault();
@ -1304,6 +1516,16 @@ export function YtAssignPanel({
data-form-type="other"
className="rounded-xl border border-white/10 bg-slate-950/80 px-3 py-2 text-sm outline-none ring-rose-400/0 transition focus:ring-2 focus:ring-rose-400/30"
/>
<select
value={newCategory}
onChange={(e) => setNewCategory((e.target.value as AssignCategory) || "normal")}
disabled={busy}
title="分组分类:普通=手动推流;时间段=排班推流"
className="rounded-xl border border-white/10 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none ring-rose-400/0 transition focus:ring-2 focus:ring-rose-400/30"
>
<option value="normal">普通</option>
<option value="time_slot">时间段</option>
</select>
<button
type="submit"
disabled={busy || !newChannelPk || !availableChannels.some((c) => c.id === newChannelPk)}
@ -1313,6 +1535,9 @@ export function YtAssignPanel({
新建分组
</button>
</form>
<p className="mt-2 text-[10px] text-slate-500">
普通 = 手动推流(精选源);时间段 = 24/N 排班 + 在播抖音源。其他分类待定。
</p>
{channels.length === 0 ? (
<p className="mt-3 text-xs text-amber-200">
还没有已授权频道。请先到{" "}
@ -1353,24 +1578,42 @@ export function YtAssignPanel({
<div>
<h4 className="text-sm font-medium text-teal-50">
{timeSlotModeOn || schedule.time_slot_mode
? "时间段排班 · 有 KEY 频道(北京时间)"
? "时间段排班 ·「时间段」分类频道(北京时间)"
: "24 小时频道轮播(北京时间)"}
</h4>
<p className="mt-0.5 text-[11px] text-teal-200/65">
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "}
{schedule.now_label}
{timeSlotModeOn ? " · 源=在播抖音" : ""}
{timeSlotModeOn || schedule.time_slot_mode ? " · 源=在播抖音" : ""}
</p>
</div>
<button
type="button"
disabled={busy}
onClick={() => void autoFillSlots(true, true)}
className="inline-flex items-center gap-1 rounded-xl border border-teal-400/20 bg-teal-500/15 px-2.5 py-1.5 text-[11px] text-teal-50 transition hover:bg-teal-500/25"
>
<RefreshCw className="h-3 w-3" />
全频道填充直播数据
</button>
<div className="flex flex-wrap items-center gap-1.5">
<button
type="button"
disabled={busy}
onClick={() => void openTimeslotExclude()}
className="inline-flex items-center gap-1 rounded-xl border border-amber-400/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] text-amber-50 transition hover:bg-amber-500/20"
title="时段推流不会选用这些抖音间(避免与手动直播撞流)"
>
<ListFilter className="h-3 w-3" />
排除手动直播名单
{excludeMeta?.count || relayStatus?.settings?.youtube_relay_timeslot_exclude_count ? (
<span className="rounded bg-amber-500/25 px-1 text-[10px] tabular-nums">
{excludeMeta?.count ??
relayStatus?.settings?.youtube_relay_timeslot_exclude_count}
</span>
) : null}
</button>
<button
type="button"
disabled={busy}
onClick={() => void autoFillSlots(true, true)}
className="inline-flex items-center gap-1 rounded-xl border border-teal-400/20 bg-teal-500/15 px-2.5 py-1.5 text-[11px] text-teal-50 transition hover:bg-teal-500/25"
>
<RefreshCw className="h-3 w-3" />
全频道填充直播数据
</button>
</div>
</div>
<div className="flex gap-1.5 overflow-x-auto pb-1">
{(schedule.channels || []).map((ch) => {
@ -1405,41 +1648,69 @@ export function YtAssignPanel({
<div className="grid gap-4 xl:grid-cols-[minmax(280px,300px)_minmax(0,1fr)]">
<aside className="space-y-2 xl:sticky xl:top-4 xl:self-start">
{(liveLanding || liveAssignIds.size > 0) && (
<div className="flex flex-wrap items-center gap-1.5 rounded-xl border border-white/10 bg-black/25 px-2.5 py-2">
<button
type="button"
onClick={() =>
setCategoryFilter((v) =>
v === "all" ? "normal" : v === "normal" ? "time_slot" : "all"
)
}
className={`rounded-lg border px-2 py-1 text-[10px] transition ${
categoryFilter === "all"
? "border-white/15 bg-white/5 text-slate-300"
: categoryFilter === "normal"
? "border-slate-400/30 bg-slate-500/15 text-slate-100"
: "border-teal-400/35 bg-teal-500/15 text-teal-50"
}`}
title="筛选分组分类:全部分类 → 普通 → 时间段"
>
{categoryFilter === "all"
? "全部分类"
: categoryFilter === "normal"
? "显示普通"
: "显示时间段"}
</button>
<button
type="button"
onClick={() => setLiveOnlyFilter((v) => !v)}
className={`rounded-lg border px-2 py-1 text-[10px] transition ${
liveOnlyFilter
? "border-rose-400/30 bg-rose-500/15 text-rose-100"
: "border-white/15 bg-white/5 text-slate-300"
}`}
>
{liveOnlyFilter ? "显示全部" : "只看在播"}
</button>
{liveAssignGroups.length > 0 ? (
<span className="ml-auto text-[10px] text-rose-200/80">
{liveAssignGroups.length} 路在播
{categoryFilter !== "all"
? ` · ${categoryFilter === "normal" ? "普通" : "时间段"}`
: ""}
</span>
) : null}
</div>
{(liveLanding || liveAssignIds.size > 0) && liveAssignGroups.length > 1 ? (
<div className="rounded-xl border border-rose-400/25 bg-rose-500/10 px-3 py-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="text-[11px] text-rose-100">
<span className="font-medium">{liveAssignGroups.length}</span> 路分配在播
{liveOnlyFilter ? " · 仅显示在播" : ""}
</div>
<button
type="button"
onClick={() => setLiveOnlyFilter((v) => !v)}
className="rounded-lg border border-rose-400/20 bg-black/20 px-2 py-1 text-[10px] text-rose-100/90 hover:bg-black/35"
>
{liveOnlyFilter ? "显示全部" : "只看在播"}
</button>
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
{liveAssignGroups.map((g) => (
<button
key={g.id}
type="button"
onClick={() => setGroupId(g.id)}
className={`shrink-0 rounded-lg border px-2 py-1 text-[10px] transition ${
g.id === groupId
? "border-rose-300/50 bg-rose-500/25 text-rose-50"
: "border-white/10 bg-black/30 text-slate-300 hover:bg-white/5"
}`}
>
{g.name || "频道"}
</button>
))}
</div>
{liveAssignGroups.length > 1 ? (
<div className="mt-2 flex gap-1.5 overflow-x-auto pb-0.5">
{liveAssignGroups.map((g) => (
<button
key={g.id}
type="button"
onClick={() => setGroupId(g.id)}
className={`shrink-0 rounded-lg border px-2 py-1 text-[10px] transition ${
g.id === groupId
? "border-rose-300/50 bg-rose-500/25 text-rose-50"
: "border-white/10 bg-black/30 text-slate-300 hover:bg-white/5"
}`}
>
{g.name || "频道"}
</button>
))}
</div>
) : null}
</div>
)}
) : null}
{orderedGroups.map((g) => {
const pk = String(g.channel_pk || "");
const ch = channelById[pk];
@ -1448,13 +1719,21 @@ export function YtAssignPanel({
const monitor = relayEntries.find((e) => e.group_id === g.id);
const pushing = isLivePushingRow(monitor);
const ytLive = liveAssignIds.has(g.id);
const cat = (g.category === "time_slot" ? "time_slot" : "normal") as AssignCategory;
return (
<button
<div
key={g.id}
id={ytLiveAssignDomId(g.id)}
type="button"
role="button"
tabIndex={0}
onClick={() => setGroupId(g.id)}
className={`scroll-mt-24 w-full min-w-0 overflow-hidden rounded-xl border p-2.5 text-left transition ${
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setGroupId(g.id);
}
}}
className={`scroll-mt-24 w-full min-w-0 cursor-pointer overflow-hidden rounded-xl border p-2.5 text-left transition ${
active
? pushing || ytLive
? "border-rose-400/50 bg-rose-500/10"
@ -1472,7 +1751,33 @@ export function YtAssignPanel({
compact
meta={ch ? buildChannelMeta(ch) : undefined}
/>
<div className="mt-2 flex flex-wrap gap-x-2 gap-y-1 text-[10px] text-slate-500">
<div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] text-slate-500">
<label
className="inline-flex items-center gap-1"
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
<span className="sr-only">分类</span>
<select
value={cat}
disabled={busy}
onClick={(e) => e.stopPropagation()}
onChange={(e) => {
e.stopPropagation();
const next = (e.target.value as AssignCategory) || "normal";
if (next !== cat) void setGroupCategory(g.id, next);
}}
className={`max-w-[5.5rem] rounded-md border px-1.5 py-0.5 text-[10px] outline-none ${
cat === "time_slot"
? "border-teal-400/35 bg-teal-500/15 text-teal-100"
: "border-white/15 bg-black/40 text-slate-200"
}`}
title="普通=手动推流;时间段=排班推流"
>
<option value="normal">普通</option>
<option value="time_slot">时间段</option>
</select>
</label>
<span>池 {(g.pool || []).length}</span>
<span>精选 {(g.featured || []).length}</span>
<span>时段 {(g.slots || []).length}</span>
@ -1490,12 +1795,18 @@ export function YtAssignPanel({
<span className="text-amber-300">推流错误</span>
) : null}
</div>
</button>
</div>
);
})}
{orderedGroups.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 px-3 py-8 text-center text-xs text-slate-500">
{liveOnlyFilter ? "当前没有分配在播频道" : "暂无分组"}
{liveOnlyFilter
? "当前没有分配在播频道"
: categoryFilter === "normal"
? "没有普通分类分组"
: categoryFilter === "time_slot"
? "没有时间段分类分组"
: "暂无分组"}
</div>
) : null}
</aside>
@ -1532,7 +1843,12 @@ export function YtAssignPanel({
onStart={(id) => void kickRelayGroup(id, "start")}
onStop={(id) => void kickRelayGroup(id, "stop")}
onRestart={(id) => void kickRelayGroup(id, "restart")}
onNekoChange={() => void loadGroups()}
onNekoChange={() => {
void loadGroups();
void loadRemoteCatalog();
}}
remoteCatalog={remoteCatalog}
hostProfile={hostProfile}
/>
<YtRelayLiveLogCard
@ -1545,6 +1861,21 @@ export function YtAssignPanel({
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<h4 className="text-sm font-medium text-slate-100">直播 KEY / 备注</h4>
<div className="flex flex-wrap gap-1.5">
<label className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[11px] text-slate-200">
<span className="text-slate-500">分类</span>
<select
value={selected.category === "time_slot" ? "time_slot" : "normal"}
disabled={busy}
onChange={(e) => {
const next = (e.target.value as AssignCategory) || "normal";
if (next !== (selected.category || "normal")) void setGroupCategory(selected.id, next);
}}
className="rounded-md border border-white/10 bg-slate-950 px-1.5 py-0.5 text-[11px] text-slate-100 outline-none"
>
<option value="normal">普通(手动推流)</option>
<option value="time_slot">时间段(排班推流)</option>
</select>
</label>
<button
type="button"
disabled={busy}
@ -2010,6 +2341,113 @@ export function YtAssignPanel({
</>
)}
{excludeOpen
? createPortal(
<div
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/70 p-4"
role="dialog"
aria-modal="true"
onClick={() => setExcludeOpen(false)}
>
<div
className="max-h-[90vh] w-full max-w-xl overflow-y-auto rounded-2xl border border-amber-400/25 bg-slate-950 p-4 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="mb-3 flex items-start justify-between gap-3">
<div>
<h3 className="text-sm font-medium text-amber-50">排除手动直播名单</h3>
<p className="mt-1 text-[11px] leading-relaxed text-slate-400">
不是黑名单:这些抖音间仍可监控 / 手动推流。时间段自动选源与「全频道填充」不会选用它们,避免与已指定的手动直播撞同一路流。
</p>
</div>
<button
type="button"
onClick={() => setExcludeOpen(false)}
className="rounded-lg border border-white/10 px-2 py-1 text-xs text-slate-300 hover:bg-white/5"
>
关闭
</button>
</div>
<p className="mb-2 text-[11px] text-slate-500">
支持多行 / 逗号分隔 /{" "}
<code className="text-slate-400">https://live.douyin.com/房间号,主播: 名称,</code>{" "}
/ 纯房间号 · 保存时自动规范化并去重
</p>
<textarea
value={excludeDraft}
onChange={(e) => {
setExcludeDraft(e.target.value);
setExcludePreview(null);
}}
rows={10}
placeholder={
"每行一条,例如:\nhttps://live.douyin.com/343450949840,主播: 街角早安三明治,\n466292216157"
}
className="mb-2 w-full rounded-xl border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs text-slate-100"
/>
<div className="mb-3 flex flex-wrap gap-2 text-[10px] text-slate-400">
<span>名单 {excludeMeta?.count ?? "—"} 条</span>
<span>·</span>
<span>有效排除房间 {excludeMeta?.effective_room_count ?? "—"}</span>
{(excludeMeta?.manual_featured_extra || 0) > 0 ? (
<>
<span>·</span>
<span>另含普通精选未写入名单 {excludeMeta?.manual_featured_extra} 间</span>
</>
) : null}
{excludePreview ? (
<>
<span>·</span>
<span>
预览 {excludePreview.count}(去重 {excludePreview.skipped_dup} / 无效{" "}
{excludePreview.skipped_invalid})
</span>
</>
) : null}
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={busy}
onClick={() => void previewTimeslotExclude()}
className="rounded-xl border border-white/15 bg-white/5 px-3 py-1.5 text-xs text-slate-100"
>
解析去重
</button>
<button
type="button"
disabled={busy}
onClick={() => void importTimeslotExcludeFromManual()}
className="rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-50"
>
从普通精选导入
</button>
<button
type="button"
disabled={busy}
onClick={() => {
setExcludeDraft("");
setExcludePreview(null);
}}
className="rounded-xl border border-white/10 px-3 py-1.5 text-xs text-slate-300"
>
清空编辑框
</button>
<button
type="button"
disabled={busy}
onClick={() => void saveTimeslotExclude()}
className="ml-auto rounded-xl border border-teal-400/30 bg-teal-500/15 px-3 py-1.5 text-xs text-teal-50"
>
保存名单
</button>
</div>
</div>
</div>,
document.body
)
: null}
{lightbox ? (
<ImageLightbox
src={lightbox.src}