diff --git a/README.md b/README.md index d86cacf..fde33d7 100644 --- a/README.md +++ b/README.md @@ -360,7 +360,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,** | **自动推流** | 设置 `youtube_relay_enabled=true` 或 UI「自动推流」;Worker 约 7s 轮询 | | **手动开始/停止** | 单频道「开始」= 武装监听(`manual_hold`),开播后自动推;「停止」释放 | | **时间段模式** | `youtube_relay_time_slot_mode`;**与自动推流、单路独占独立**。开启后:有 KEY 的 N 个频道按北京时 **24/N** 轮播;**源 = 监控库当前在播抖音房**(非精选列表);非当前时段停 FFmpeg | -| **单路独占** | `youtube_relay_exclusive_live`(VPS 默认开)。开:开播时只留一路 FFmpeg 并暂停兄弟**本机** Neko。**物理机建议关** | +| **单路独占** | `youtube_relay_exclusive_live`(VPS 默认开)。开:开播时只留一路 FFmpeg 并暂停兄弟**本机** Neko。普通频道选源**只认直播地址列表里真正在播的房**;拉流探测 `status=4`(监控可能仍显示在播)时排除该房、换同组源,仍失败则**释放独占**让下一组接管。多路同时推需关闭独占 | | **本机 Neko** | 分配卡片启停 → `POST .../groups/{id}/neko`;容器名 `douyinweb-neko-{N}`,URL `${PUBLIC_BASE}/neko/{N}/`。VPS / 物理机共用 `compose_service_lines`(Studio 登录页、live-ops 扩展、TM seed、远控码率默认 `1024x576@10` / 10fps / 700kbps) | | **远程 ops-neko** | 仅物理机跑 `douyinweb-ops-neko-{slot}`;edge 心跳推 catalog 到 VPS hub;分配页绑定后 `neko_open_prefer=remote`,打开 URL 优先 `https://….cn/ops-neko/{slot}/`(腾讯云 ICE)。**不删除**本机 `neko_instance_id` | | **画质预设** | `youtube_relay_quality_preset`(如 `720p`、`vps_ultra`);含分辨率、码率、AAC **128k**(推流,不是 Neko 远控码率) | diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py index c457fc8..0c4ddd8 100644 --- a/backend/app/youtube_relay_pipeline.py +++ b/backend/app/youtube_relay_pipeline.py @@ -115,19 +115,22 @@ def _normal_auto_candidates(groups: list[dict[str, Any]]) -> list[dict[str, Any] def _claim_first_live_normal( groups: list[dict[str, Any]], + *, + exclude_room_ids: set[str] | frozenset[str] | None = None, ) -> tuple[str, dict[str, Any], dict[str, str]] | None: """Exclusive normal mode: claim the first group whose 直播地址列表 has a live room. Deterministic order: sort_order, then group id. Sticky winner is handled by caller. """ live_ids = _live_room_ids() + exclude = {str(x).strip() for x in (exclude_room_ids or ()) if str(x or "").strip()} ranked: list[tuple[int, str, dict[str, Any], dict[str, str]]] = [] for g in groups: - src = pick_source_for_group(g, respect_schedule=False) + src = pick_source_for_group(g, respect_schedule=False, exclude_room_ids=exclude) if not src: continue rid = str(src.get("room_id") or "").strip() - if not rid or rid not in live_ids: + if not rid or rid not in live_ids or rid in exclude: continue ranked.append((int(g.get("sort_order") or 0), str(g.get("id") or ""), g, src)) if not ranked: @@ -211,6 +214,8 @@ def pick_source_for_group( if not url: continue rid = str(item.get("room_id") or "").strip() + if rid and rid in exclude: + continue live = rid in live_ids if rid else False candidates.append( { @@ -221,8 +226,12 @@ def pick_source_for_group( "idx": idx, } ) + # Auto-relay must not glue onto offline featured rows (monitor lag / status=4). + # Prefer live; if none live → None so exclusive can rotate to another group. candidates.sort(key=lambda x: (0 if x["live"] else 1, x["idx"])) for c in candidates: + if not c["live"]: + break return { "source_url": c["url"], "room_id": c["room_id"], @@ -245,6 +254,8 @@ class YoutubeRelayPipeline: # Consecutive Studio-not-on-air kills → cooldown (stops flap + daily stream burn). self._studio_fail_times: dict[str, list[float]] = {} self._studio_cooldown_until: dict[str, float] = {} + # Douyin probe said offline (status=4) while monitor may still list live — TTL exclude. + self._probe_offline_until: dict[str, float] = {} self.last_error = "" self.processed = 0 self._status_cache: dict[str, Any] | None = None @@ -262,6 +273,18 @@ class YoutubeRelayPipeline: self._studio_cooldown_until.pop(gid, None) self._studio_fail_times.pop(gid, None) + def _probe_offline_room_ids(self) -> set[str]: + now = time.time() + alive = {rid: until for rid, until in self._probe_offline_until.items() if float(until) > now} + self._probe_offline_until = alive + return set(alive.keys()) + + def _mark_probe_offline(self, room_id: str, *, ttl_sec: float = 180.0) -> None: + rid = str(room_id or "").strip() + if not rid: + return + self._probe_offline_until[rid] = time.time() + max(30.0, float(ttl_sec)) + def _note_studio_not_on_air(self, gid: str) -> tuple[bool, str]: """Record a Studio-not-on-air kill. Returns (tripped, message).""" now = time.time() @@ -935,17 +958,25 @@ class YoutubeRelayPipeline: if exclusive_on: cur = str(self._exclusive_winner or "").strip() cur_g = by_id.get(cur) if cur else None + probe_exclude = self._probe_offline_room_ids() if ( cur_g and cur_g.get("enabled") and not _group_uses_time_slot(cur_g) and _group_has_stream_key(cur_g) ): - sticky_src = pick_source_for_group(cur_g, respect_schedule=False) + sticky_src = pick_source_for_group( + cur_g, + respect_schedule=False, + exclude_room_ids=probe_exclude, + ) live_ids = _live_room_ids() + sticky_rid = str((sticky_src or {}).get("room_id") or "").strip() sticky_live = bool( sticky_src - and str(sticky_src.get("room_id") or "").strip() in live_ids + and sticky_rid + and sticky_rid in live_ids + and sticky_rid not in probe_exclude ) sess = self._sessions.get(cur) still_pushing = bool(sess and sess.stats.running) @@ -959,7 +990,9 @@ class YoutubeRelayPipeline: await self._release_exclusive_live() if not winner_gid: - claimed = _claim_first_live_normal(normal_groups) + claimed = _claim_first_live_normal( + normal_groups, exclude_room_ids=probe_exclude + ) if claimed: winner_gid, winner_g, winner_src = claimed @@ -1484,8 +1517,10 @@ 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: + # Monitor「进行中场次」can lag; sticky prefer must not glue forever onto status=4. + # Time-slot rotates live list; normal exclusive rotates featured then releases sticky. + exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True)) + if not cands and (slot_mode or exclusive_on): live_sess = self._sessions.get(gid) if live_sess and live_sess.stats.running: return { @@ -1495,10 +1530,12 @@ class YoutubeRelayPipeline: "ffmpeg_pid": int(live_sess.stats.pid or 0), "note": "probe_miss_keep_ffmpeg", } - exclude: set[str] = set() + exclude: set[str] = set(self._probe_offline_room_ids()) failed_rid = str(src.get("room_id") or "").strip() if failed_rid: exclude.add(failed_rid) + if probe.get("ok") and not probe.get("is_live"): + self._mark_probe_offline(failed_rid) boot_log.append( f"[relay] room offline/probe-miss rid={failed_rid or '-'} " f"status={probe.get('status_code')} → rotate live list" @@ -1521,8 +1558,6 @@ class YoutubeRelayPipeline: 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 "") @@ -1551,6 +1586,8 @@ class YoutubeRelayPipeline: if cands: break exclude.add(alt_rid) + if probe.get("ok") and not probe.get("is_live"): + self._mark_probe_offline(alt_rid) failed_rid = alt_rid if not cands: @@ -1566,6 +1603,28 @@ class YoutubeRelayPipeline: } if gid in self._sessions: await self._halt_session(gid, reason="wait_live") + failed_rid = str(src.get("room_id") or "").strip() + if failed_rid and probe.get("ok") and not probe.get("is_live"): + self._mark_probe_offline(failed_rid) + # Exclusive sticky: monitor can still list this room live while probe=4 — + # release so another normal group (with a real live featured) can claim. + if ( + exclusive_on + and not slot_mode + and str(self._exclusive_winner or "") == gid + and gid not in self._manual_hold + and probe.get("ok") + and not probe.get("is_live") + ): + boot_log.append( + f"[relay] exclusive release: winner featured probe offline " + f"rid={failed_rid or '-'} status={probe.get('status_code')}" + ) + self._exclusive_winner = None + try: + await self._release_exclusive_live() + except Exception: + pass anchor = str(src.get("anchor_name") or probe.get("anchor_name") or "").strip() or "-" if probe.get("risk") or (probe.get("ok") is False): note = str(probe.get("error") or "风控/接口失败,将继续轮询").strip() @@ -1592,6 +1651,7 @@ class YoutubeRelayPipeline: "group_id": gid, "source_url": src.get("source_url") or "", "note": line, + "exclusive_released": str(self._exclusive_winner or "") != gid, } try: diff --git a/backend/tests/test_relay_normal_auto.py b/backend/tests/test_relay_normal_auto.py index b582724..8f7ecd9 100644 --- a/backend/tests/test_relay_normal_auto.py +++ b/backend/tests/test_relay_normal_auto.py @@ -76,3 +76,31 @@ def test_pick_source_normal_featured_prefer_live(monkeypatch): } src = pick_source_for_group(g, respect_schedule=False) assert src and src["room_id"] == "live1" + + +def test_pick_source_normal_returns_none_when_all_offline(monkeypatch): + monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", lambda: set()) + g = { + "id": "g1", + "enabled": 1, + "category": "normal", + "featured": [ + {"url": "https://live.douyin.com/off", "room_id": "off", "title": "off"}, + ], + } + assert pick_source_for_group(g, respect_schedule=False) is None + + +def test_pick_source_normal_respects_exclude(monkeypatch): + monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", lambda: {"a", "b"}) + g = { + "id": "g1", + "enabled": 1, + "category": "normal", + "featured": [ + {"url": "https://live.douyin.com/a", "room_id": "a", "title": "A"}, + {"url": "https://live.douyin.com/b", "room_id": "b", "title": "B"}, + ], + } + src = pick_source_for_group(g, respect_schedule=False, exclude_room_ids={"a"}) + assert src and src["room_id"] == "b" diff --git a/scripts/_deploy_excl_dy_only.py b/scripts/_deploy_excl_dy_only.py new file mode 100644 index 0000000..236a0d3 --- /dev/null +++ b/scripts/_deploy_excl_dy_only.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOST = "108.174.50.68" + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(15): + try: + c.connect( + HOST, + 22, + "root", + PASS, + timeout=50, + allow_agent=False, + look_for_keys=False, + banner_timeout=120, + ) + print("connected", i, flush=True) + break + except Exception as e: + print("retry", i, type(e).__name__, flush=True) + time.sleep(4 + i) + else: + print("ssh_fail") + return 1 + + sftp = c.open_sftp() + for rel, dst in [ + ("backend/app/youtube_relay_pipeline.py", "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py"), + ("backend/tests/test_relay_normal_auto.py", "/opt/douyinWEB/backend/tests/test_relay_normal_auto.py"), + ]: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_excl_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + _, o, e = c.exec_command(f"cat {tmp} > {dst} && echo OK {dst}", timeout=30) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + sftp.close() + + remote = """ +systemctl restart douyinweb-api +for i in $(seq 1 20); do + c=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health_$i=$c + [ "$c" = "200" ] && break + sleep 2 +done +systemctl is-active douyinweb-api +""" + _, o, e = c.exec_command(remote, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace"), flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/_deploy_exclusive_probe_rotate.py b/scripts/_deploy_exclusive_probe_rotate.py new file mode 100644 index 0000000..50bad7c --- /dev/null +++ b/scripts/_deploy_exclusive_probe_rotate.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +"""Deploy exclusive probe-offline rotate fix; keep current push if healthy.""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")] +FILES = [ + ("backend/app/youtube_relay_pipeline.py", "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py"), + ("backend/tests/test_relay_normal_auto.py", "/opt/douyinWEB/backend/tests/test_relay_normal_auto.py"), +] + +REMOTE = r''' +set -e +cd /opt/douyinWEB/backend +.venv/bin/python -m pytest tests/test_relay_normal_auto.py -q --tb=line || true +systemctl restart douyinweb-api +for i in $(seq 1 25); do + c=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health_$i=$c + [ "$c" = "200" ] && break + sleep 2 +done +PYTHONPATH=/opt/douyinWEB/backend .venv/bin/python - <<'PY' +import json, time +from app import youtube_relay_db, yt_assign_db +from app.youtube_neko import _cdp_studio_page_signals +from app.youtube_relay_pipeline import youtube_relay_pipeline as rp + +# walking tour on dylive +groups = {str(g.get("name")): g for g in yt_assign_db.list_groups(include_urls=False)} +for name in ("walking tour", "Nomadro Hub"): + g = groups.get(name) + if not g: + print("missing", name); continue + st = youtube_relay_db.get_relay_state(g["id"]) or {} + print(name, "status", st.get("status"), "src", st.get("source_room_id"), "pid", st.get("ffmpeg_pid"), "err", str(st.get("error") or "")[:80]) +print("exclusive_winner", getattr(rp, "_exclusive_winner", None)) +# give worker a tick +time.sleep(8) +for name in ("walking tour",): + g = groups.get(name) + if not g: continue + st = youtube_relay_db.get_relay_state(g["id"]) or {} + print("after_tick", name, st.get("status"), st.get("ffmpeg_pid"), (st.get("recent_log") or [])[-2:]) + nid = int(g.get("neko_instance_id") or 0) + if nid: + try: + sig = _cdp_studio_page_signals(nid, force=True) + print("studio", sig.get("live_status"), "on_air", sig.get("on_air"), "recv", sig.get("encoder_receiving")) + except Exception as e: + print("studio_err", e) +PY +systemctl is-active douyinweb-api +''' + + +def connect(host: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(8): + try: + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90) + return c + except Exception as e: + print("ssh_retry", host, i, e, flush=True) + time.sleep(2 + i) + raise SystemExit(f"ssh_fail {host}") + + +def main(): + for label, host in HOSTS: + print(f"\n===== {label} {host} =====", flush=True) + c = connect(host) + sftp = c.open_sftp() + for rel, dst in FILES: + data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") + tmp = f"/tmp/_excl_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + _, o, e = c.exec_command(f"cat {tmp} > {dst} && echo OK {dst}", timeout=30) + print((o.read() + e.read()).decode("utf-8", "replace")[:200], flush=True) + with sftp.file("/tmp/_deploy_excl_rotate.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + sftp.close() + _, o, e = c.exec_command("bash /tmp/_deploy_excl_rotate.sh", timeout=240) + print((o.read() + e.read()).decode("utf-8", "replace")[-5000:], flush=True) + c.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/_jump_deploy_excl_dy.py b/scripts/_jump_deploy_excl_dy.py new file mode 100644 index 0000000..e024afb --- /dev/null +++ b/scripts/_jump_deploy_excl_dy.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +import sys + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +c = paramiko.SSHClient() +c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False) +cmd = r""" +set -e +export SSHPASS='Xiao4669805' +command -v sshpass >/dev/null || apt-get install -y sshpass >/dev/null +sshpass -e scp -o StrictHostKeyChecking=no /tmp/youtube_relay_pipeline.py root@108.174.50.68:/opt/douyinWEB/backend/app/youtube_relay_pipeline.py +sshpass -e scp -o StrictHostKeyChecking=no /tmp/test_relay_normal_auto.py root@108.174.50.68:/opt/douyinWEB/backend/tests/test_relay_normal_auto.py +sshpass -e ssh -o StrictHostKeyChecking=no root@108.174.50.68 bash -s <<'EOS' +systemctl restart douyinweb-api +for i in $(seq 1 20); do + c=$(curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health || echo x) + echo health_$i=$c + [ "$c" = "200" ] && break + sleep 2 +done +systemctl is-active douyinweb-api +EOS +""" +_, o, e = c.exec_command(cmd, timeout=180) +print((o.read() + e.read()).decode("utf-8", "replace")) +c.close() diff --git a/scripts/_probe_dual_normal_push_now.py b/scripts/_probe_dual_normal_push_now.py new file mode 100644 index 0000000..b7379e9 --- /dev/null +++ b/scripts/_probe_dual_normal_push_now.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +import sys +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" + + +def probe(host: str, label: str) -> None: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + cmd = r""" +cd /opt/douyinWEB/backend && PYTHONPATH=/opt/douyinWEB/backend .venv/bin/python - <<'PY' +import subprocess +from app import youtube_relay_db, yt_assign_db, db +from app.youtube_neko import _cdp_studio_page_signals +from app.youtube_relay_pipeline import youtube_relay_pipeline as rp, _claim_first_live_normal, _normal_auto_candidates + +cfg = db.get_settings_map() +print('relay', cfg.get('youtube_relay_enabled'), 'exclusive', cfg.get('youtube_relay_exclusive_live'), 'slot', cfg.get('youtube_relay_time_slot_mode')) +print('winner', getattr(rp, '_exclusive_winner', None), 'probe_off', sorted(getattr(rp, '_probe_offline_until', {}) or {})[:8]) +groups = yt_assign_db.list_groups(include_urls=True) +normals = [g for g in groups if (g.get('category') or 'normal') != 'time_slot'] +for g in normals: + st = youtube_relay_db.get_relay_state(g['id']) or {} + print('N', g.get('name'), st.get('status'), 'src', st.get('source_room_id') or '-', 'pid', st.get('ffmpeg_pid') or 0, str(st.get('error') or '')[:50]) +claimed = _claim_first_live_normal(_normal_auto_candidates(groups)) +print('claim', (claimed[1].get('name') if claimed else None), (claimed[2] if claimed else None)) +print('ffmpeg_n', subprocess.getoutput("ps -ef | grep ffmpeg | grep -v grep | wc -l").strip()) +# studio for any pushing normal +for g in normals: + st = youtube_relay_db.get_relay_state(g['id']) or {} + if str(st.get('status') or '') not in {'pushing', 'starting'}: + continue + nid = int(g.get('neko_instance_id') or 0) + if not nid: + continue + try: + sig = _cdp_studio_page_signals(nid, force=True) + print('studio', g.get('name'), 'neko', nid, sig.get('live_status'), 'on_air', sig.get('on_air'), 'recv', sig.get('encoder_receiving')) + except Exception as e: + print('studio_err', e) +PY +""" + _, o, e = c.exec_command(cmd, timeout=70) + print(f"===== {label} {host} =====") + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + probe("107.173.30.245", "dylive") + try: + probe("108.174.50.68", "dy") + except Exception as e: + print("dy_direct_fail", e) + # jump + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect("107.173.30.245", 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + "sshpass -e ssh -o StrictHostKeyChecking=no root@108.174.50.68 'curl -sS -m 5 http://127.0.0.1:8014/api/health | head -c 200'", + timeout=40, + environment={"SSHPASS": PASS}, + ) + # paramiko may not pass env that way; use inline + _, o, e = c.exec_command( + "SSHPASS='Xiao4669805' sshpass -e ssh -o StrictHostKeyChecking=no root@108.174.50.68 \"curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health\"", + timeout=40, + ) + print("dy_via_jump_health", (o.read() + e.read()).decode("utf-8", "replace")) + c.close() diff --git a/scripts/_probe_dylive_normal_offline.py b/scripts/_probe_dylive_normal_offline.py new file mode 100644 index 0000000..ae0891f --- /dev/null +++ b/scripts/_probe_dylive_normal_offline.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import json +import sys + +import paramiko + +HOST = "107.173.30.245" +PASS = "Xiao4669805" + +REMOTE = r''' +cd /opt/douyinWEB/backend && .venv/bin/python - <<'PY' +import json +from app import db, yt_assign_db, youtube_relay_db +from app.youtube_relay_status import summarize_relay_group +from app.youtube_relay_pipeline import youtube_relay_pipeline as rp, _normal_auto_candidates, pick_source_for_group + +cfg = db.get_settings_map() +for k in sorted(cfg): + if 'relay' in k or 'slot' in k or 'exclusive' in k: + print('CFG', k, '=', cfg[k]) + +groups = yt_assign_db.list_groups(include_urls=True) +normals = [g for g in groups if (g.get('category') or 'normal') == 'normal'] +print('normal_groups', len(normals), 'all', len(groups)) +print('exclusive_winner', getattr(rp, '_exclusive_winner', None)) +print('relay_running', getattr(rp, '_running', None), getattr(rp, 'running', None)) +print('rp_procs', list(getattr(rp, '_procs', {}) or {})[:10] if hasattr(rp,'_procs') else 'n/a') + +# candidates +cands = _normal_auto_candidates(groups) +print('normal_auto_candidates', len(cands)) +for c in cands: + print(' CAND', c.get('name'), 'gid', str(c.get('id'))[:8], 'feat', len(c.get('featured') or [])) + +# each normal: featured live + relay state +for g in normals: + name = g.get('name') or '' + gid = g.get('id') + feat = g.get('featured') or [] + print('====', name, 'gid', str(gid)[:8], 'neko', g.get('neko_instance_id'), 'neko_en', g.get('neko_enabled'), 'feat_n', len(feat)) + for f in feat[:8]: + print(' FEAT', f.get('room_id') or '', (f.get('title') or '')[:40], (f.get('url') or '')[:60]) + try: + src = pick_source_for_group(g, respect_schedule=False) + print(' PICK_SRC', json.dumps(src, ensure_ascii=False, default=str)[:300] if src else None) + except Exception as e: + print(' PICK_ERR', e) + st = youtube_relay_db.get_relay_state(gid) or {} + print(' STATE', json.dumps({k: st.get(k) for k in ('status','error','source_url','source_room_id','pid','started_at','updated_at','manual_hold','ffmpeg_running','is_pushing')}, ensure_ascii=False, default=str)[:500]) + # ffmpeg processes for this group + try: + summ = summarize_relay_group(g, st) + print(' SUM', json.dumps({k: summ.get(k) for k in ('business_status','is_pushing','status_label','error','source_room_id','neko')}, ensure_ascii=False, default=str)[:400]) + except Exception as e: + print(' SUM_ERR', e) + +# live rooms from monitor matching featured +live_rids=set() +try: + rows = db.list_rooms(limit=500) if hasattr(db,'list_rooms') else None +except Exception: + rows=None +if rows is None: + import sqlite3 + from app.config import settings + path = getattr(settings, 'db_path', None) or '/opt/douyinWEB/backend/data/monitor.db' + con=sqlite3.connect(path); con.row_factory=sqlite3.Row + cols=[r[1] for r in con.execute('PRAGMA table_info(rooms)')] + print('rooms_cols', cols[:25]) + q="SELECT room_id, last_anchor, last_status FROM rooms WHERE COALESCE(last_status,'')='live' LIMIT 30" + + try: + rs=con.execute(q).fetchall() + except Exception as e: + print('qerr', e) + # try simpler + rs=con.execute('SELECT room_id, last_status FROM rooms LIMIT 5').fetchall() + print('sample', [dict(r) for r in rs]) + rs=[] + for r in rs: + live_rids.add(str(r['room_id'])) + print('LIVE_ROOM', r['room_id'], (r['last_anchor'] if 'last_anchor' in r.keys() else ''), r['last_status'] if 'last_status' in r.keys() else '') +else: + print('list_rooms', type(rows)) + +print('LIVE_RIDS', sorted(live_rids)[:20]) + +# ffmpeg / docker neko +import subprocess +print('FFMPEG', subprocess.getoutput('ps -ef | grep -E \"ffmpeg.*youtube|ffmpeg.*rtmp\" | grep -v grep | head -20')[:800]) +print('NEKO', subprocess.getoutput('docker ps --format \"{{.Names}} {{.Status}}\" | grep -E \"douyinweb-neko\" | head -20')[:800]) +PY +''' + +def main(): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(HOST, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command(REMOTE, timeout=90) + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + +if __name__ == "__main__": + main() diff --git a/scripts/_remote_check_room_status.py b/scripts/_remote_check_room_status.py new file mode 100644 index 0000000..34eaef0 --- /dev/null +++ b/scripts/_remote_check_room_status.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +import json +import asyncio +from app.douyin import check_room +from app import db + +cfg = db.get_settings_map() +cookie = str(cfg.get("dy_cookie") or "").strip() +print("cookie_len", len(cookie)) + +async def main(): + for rid, title in [ + ("881772183814", "apo"), + ("690114366322", "luwei"), + ]: + url = f"https://live.douyin.com/{rid}" + probe = await check_room(url, cookie=cookie) + print( + title, + rid, + json.dumps( + { + "ok": probe.get("ok"), + "is_live": probe.get("is_live"), + "status_code": probe.get("status_code"), + "risk": probe.get("risk"), + "anchor": (probe.get("anchor_name") or "")[:40], + "err": str(probe.get("error") or "")[:80], + "cands": len(probe.get("stream_candidates") or []), + "stream": str(probe.get("stream_url") or "")[:80], + }, + ensure_ascii=False, + ), + ) + +asyncio.run(main()) + +# monitor live flags for same rooms +import sqlite3 +from app.config import settings +path = getattr(settings, "db_path", None) or "data/monitor.db" +con = sqlite3.connect(path) +con.row_factory = sqlite3.Row +for rid in ("881772183814", "690114366322"): + r = con.execute( + "SELECT room_id, last_status, last_anchor, last_checked_at FROM rooms WHERE room_id=?", + (rid,), + ).fetchone() + print("DB", dict(r) if r else rid) diff --git a/scripts/_verify_excl_and_deploy_dy.py b/scripts/_verify_excl_and_deploy_dy.py new file mode 100644 index 0000000..5efef63 --- /dev/null +++ b/scripts/_verify_excl_and_deploy_dy.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +import sys +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PASS = "Xiao4669805" + + +def probe(host: str, label: str): + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, 22, "root", PASS, timeout=50, allow_agent=False, look_for_keys=False, banner_timeout=120) + cmd = r''' +cd /opt/douyinWEB/backend && PYTHONPATH=/opt/douyinWEB/backend .venv/bin/python - <<'PY' +import json, subprocess +from app import youtube_relay_db, yt_assign_db +from app.youtube_neko import _cdp_studio_page_signals +from app.youtube_relay_pipeline import youtube_relay_pipeline as rp, _claim_first_live_normal, _normal_auto_candidates + +groups = yt_assign_db.list_groups(include_urls=True) +by = {g.get("name"): g for g in groups} +g = by.get("walking tour") +st = youtube_relay_db.get_relay_state(g["id"]) if g else {} +print("wt", (st or {}).get("status"), "pid", (st or {}).get("ffmpeg_pid"), "src", (st or {}).get("source_room_id"), "err", str((st or {}).get("error") or "")[:100]) +print("log", ((st or {}).get("recent_log") or [])[-4:]) +print("winner", getattr(rp, "_exclusive_winner", None)) +claimed = _claim_first_live_normal(_normal_auto_candidates(groups)) +print("claim", claimed[1].get("name") if claimed else None, claimed[2] if claimed else None) +print("ffmpeg", subprocess.getoutput("ps -ef | grep 'ffmpeg' | grep -v grep | wc -l").strip()) +if g: + nid=int(g.get("neko_instance_id") or 0) + if nid: + try: + sig=_cdp_studio_page_signals(nid, force=True) + print("studio", sig.get("live_status"), "on_air", sig.get("on_air"), "recv", sig.get("encoder_receiving"), "lost", sig.get("encoder_lost")) + except Exception as e: + print("studio_err", e) +PY +''' + _, o, e = c.exec_command(cmd, timeout=60) + print(f"=== {label} ===") + print((o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +def deploy_dy(): + root = Path(__file__).resolve().parents[1] + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + for i in range(10): + try: + c.connect("108.174.50.68", 22, "root", PASS, timeout=50, allow_agent=False, look_for_keys=False, banner_timeout=120) + break + except Exception as e: + print("dy_ssh", i, e, flush=True) + time.sleep(3 + i) + else: + print("dy_ssh_fail") + return + sftp = c.open_sftp() + for rel, dst in [ + ("backend/app/youtube_relay_pipeline.py", "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py"), + ("backend/tests/test_relay_normal_auto.py", "/opt/douyinWEB/backend/tests/test_relay_normal_auto.py"), + ]: + data = (root / rel).read_bytes().replace(b"\r\n", b"\n") + tmp = f"/tmp/_excl_{Path(rel).name}" + with sftp.file(tmp, "wb") as f: + f.write(data) + c.exec_command(f"cat {tmp} > {dst}", timeout=20) + sftp.close() + _, o, e = c.exec_command( + "systemctl restart douyinweb-api; sleep 4; curl -sS -m 5 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo; systemctl is-active douyinweb-api", + timeout=60, + ) + print("dy_deploy", (o.read() + e.read()).decode("utf-8", "replace")) + c.close() + + +if __name__ == "__main__": + time.sleep(20) + probe("107.173.30.245", "dylive") + deploy_dy()