diff --git a/d2ypp2/douyin_youtube_ffplay.py b/d2ypp2/douyin_youtube_ffplay.py index b2ec0a3..eb1ff33 100644 --- a/d2ypp2/douyin_youtube_ffplay.py +++ b/d2ypp2/douyin_youtube_ffplay.py @@ -249,13 +249,25 @@ def _is_disabled_value(value: str) -> bool: return (value or "").strip().lower() in {"0", "false", "no", "off", "none", "direct"} +_PROXY_ENV_KEYS = ( + "http_proxy", + "https_proxy", + "all_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", +) + + def _normalize_push_proxy_mode(configured: str | None = None) -> str: - value = ( - configured - or os.environ.get("YOUTUBE_PUSH_PROXY_MODE") - or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_MODE") - or "auto" - ) + value = configured or os.environ.get("YOUTUBE_PUSH_PROXY_MODE") or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_MODE") + if not value: + attach = (os.environ.get("SHELLCRASH_ATTACH_FFMPEG") or "").strip() + if _is_disabled_value(attach): + return "off" + if attach.lower() in {"1", "true", "yes", "on", "enable", "enabled", "force", "forced", "proxy", "shellcrash"}: + return "proxychains" + value = "auto" low = (value or "").strip().lower() if low in {"0", "false", "no", "off", "none", "direct"}: return "off" @@ -267,16 +279,12 @@ def _normalize_push_proxy_mode(configured: str | None = None) -> str: def _resolve_youtube_push_proxy(configured: str | None = None) -> str: - candidates = [ + explicit_candidates = [ configured, os.environ.get("YOUTUBE_PUSH_PROXY"), os.environ.get("LIVE_YOUTUBE_PUSH_PROXY"), - os.environ.get("https_proxy"), - os.environ.get("http_proxy"), - os.environ.get("HTTPS_PROXY"), - os.environ.get("HTTP_PROXY"), ] - for value in candidates: + for value in explicit_candidates: value = (value or "").strip() if _is_disabled_value(value): return "" @@ -285,16 +293,36 @@ def _resolve_youtube_push_proxy(configured: str | None = None) -> str: auto = os.environ.get("YOUTUBE_PUSH_PROXY_AUTO", "1").strip().lower() if auto not in {"0", "false", "no", "off"} and _is_local_tcp_open("127.0.0.1", 7890): - return "http://127.0.0.1:7890" + return "socks5://127.0.0.1:7890" + + for key in ("https_proxy", "http_proxy", "HTTPS_PROXY", "HTTP_PROXY"): + value = (os.environ.get(key) or "").strip() + if _is_disabled_value(value): + return "" + if value: + return value return "" -def _ffmpeg_env_with_push_proxy(push_proxy: str) -> dict[str, str] | None: +def _ffmpeg_env_with_push_proxy( + push_proxy: str, + proxy_mode: str = "auto", + *, + use_proxychains: bool = False, +) -> dict[str, str]: + env = os.environ.copy() + for key in _PROXY_ENV_KEYS: + env.pop(key, None) + push_proxy = (push_proxy or "").strip() if not push_proxy: - return None - env = os.environ.copy() - for key in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + return env + + mode = _normalize_push_proxy_mode(proxy_mode) + if mode == "off" or use_proxychains: + return env + + for key in _PROXY_ENV_KEYS: env[key] = push_proxy return env @@ -563,8 +591,8 @@ def start_douyin_youtube_ffplay( raise ValueError(f"请在 {config_file} 中配置 key=你的stream_key") # ====================== 常量配置 ====================== - push_proxy = _resolve_youtube_push_proxy(push_proxy) push_proxy_mode = _normalize_push_proxy_mode(push_proxy_mode) + push_proxy = "" if push_proxy_mode == "off" else _resolve_youtube_push_proxy(push_proxy) if push_proxy: print(f"[INFO] YouTube push proxy ({push_proxy_mode}): {_redact_proxy_url(push_proxy)}") ffmpeg_bin, ffmpeg_note = _resolve_youtube_push_ffmpeg("ffmpeg", push_proxy, push_proxy_mode) @@ -902,11 +930,14 @@ def start_douyin_youtube_ffplay( if _ffmpeg_cwd: _popen_kw["cwd"] = _ffmpeg_cwd ffmpeg_exec = _proxychains_command(ffmpeg_command, push_proxy, push_proxy_mode) + _uses_proxychains = ffmpeg_exec is not None if ffmpeg_exec is None: ffmpeg_exec = ffmpeg_command - _ffmpeg_env = _ffmpeg_env_with_push_proxy(push_proxy) - if _ffmpeg_env: - _popen_kw["env"] = _ffmpeg_env + _popen_kw["env"] = _ffmpeg_env_with_push_proxy( + push_proxy, + push_proxy_mode, + use_proxychains=_uses_proxychains, + ) proc = subprocess.Popen(ffmpeg_exec, **_popen_kw) proc.last_out_ts = time.time() diff --git a/d2ypp2/scripts/launch.py b/d2ypp2/scripts/launch.py index 9a04fb9..908279f 100644 --- a/d2ypp2/scripts/launch.py +++ b/d2ypp2/scripts/launch.py @@ -51,8 +51,7 @@ import env_check # noqa: E402 from src.runtime_bootstrap import ensure_runtime_layout, raise_nofile_limit # noqa: E402 -def load_runtime_env() -> None: - path = ROOT / "config" / "runtime.env" +def _load_env_file(path: Path) -> None: if not path.is_file(): return for raw in path.read_text(encoding="utf-8").splitlines(): @@ -67,6 +66,11 @@ def load_runtime_env() -> None: os.environ[k] = v +def load_runtime_env() -> None: + _load_env_file(ROOT / "config" / "runtime.env") + _load_env_file(ROOT / "config" / "system-stack.env") + + @dataclass(frozen=True) class NodeRuntime: node: Path diff --git a/d2ypp2/src/douyin_source_display.py b/d2ypp2/src/douyin_source_display.py index 6ff6e27..8d91795 100644 --- a/d2ypp2/src/douyin_source_display.py +++ b/d2ypp2/src/douyin_source_display.py @@ -4,18 +4,28 @@ import re from typing import Any _DOUYIN_LIVE_URL_RE = re.compile(r"https?://(?:www\.)?live\.douyin\.com/([a-zA-Z0-9_-]+)", re.IGNORECASE) +_DOUYIN_LIVE_ROOM_RE = re.compile(r"(?:https?://(?:www\.)?)?live\.douyin\.com/([a-zA-Z0-9_-]+)", re.IGNORECASE) _STATUS_TITLE_RE = re.compile( r"(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中)", re.IGNORECASE, ) +_RECORDING_TITLE_RE = re.compile(r"(?:正在录制|录制中)\s*\d*\s*个?\s*[::]\s*([^\[\r\n]{1,80})", re.IGNORECASE) +_LIVE_TITLE_RE = re.compile( + r"(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:正在直播中|正在直播|直播中|已开播|开始推流|录制中|推流中)", + re.IGNORECASE, +) +_WAIT_TITLE_RE = re.compile(r"(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|主播已下播|下播)", re.IGNORECASE) _LABEL_TITLE_RE = re.compile(r"(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*(.{1,80})", re.IGNORECASE) _BAD_TITLE_RE = re.compile(r"^\s*(?:-|—|_|无|未知|unknown|null|undefined|none|nan)?\s*$", re.IGNORECASE) +_ERROR_CONTEXT_RE = re.compile(r"(?:获取失败|错误|异常|error|failed|exception)", re.IGNORECASE) def _clean_source_title(value: str) -> str: text = (value or "").strip().strip("\"'`[]()()【】") + text = re.sub(r"^\[[A-Z]+\]\s*", "", text, flags=re.IGNORECASE) + text = re.sub(r"^序号\s*\d+\s*", "", text) text = re.sub(r"^(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*", "", text, flags=re.IGNORECASE) - text = _DOUYIN_LIVE_URL_RE.sub("", text) + text = _DOUYIN_LIVE_ROOM_RE.sub("", text) text = re.sub(r"(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中).*$", "", text).strip() text = text.strip(" ,,;;||-—::") if _BAD_TITLE_RE.match(text): @@ -29,49 +39,148 @@ def _clean_source_title(value: str) -> str: return text[:48] -def _source_title_from_url_lines(url_lines: str) -> str: +def _url_entries_from_lines(url_lines: str) -> list[dict[str, str]]: + entries: list[dict[str, str]] = [] for line in (url_lines or "").splitlines(): raw = line.strip() if not raw or raw.startswith("#"): continue - match = _DOUYIN_LIVE_URL_RE.search(raw) + match = _DOUYIN_LIVE_ROOM_RE.search(raw) if not match: continue + room_id = match.group(1) tail = raw[match.end() :].strip(" ,,;;||-—::") title = _clean_source_title(tail) - if title: - return title - parts = re.split(r"[,,||]", raw, maxsplit=1) - if len(parts) > 1: - title = _clean_source_title(parts[1]) - if title: - return title + if not title: + parts = re.split(r"[,,||]", raw, maxsplit=1) + if len(parts) > 1: + title = _clean_source_title(parts[1]) + entries.append( + { + "room_id": room_id, + "source_url": f"https://live.douyin.com/{room_id}", + "source_title": title, + } + ) + return entries + + +def _source_title_from_url_lines(url_lines: str) -> str: + for entry in _url_entries_from_lines(url_lines): + if entry["source_title"]: + return entry["source_title"] return "" def _source_title_from_log(recent_log: str) -> str: lines = [line.strip() for line in (recent_log or "").splitlines() if line.strip()] - for line in reversed(lines[-160:]): - for pattern in (_LABEL_TITLE_RE, _STATUS_TITLE_RE): + tail = lines[-240:] + for pattern in (_RECORDING_TITLE_RE, _LIVE_TITLE_RE): + for line in reversed(tail): match = pattern.search(line) if not match: continue title = _clean_source_title(match.group(1)) if title: return title + for line in reversed(tail): + if _ERROR_CONTEXT_RE.search(line): + continue + match = _LABEL_TITLE_RE.search(line) + if not match: + continue + title = _clean_source_title(match.group(1)) + if title: + return title + for line in reversed(tail): + match = _WAIT_TITLE_RE.search(line) or _STATUS_TITLE_RE.search(line) + if not match: + continue + title = _clean_source_title(match.group(1)) + if title: + return title return "" +def _current_room_id_from_log(recent_log: str) -> str: + room_id = "" + for match in _DOUYIN_LIVE_ROOM_RE.finditer(recent_log or ""): + room_id = match.group(1) + return room_id + + +def _normalize_title_for_match(value: str) -> str: + return re.sub(r"\s+", "", _clean_source_title(value)).casefold() + + +def _entry_for_room(entries: list[dict[str, str]], room_id: str) -> dict[str, str] | None: + if not room_id: + return None + for entry in entries: + if entry.get("room_id") == room_id: + return entry + return None + + +def _entry_for_title(entries: list[dict[str, str]], title: str) -> dict[str, str] | None: + needle = _normalize_title_for_match(title) + if not needle: + return None + for entry in entries: + candidate = _normalize_title_for_match(entry.get("source_title", "")) + if not candidate: + continue + if candidate == needle: + return entry + if len(candidate) >= 3 and len(needle) >= 3 and (candidate in needle or needle in candidate): + return entry + return None + + def extract_douyin_source_meta(url_lines: str = "", recent_log: str = "") -> dict[str, Any]: - text = f"{url_lines or ''}\n{recent_log or ''}" - room_match = _DOUYIN_LIVE_URL_RE.search(text) - room_id = room_match.group(1) if room_match else "" - source_url = f"https://live.douyin.com/{room_id}" if room_id else "" - title = _source_title_from_url_lines(url_lines) or _source_title_from_log(recent_log) + entries = _url_entries_from_lines(url_lines) + log_room_id = _current_room_id_from_log(recent_log) + log_title = _source_title_from_log(recent_log) + matched_entry = _entry_for_title(entries, log_title) or _entry_for_room(entries, log_room_id) + source_ambiguous = False + source_current = False + + if matched_entry: + room_id = matched_entry["room_id"] + source_url = matched_entry["source_url"] + title = log_title or matched_entry.get("source_title", "") + source_current = bool(log_room_id or log_title) + elif log_room_id: + room_id = log_room_id + source_url = f"https://live.douyin.com/{room_id}" + title = log_title + source_current = True + elif len(entries) == 1: + room_id = entries[0]["room_id"] + source_url = entries[0]["source_url"] + title = entries[0].get("source_title", "") or log_title + elif log_title: + room_id = "" + source_url = "" + title = log_title + source_ambiguous = bool(entries) + source_current = True + elif entries: + room_id = entries[0]["room_id"] + source_url = entries[0]["source_url"] + title = entries[0].get("source_title", "") + source_ambiguous = len(entries) > 1 + else: + room_id = "" + source_url = "" + title = "" + display = title or (f"抖音直播间 {room_id}" if room_id else "") return { "source_title": title, "source_room_id": room_id, "source_url": source_url, "source_display": display, + "source_ambiguous": source_ambiguous, + "source_current": source_current, } diff --git a/d2ypp2/src/network_preflight.py b/d2ypp2/src/network_preflight.py index 16996c6..5b4e73d 100644 --- a/d2ypp2/src/network_preflight.py +++ b/d2ypp2/src/network_preflight.py @@ -204,6 +204,11 @@ def _douyin_ok(probes: list[dict[str, Any]]) -> bool: return any(item.get("ok") for item in probes if item.get("target") == "douyin") +def _push_proxy_from_http_proxy(proxy: str) -> str: + suffix = (proxy or "").split("://", 1)[-1] + return f"socks5://{suffix}" if suffix else "" + + def _proxy_env(proxy: str) -> dict[str, str]: bypass = ",".join( [ @@ -229,6 +234,11 @@ def _proxy_env(proxy: str) -> dict[str, str]: "HTTPS_PROXY": proxy, "all_proxy": proxy, "ALL_PROXY": proxy, + "YOUTUBE_PUSH_PROXY": _push_proxy_from_http_proxy(proxy), + "LIVE_YOUTUBE_PUSH_PROXY": _push_proxy_from_http_proxy(proxy), + "YOUTUBE_PUSH_PROXY_MODE": "proxychains", + "LIVE_YOUTUBE_PUSH_PROXY_MODE": "proxychains", + "YOUTUBE_PUSH_PROXY_AUTO": "0", "no_proxy": bypass, "NO_PROXY": bypass, "LIVE_YOUTUBE_NETWORK_MODE": "shellcrash", diff --git a/d2ypp2/src/web_process_backend.py b/d2ypp2/src/web_process_backend.py index 709c26f..5c70745 100644 --- a/d2ypp2/src/web_process_backend.py +++ b/d2ypp2/src/web_process_backend.py @@ -513,7 +513,23 @@ def build_pm2_start_command(base_dir: Path, process: str, script: str) -> Option "PYTHONUNBUFFERED=1", f"PYTHONPATH={shlex.quote(str(base_dir))}:${{PYTHONPATH:-}}", ] - for key in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "no_proxy", "NO_PROXY", "LIVE_YOUTUBE_NETWORK_MODE"): + for key in ( + "http_proxy", + "https_proxy", + "all_proxy", + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "no_proxy", + "NO_PROXY", + "LIVE_YOUTUBE_NETWORK_MODE", + "YOUTUBE_PUSH_PROXY", + "LIVE_YOUTUBE_PUSH_PROXY", + "YOUTUBE_PUSH_PROXY_MODE", + "LIVE_YOUTUBE_PUSH_PROXY_MODE", + "YOUTUBE_PUSH_PROXY_AUTO", + "SHELLCRASH_ATTACH_FFMPEG", + ): value = os.environ.get(key) if value: env_bits.append(f"{key}={shlex.quote(value)}") diff --git a/d2ypp2/src/youtube_live_store.py b/d2ypp2/src/youtube_live_store.py index b813f99..ada77ab 100644 --- a/d2ypp2/src/youtube_live_store.py +++ b/d2ypp2/src/youtube_live_store.py @@ -10,6 +10,8 @@ import uuid from pathlib import Path from typing import Any +from src.douyin_source_display import extract_douyin_source_meta + from src.control_plane import CONFIG_DIR _DB_NAME = "hub_state.sqlite" @@ -591,8 +593,12 @@ def record_process_observation( if _payload_indicates_process_inactive(payload): return finish_active_events(process, reason=str(payload.get("business_note") or payload.get("raw_status") or "process inactive"), db_path=db_path) - source_url = extract_first_url(url_lines) - source_room_id = extract_source_room_id(url_lines, payload.get("recent_log"), payload.get("recent_error")) + source_meta = extract_douyin_source_meta( + url_lines, + "\n".join(str(payload.get(key) or "") for key in ("recent_log", "recent_error")), + ) + source_url = str(source_meta.get("source_url") or extract_first_url(url_lines)) + source_room_id = str(source_meta.get("source_room_id") or extract_source_room_id(url_lines, payload.get("recent_log"), payload.get("recent_error"))) conn = _connect(db_path) try: row = _upsert_event( diff --git a/d2ypp2/src/youtube_quality_guard.py b/d2ypp2/src/youtube_quality_guard.py index 7400f0e..2b3afcd 100644 --- a/d2ypp2/src/youtube_quality_guard.py +++ b/d2ypp2/src/youtube_quality_guard.py @@ -126,12 +126,12 @@ def build_youtube_quality_guard_report( score, issues = _process_score(row, metrics) cfg = config_by_process.get(process) or {} source_meta = extract_douyin_source_meta(cfg.get("url_lines", ""), str(row.get("recent_log") or "")) - source_title = str(row.get("source_title") or source_meta.get("source_title") or "").strip() - source_room_id = str(row.get("source_room_id") or source_meta.get("source_room_id") or "").strip() - source_url = str(row.get("source_url") or source_meta.get("source_url") or "").strip() + source_title = str(source_meta.get("source_title") or row.get("source_title") or "").strip() + source_room_id = str(source_meta.get("source_room_id") or row.get("source_room_id") or "").strip() + source_url = str(source_meta.get("source_url") or row.get("source_url") or "").strip() source_display = str( - row.get("source_display") - or source_meta.get("source_display") + source_meta.get("source_display") + or row.get("source_display") or source_title or (f"抖音直播间 {source_room_id}" if source_room_id else "") ).strip() diff --git a/d2ypp2/tests/test_douyin_source_display.py b/d2ypp2/tests/test_douyin_source_display.py index 9c669e8..5b93087 100644 --- a/d2ypp2/tests/test_douyin_source_display.py +++ b/d2ypp2/tests/test_douyin_source_display.py @@ -31,6 +31,78 @@ class DouyinSourceDisplayTests(unittest.TestCase): self.assertEqual(meta["source_room_id"], "723267141877") self.assertEqual(meta["source_display"], "抖音直播间 723267141877") + def test_prefers_current_log_title_over_first_configured_room(self) -> None: + meta = extract_douyin_source_meta( + "\n".join( + [ + "https://live.douyin.com/11111111, 主播: 已下播的旧直播间", + "https://live.douyin.com/22222222, 主播: 当前推流主播", + ] + ), + "frame= 100 speed=1.00x\n序号2 当前推流主播 正在直播中...\nframe= 200 speed=1.00x", + ) + + self.assertEqual(meta["source_title"], "当前推流主播") + self.assertEqual(meta["source_room_id"], "22222222") + self.assertEqual(meta["source_url"], "https://live.douyin.com/22222222") + self.assertEqual(meta["source_display"], "当前推流主播") + self.assertTrue(meta["source_current"]) + self.assertFalse(meta["source_ambiguous"]) + + def test_prefers_last_room_url_seen_in_log(self) -> None: + meta = extract_douyin_source_meta( + "\n".join( + [ + "https://live.douyin.com/11111111, 主播: 旧直播间", + "https://live.douyin.com/22222222, 主播: 当前直播间", + ] + ), + "检测 https://live.douyin.com/11111111\n切换到 https://live.douyin.com/22222222 开始推流", + ) + + self.assertEqual(meta["source_room_id"], "22222222") + self.assertEqual(meta["source_url"], "https://live.douyin.com/22222222") + self.assertTrue(meta["source_current"]) + + def test_recording_line_wins_over_later_waiting_and_error_lines(self) -> None: + meta = extract_douyin_source_meta( + "\n".join( + [ + "https://live.douyin.com/11111111, 主播: 错误里的主播", + "https://live.douyin.com/22222222, 主播: 当前推流主播", + "https://live.douyin.com/33333333, 主播: 后面等待主播", + ] + ), + "\n".join( + [ + "正在录制 1 个: 当前推流主播[原画 0:25:05][FFmpeg] frame=45112 speed=1x", + "序号3 后面等待主播 等待直播...", + "Error message: Douyin web data fetch error", + "序号1 网址内容获取失败,进行重试中...获取失败的地址是:('原画', 'https://live.douyin.com/11111111', '主播: 错误里的主播')", + ] + ), + ) + + self.assertEqual(meta["source_title"], "当前推流主播") + self.assertEqual(meta["source_room_id"], "22222222") + self.assertEqual(meta["source_url"], "https://live.douyin.com/22222222") + self.assertTrue(meta["source_current"]) + + def test_marks_multiple_configured_rooms_ambiguous_without_current_log(self) -> None: + meta = extract_douyin_source_meta( + "\n".join( + [ + "https://live.douyin.com/11111111, 主播: 旧直播间", + "https://live.douyin.com/22222222, 主播: 当前直播间", + ] + ), + "frame= 100 speed=1.00x", + ) + + self.assertEqual(meta["source_room_id"], "11111111") + self.assertTrue(meta["source_ambiguous"]) + self.assertFalse(meta["source_current"]) + if __name__ == "__main__": unittest.main() diff --git a/d2ypp2/tests/test_network_preflight.py b/d2ypp2/tests/test_network_preflight.py index fcfcd21..3db7a81 100644 --- a/d2ypp2/tests/test_network_preflight.py +++ b/d2ypp2/tests/test_network_preflight.py @@ -61,6 +61,9 @@ class NetworkPreflightTests(unittest.TestCase): self.assertEqual(result["network_profile"], "shellcrash_proxy") self.assertEqual(os.environ.get("LIVE_YOUTUBE_NETWORK_MODE"), "shellcrash") self.assertEqual(os.environ.get("HTTP_PROXY"), "http://127.0.0.1:7890") + self.assertEqual(os.environ.get("YOUTUBE_PUSH_PROXY"), "socks5://127.0.0.1:7890") + self.assertEqual(os.environ.get("YOUTUBE_PUSH_PROXY_MODE"), "proxychains") + self.assertEqual(os.environ.get("YOUTUBE_PUSH_PROXY_AUTO"), "0") def test_ffmpeg_attach_off_keeps_soft_router_direct_even_if_shellcrash_runs(self) -> None: def fake_probe(url: str, **kwargs): diff --git a/d2ypp2/tests/test_web_process_backend.py b/d2ypp2/tests/test_web_process_backend.py index b18c2c8..d767373 100644 --- a/d2ypp2/tests/test_web_process_backend.py +++ b/d2ypp2/tests/test_web_process_backend.py @@ -42,13 +42,26 @@ class WebProcessBackendTests(unittest.TestCase): script = base_dir / "youtube.py" script.write_text("print('ok')\n", encoding="utf-8") - with patch.dict("os.environ", {"https_proxy": "http://127.0.0.1:7890", "LIVE_YOUTUBE_NETWORK_MODE": "shellcrash"}, clear=False): + with patch.dict( + "os.environ", + { + "https_proxy": "http://127.0.0.1:7890", + "LIVE_YOUTUBE_NETWORK_MODE": "shellcrash", + "YOUTUBE_PUSH_PROXY": "socks5://127.0.0.1:7890", + "YOUTUBE_PUSH_PROXY_MODE": "proxychains", + "YOUTUBE_PUSH_PROXY_AUTO": "0", + }, + clear=False, + ): cmd = build_pm2_start_command(base_dir, "youtube", "youtube.py") self.assertIsNotNone(cmd) assert cmd is not None self.assertIn("https_proxy=http://127.0.0.1:7890", cmd) self.assertIn("LIVE_YOUTUBE_NETWORK_MODE=shellcrash", cmd) + self.assertIn("YOUTUBE_PUSH_PROXY=socks5://127.0.0.1:7890", cmd) + self.assertIn("YOUTUBE_PUSH_PROXY_MODE=proxychains", cmd) + self.assertIn("YOUTUBE_PUSH_PROXY_AUTO=0", cmd) def test_preferred_python_interpreter_falls_back_to_system_python_when_venv_is_missing(self) -> None: with tempfile.TemporaryDirectory() as tmp: diff --git a/d2ypp2/tests/test_youtube_push_config.py b/d2ypp2/tests/test_youtube_push_config.py index bd585f3..5ab0a99 100644 --- a/d2ypp2/tests/test_youtube_push_config.py +++ b/d2ypp2/tests/test_youtube_push_config.py @@ -6,6 +6,7 @@ from pathlib import Path from unittest.mock import patch from douyin_youtube_ffplay import ( + _ffmpeg_env_with_push_proxy, _ffmpeg_stats_args, _normalize_push_proxy_mode, _proxychains_proxy_line, @@ -112,6 +113,35 @@ class YoutubePushConfigTests(unittest.TestCase): self.assertEqual(_resolve_youtube_push_proxy(), "") self.assertEqual(_normalize_push_proxy_mode("direct"), "off") + def test_shellcrash_auto_proxy_prefers_socks_for_proxychains(self) -> None: + with ( + patch.dict("os.environ", {}, clear=True), + patch("douyin_youtube_ffplay._is_local_tcp_open", return_value=True), + ): + self.assertEqual(_resolve_youtube_push_proxy(), "socks5://127.0.0.1:7890") + + def test_proxychains_ffmpeg_env_strips_generic_http_proxy(self) -> None: + with patch.dict( + "os.environ", + { + "HTTP_PROXY": "http://127.0.0.1:7890", + "HTTPS_PROXY": "http://127.0.0.1:7890", + "ALL_PROXY": "http://127.0.0.1:7890", + "LIVE_YOUTUBE_NETWORK_MODE": "shellcrash", + }, + clear=True, + ): + env = _ffmpeg_env_with_push_proxy( + "socks5://127.0.0.1:7890", + "proxychains", + use_proxychains=True, + ) + + self.assertNotIn("HTTP_PROXY", env) + self.assertNotIn("HTTPS_PROXY", env) + self.assertNotIn("ALL_PROXY", env) + self.assertEqual(env.get("LIVE_YOUTUBE_NETWORK_MODE"), "shellcrash") + def test_proxychains_proxy_line_parses_http_and_socks(self) -> None: self.assertEqual( _proxychains_proxy_line("http://user:pass@127.0.0.1:7890"), diff --git a/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx b/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx index e6c96b3..684b6c7 100644 --- a/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx +++ b/d2ypp2/web-console/components/live-product/LiveProcessLiveLogCard.tsx @@ -25,6 +25,8 @@ type StatusPayload = { source_room_id?: string; source_url?: string; source_display?: string; + source_ambiguous?: boolean; + source_current?: boolean; }; function fmtDuration(sec: number): string { @@ -99,6 +101,9 @@ export function LiveProcessLiveLogCard({ const [sourceRoomId, setSourceRoomId] = useState(""); const [sourceUrl, setSourceUrl] = useState(""); const [sourceDisplay, setSourceDisplay] = useState(""); + const [sourceAmbiguous, setSourceAmbiguous] = useState(false); + const [sourceCurrent, setSourceCurrent] = useState(false); + const [isPushing, setIsPushing] = useState(false); const [paused, setPaused] = useState(false); const [liveSince, setLiveSince] = useState(null); const [nowTick, setNowTick] = useState(0); @@ -114,13 +119,35 @@ export function LiveProcessLiveLogCard({ const douyinHints = extractDouyinRoomHints(urlListText); const onlineNow = /^(online|running)$/i.test(processStatus); const roomFromLog = extractDouyinCurrentRoomFromLog(recentLog); - const fallbackUrl = extractDouyinLiveUrls(urlListText)[0] ?? ""; - const primaryRoomId = sourceRoomId || roomFromLog || (fallbackUrl.match(/live\.douyin\.com\/([a-zA-Z0-9_-]+)/i)?.[1] ?? null); - const primaryUrl = sourceUrl || (primaryRoomId ? `https://live.douyin.com/${primaryRoomId}` : fallbackUrl || null); + const fallbackUrls = extractDouyinLiveUrls(urlListText); + const fallbackUrl = fallbackUrls[0] ?? ""; + const pushingNow = isPushing || ["streaming", "relay_slow"].includes(businessStatus.trim().toLowerCase()); + const suppressAmbiguousBackend = sourceAmbiguous && pushingNow && !sourceCurrent; + const backendRoomId = suppressAmbiguousBackend ? "" : sourceRoomId; + const backendUrl = suppressAmbiguousBackend ? "" : sourceUrl; + const suppressAmbiguousFallback = + fallbackUrls.length > 1 && + pushingNow && + !backendUrl && + !backendRoomId && + !roomFromLog && + (sourceAmbiguous || !!sourceDisplay || !!sourceTitle); + const primaryRoomId = + backendRoomId || + roomFromLog || + (!suppressAmbiguousFallback ? fallbackUrl.match(/live\.douyin\.com\/([a-zA-Z0-9_-]+)/i)?.[1] ?? null : null); + const primaryUrl = + backendUrl || + (backendRoomId ? `https://live.douyin.com/${backendRoomId}` : "") || + (roomFromLog ? `https://live.douyin.com/${roomFromLog}` : "") || + (!suppressAmbiguousFallback ? fallbackUrl || null : null); + const localSourceLabel = suppressAmbiguousBackend + ? douyinSourceDisplayFrom("", recentLog) + : douyinSourceDisplayFrom(urlListText, recentLog); const primarySourceLabel = - sourceDisplay || - sourceTitle || - douyinSourceDisplayFrom(urlListText, recentLog) || + (suppressAmbiguousBackend ? "" : sourceDisplay) || + (suppressAmbiguousBackend ? "" : sourceTitle) || + localSourceLabel || (primaryRoomId ? `抖音直播间 ${primaryRoomId}` : ""); const youtubeKeyRejected = businessStatus.trim().toLowerCase() === "youtube_key_rejected"; @@ -150,6 +177,9 @@ export function LiveProcessLiveLogCard({ setSourceRoomId(data.source_room_id || ""); setSourceUrl(data.source_url || ""); setSourceDisplay(data.source_display || ""); + setSourceAmbiguous(!!data.source_ambiguous); + setSourceCurrent(!!data.source_current); + setIsPushing(!!data.is_pushing); const online = /^(online|running)$/i.test(ps); if (online && !prevOnlineRef.current) { setLiveSince(Date.now()); @@ -169,6 +199,9 @@ export function LiveProcessLiveLogCard({ setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); + setSourceAmbiguous(false); + setSourceCurrent(false); + setIsPushing(false); } finally { pullInFlightRef.current = false; if (pullQueuedRef.current) { @@ -194,6 +227,9 @@ export function LiveProcessLiveLogCard({ setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); + setSourceAmbiguous(false); + setSourceCurrent(false); + setIsPushing(false); setLiveSince(null); prevOnlineRef.current = false; return; @@ -209,6 +245,9 @@ export function LiveProcessLiveLogCard({ setSourceRoomId(""); setSourceUrl(""); setSourceDisplay(""); + setSourceAmbiguous(false); + setSourceCurrent(false); + setIsPushing(false); setLiveSince(null); prevOnlineRef.current = false; void pull(); diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx index a4eb5fe..4da4b9c 100644 --- a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx @@ -187,15 +187,39 @@ function laneDraftsFromChannels(channels: YoutubeProChannel[]): Record [channel.id, laneDraftFromChannel(channel)])); } +function isLivePushingRow(row?: LiveProcRow): boolean { + const business = (row?.business_status || "").trim().toLowerCase(); + return !!row?.is_pushing || business === "streaming" || business === "relay_slow"; +} + function douyinSourceDisplayFor(row?: LiveProcRow, urlLines = "", logText = ""): string { - const fromBackend = (row?.source_display || row?.source_title || "").trim(); - if (fromBackend) return fromBackend; + const suppressAmbiguousBackend = !!row?.source_ambiguous && isLivePushingRow(row) && !row?.source_current; + if (!suppressAmbiguousBackend) { + const fromBackend = (row?.source_display || row?.source_title || "").trim(); + if (fromBackend) return fromBackend; + } else { + const fromLogOnly = logText ? douyinSourceDisplayFrom("", logText).trim() : ""; + if (fromLogOnly) return fromLogOnly; + return ""; + } const fromLocal = douyinSourceDisplayFrom(urlLines, logText).trim(); if (fromLocal) return fromLocal; const roomId = (row?.source_room_id || "").trim(); return roomId ? `抖音直播间 ${roomId}` : ""; } +function douyinSourceUrlFor(row?: LiveProcRow, urlLines = ""): string { + const backendUrl = (row?.source_url || "").trim(); + if (backendUrl) return backendUrl; + const urls = extractDouyinLiveUrls(urlLines); + const suppressAmbiguousLocal = + isLivePushingRow(row) && + (row?.source_ambiguous || !!row?.source_display || !!row?.source_title) && + urls.length > 1; + if (suppressAmbiguousLocal) return ""; + return urls[0] ?? ""; +} + type LiveProcRow = { pm2: string; script?: string; @@ -214,6 +238,8 @@ type LiveProcRow = { source_room_id?: string; source_url?: string; source_display?: string; + source_ambiguous?: boolean; + source_current?: boolean; }; type YoutubeLiveAlert = { @@ -2772,7 +2798,7 @@ export function LiveYoutubeUnmannedView({ const laneKeyText = sel ? activeLaneDraft?.streamKey ?? c.streamKey ?? "" : c.streamKey ?? ""; const laneUrls = nonCommentUrlLinesOf(laneUrlText); const douyinUrls = extractDouyinLiveUrls(laneUrlText); - const dUrl = douyinUrls[0]; + const dUrl = douyinSourceUrlFor(row, laneUrlText); const suf = parseYoutubeStreamKeySuffix(`key = ${laneKeyText}`); const rowOnline = pm2StatusOnline(st); const laneIndex = channels.findIndex((row) => row.id === c.id); diff --git a/d2ypp2/web-console/lib/youtubeConfigUtils.ts b/d2ypp2/web-console/lib/youtubeConfigUtils.ts index 3918425..12bb174 100644 --- a/d2ypp2/web-console/lib/youtubeConfigUtils.ts +++ b/d2ypp2/web-console/lib/youtubeConfigUtils.ts @@ -77,11 +77,25 @@ export function extractDouyinSourceTitleFromUrlLines(urlIni: string): string { export function extractDouyinSourceTitleFromLog(logText: string): string { const lines = logText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-160); + const recording = /(?:正在录制|录制中)\s*\d*\s*个?\s*[::]\s*([^\[\r\n]{1,80})/i; + const live = /(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:正在直播中|正在直播|直播中|已开播|开始推流|录制中|推流中)/i; + const labeled = /(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*(.{1,80})/i; + const waiting = /(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|主播已下播|下播)/i; + const errorContext = /(?:获取失败|错误|异常|error|failed|exception)/i; + + for (const pattern of [recording, live]) { + for (let i = lines.length - 1; i >= 0; i -= 1) { + const title = cleanDouyinSourceTitle(lines[i].match(pattern)?.[1] || ""); + if (title) return title; + } + } for (let i = lines.length - 1; i >= 0; i -= 1) { - const line = lines[i]; - const labeled = line.match(/(?:主播|房间名|直播间|抖音源|源站|标题)\s*[::]\s*(.{1,80})/i); - const status = line.match(/(?:序号\s*\d+\s*)?(.{1,80}?)\s*(?:等待直播|正在直播|直播中|已开播|开始推流|主播已下播|下播|录制中|推流中)/i); - const title = cleanDouyinSourceTitle(labeled?.[1] || status?.[1] || ""); + if (errorContext.test(lines[i])) continue; + const title = cleanDouyinSourceTitle(lines[i].match(labeled)?.[1] || ""); + if (title) return title; + } + for (let i = lines.length - 1; i >= 0; i -= 1) { + const title = cleanDouyinSourceTitle(lines[i].match(waiting)?.[1] || ""); if (title) return title; } return ""; diff --git a/d2ypp2/web.py b/d2ypp2/web.py index 1537387..eb834c4 100644 --- a/d2ypp2/web.py +++ b/d2ypp2/web.py @@ -1809,8 +1809,12 @@ async def _process_monitor_snapshot_from_info( status = str(info.get("process_status") or "").lower() online = status in {"online", "running", "launching"} read_logs = online or not light - log_lines = 12 if light else 40 - error_lines = 8 if light else 40 + if light and process_family(name) == "youtube": + log_lines = 80 + error_lines = 24 + else: + log_lines = 12 if light else 40 + error_lines = 8 if light else 40 if recent_log_override is not None and recent_error_override is not None: recent_log = recent_log_override